When a publisher sends an email newsletter with email click analytics enabled, Ghost will replace all the links in the email's content with a link of the form `https://{site_url}/r/{redirect hash}?m={member UUID}`. When a member clicks on a link in their email, Ghost receives the request, redirects the user to the original link's URL, then updates some analytics data in the database.
### The details
The following deep-dive covers the link redirect flow from when the member clicks on a link in an email.
First, we lookup the redirect by the `/r/{hash}` value in the URL:
```
select `redirects`.* from `redirects` where `redirects`.`from` = ? limit ? undefined
```
If the redirect exists, the `LinkRedirectsService` emits a `RedirectEvent`, and then responds to the HTTP request with a 302.
The `LinkClickTrackingService` subscribes to the `RedirectEvent` and kicks off the analytics inserts/updates. First we grab the `uuid` from the `?m={uuid}` parameter and lookup the member by `uuid`:
```
select `members`.* from `members` where `members`.`uuid` = ? limit ? undefined
```
Then we insert a row into the `members_click_events` table to record the click:
select `members_click_events`.* from `members_click_events` where `members_click_events`.`id` = ? limit ? undefined
```
At this point, we emit a `MemberLinkClickEvent` with the member ID and `lastSeenAt` timestamp.
The `LastSeenAtUpdater` subscribes to the `MemberLinkClickEvent`. First, it checks if the `lastSeenAt` value has already been updated in the current day.
If it has, we stop here.
If it hasn't, we continue to update the member. First, we select the member by ID:
```
select `members`.* from `members` where `members`.`id` = ? limit ? undefined
```
Then we start a transaction and get a lock on the member for updating:
```
BEGIN; trx34
select `members`.* from `members` where `members`.`id` = ? limit ? for update trx34
```
Since we're editing the member, we will eventually need to emit a `member.edited` webhook with the standard includes (labels and newsletters) so we also query them here:
```
select `labels`.*, `members_labels`.`member_id` as `_pivot_member_id`, `members_labels`.`label_id` as `_pivot_label_id`, `members_labels`.`sort_order` as `_pivot_sort_order` from `labels` inner join `members_labels` on `members_labels`.`label_id` = `labels`.`id` where `members_labels`.`member_id` in (?) order by `sort_order` ASC for update trx34
```
Then we query the member's newsletters:
```
select `newsletters`.*, `members_newsletters`.`member_id` as `_pivot_member_id`, `members_newsletters`.`newsletter_id` as `_pivot_newsletter_id` from `newsletters` inner join `members_newsletters` on `members_newsletters`.`newsletter_id` = `newsletters`.`id` where `members_newsletters`.`member_id` in (?) order by `newsletters`.`sort_order` ASC for update trx34