Skip to content

Made "record sent automation email" code more consistent#29399

Merged
troyciesco merged 2 commits into
mainfrom
evanhahn-ny-1459-automations-apis-recordemailsent-function-should-use-the
Jul 20, 2026
Merged

Made "record sent automation email" code more consistent#29399
troyciesco merged 2 commits into
mainfrom
evanhahn-ny-1459-automations-apis-recordemailsent-function-should-use-the

Conversation

@EvanHahn

Copy link
Copy Markdown
Contributor

closes https://linear.app/ghost/issue/NY-1459

automationsApi.recordEmailSent was different from the others: it hit the database directly. Now it's part of the automations repository just like the rest.

This cleanup should have no user impact.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3dda494d-811b-4ab6-b1ec-bef859b45745

📥 Commits

Reviewing files that changed from the base of the PR and between 91c589d and 95900d3.

📒 Files selected for processing (6)
  • ghost/core/core/server/services/automations/automations-api.ts
  • ghost/core/core/server/services/automations/automations-repository.ts
  • ghost/core/core/server/services/automations/database-automations-repository.ts
  • ghost/core/core/server/services/automations/poll.ts
  • ghost/core/test/unit/server/services/automations/automations-api.test.js
  • ghost/core/test/unit/server/services/automations/automations-repository.test.ts
💤 Files with no reviewable changes (1)
  • ghost/core/test/unit/server/services/automations/automations-api.test.js
🚧 Files skipped from review as they are similar to previous changes (4)
  • ghost/core/core/server/services/automations/automations-repository.ts
  • ghost/core/core/server/services/automations/poll.ts
  • ghost/core/test/unit/server/services/automations/automations-repository.test.ts
  • ghost/core/core/server/services/automations/database-automations-repository.ts

Walkthrough

The recordEmailSent contract moved to AutomationsRepository. The API delegates recording to the repository, whose transaction inserts recipient data and increments the related action revision’s sent count. Polling uses the shared repository type, and repository tests cover populated and null-member scenarios.

Suggested reviewers: cmraible

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: moving recordEmailSent into the automations repository for consistency.
Description check ✅ Passed The description accurately describes the repository refactor and expected lack of user impact.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch evanhahn-ny-1459-automations-apis-recordemailsent-function-should-use-the

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@nx-cloud

nx-cloud Bot commented Jul 16, 2026

Copy link
Copy Markdown

🤖 Nx Cloud AI Fix

Ensure the fix-ci command is configured to always run in your CI pipeline to get automatic fixes in future runs. For more information, please see https://nx.dev/ci/features/self-healing-ci


View your CI Pipeline Execution ↗ for commit 91c589d

Command Status Duration Result
nx run ghost:test:ci:integration ✅ Succeeded 2m 12s View ↗
nx run ghost:test:integration ✅ Succeeded 2m 42s View ↗
nx run ghost:test:legacy ✅ Succeeded 3m 8s View ↗
nx run ghost:test:e2e ✅ Succeeded 2m 30s View ↗
nx run @tryghost/admin:build ✅ Succeeded 5s View ↗
nx run-many -t test:unit -p ghost ✅ Succeeded 4s View ↗
nx run ghost-monorepo:lint:boundaries ✅ Succeeded <1s View ↗
nx run-many -t lint -p ghost,ghost-monorepo ✅ Succeeded 1s View ↗
nx run-many --target=build --projects=tag:publi... ✅ Succeeded <1s View ↗

💡 Verify your cache is correct by running tasks in a sandbox. Read docs ↗


☁️ Nx Cloud last updated this comment at 2026-07-20 18:51:28 UTC

return await knex.transaction(trx => retryStep(trx, step, retryAt));
},

async recordEmailSent(options): Promise<void> {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a diff showing what actually changed:

@@ -1,5 +1,7 @@
-await knex.transaction(async (transacting: Knex.Transaction) => {
-  await AutomatedEmailRecipient.add({
+await knex.transaction(async (trx) => {
+  const now = toDatabaseDate(new Date());
+  await trx("automated_email_recipients").insert({
+    id: ObjectId().toHexString(),
     member_id: options.memberId,
     member_uuid: options.memberUuid,
     member_email: options.memberEmail,
@@ -9,12 +11,14 @@
       ? { mailgun_message_id: options.mailgunMessageId }
       : {}),
     track_opens: options.trackOpens,
-  }, { transacting });
+    created_at: now,
+    updated_at: now,
+  });
 
-  await transacting("automation_action_revisions")
+  await trx("automation_action_revisions")
     .where("id", options.automationActionRevisionId)
     .update({
-      email_sent_count: transacting.raw("COALESCE(??, 0) + ?", [
+      email_sent_count: trx.raw("COALESCE(??, 0) + ?", [
         "email_sent_count",
         1,
       ]),

});

describe('recordEmailSent', function () {
it('records the recipient and increments the action revision count', async function () {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a diff showing what actually changed in this test:

-it("records the recipient and increments the action revision count in one transaction", async function () {
-  const emailSentCountExpression = Symbol("email_sent_count_expression");
-  const updateRevision = sinon.stub().resolves();
-  const whereRevision = sinon.stub().returns({ update: updateRevision });
-  const transacting = sinon.stub().withArgs("automation_action_revisions")
-    .returns({ where: whereRevision });
-  transacting.raw = sinon.stub().returns(emailSentCountExpression);
-  const transaction = sinon.stub(db.knex, "transaction").callsFake(
-    async (callback) => {
-      return await callback(transacting);
-    },
-  );
-  const addRecipient = sinon.stub(AutomatedEmailRecipient, "add").resolves();
+it("records the recipient and increments the action revision count", async function () {
+  const revision = await knex("automation_action_revisions").select("id")
+    .first();
+  assert(revision);
 
-  await automationsApi.recordEmailSent({
-    automationActionRevisionId: "revision-id",
+  await repo.recordEmailSent({
+    automationActionRevisionId: revision.id,
     mailgunMessageId: "mailgun-message-id",
     memberEmail: "member@example.com",
     memberId: "member-id",
@@ -22,22 +13,28 @@
     trackOpens: true,
   });
 
-  sinon.assert.calledOnce(transaction);
-  sinon.assert.calledOnceWithExactly(addRecipient, {
+  const recipient = await knex("automated_email_recipients").first();
+  assert.deepEqual(recipient, {
+    id: recipient.id,
+    automation_action_revision_id: revision.id,
     member_id: "member-id",
     member_uuid: "00000000-0000-4000-8000-000000000001",
     member_email: "member@example.com",
     member_name: "Test Member",
-    automation_action_revision_id: "revision-id",
     mailgun_message_id: "mailgun-message-id",
-    track_opens: true,
-  }, { transacting });
-  sinon.assert.calledOnceWithExactly(whereRevision, "id", "revision-id");
-  sinon.assert.calledOnceWithExactly(transacting.raw, "COALESCE(??, 0) + ?", [
-    "email_sent_count",
-    1,
-  ]);
-  sinon.assert.calledOnceWithExactly(updateRevision, {
-    email_sent_count: emailSentCountExpression,
+    delivered_at: null,
+    opened_at: null,
+    track_opens: 1,
+    created_at: recipient.created_at,
+    updated_at: recipient.updated_at,
   });
+  assert(ObjectId.isValid(recipient.id));
+  assert.equal(typeof recipient.created_at, "string");
+  assert.equal(recipient.updated_at, recipient.created_at);
+
+  const updatedRevision = await knex("automation_action_revisions")
+    .select("email_sent_count")
+    .where("id", revision.id)
+    .first();
+  assert.equal(updatedRevision.email_sent_count, 1);
 });

@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 64.28571% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.50%. Comparing base (9fd4070) to head (95900d3).

Files with missing lines Patch % Lines
...ver/services/automations/automations-repository.ts 0.00% 14 Missing ⚠️
...ces/automations/database-automations-repository.ts 95.83% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #29399      +/-   ##
==========================================
- Coverage   74.53%   74.50%   -0.04%     
==========================================
  Files        1602     1602              
  Lines      140399   140406       +7     
  Branches    17060    17057       -3     
==========================================
- Hits       104646   104609      -37     
- Misses      34733    34743      +10     
- Partials     1020     1054      +34     
Flag Coverage Δ
e2e-tests 76.58% <64.28%> (-0.04%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@EvanHahn
EvanHahn requested a review from troyciesco July 16, 2026 17:13
EvanHahn and others added 2 commits July 20, 2026 14:35
closes https://linear.app/ghost/issue/NY-1459

`automationsApi.recordEmailSent` was different from the others: it hit
the database directly. Now it's part of the automations repository just
like the rest.

This change should have no user impact.
@troyciesco
troyciesco force-pushed the evanhahn-ny-1459-automations-apis-recordemailsent-function-should-use-the branch from 91c589d to 95900d3 Compare July 20, 2026 18:41
@troyciesco
troyciesco merged commit 61a56c5 into main Jul 20, 2026
49 checks passed
@troyciesco
troyciesco deleted the evanhahn-ny-1459-automations-apis-recordemailsent-function-should-use-the branch July 20, 2026 18:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants