Skip to main content

New-Style Launch Email (StyleLaunch, INFRA-836)

One-time email to a factory the first time it receives a work order for a style in a PO category.

Append new findings about this area here, not to .claude/rules/architecture.md.

What counts as "new"​

A launch is keyed on (styleId, factoryId, category) — @@unique on StyleLaunch.

  • Factory is PurchaseOrder.factoryId, which PO creation resolves from n8n's mtoWarehouse (Factory.factoryCode = mtoWarehouse, e.g. 288 = VN1, 247 = Aolong).
  • Category is PurchaseOrder.category. Only dress and scarf are in scope; jewelry never writes a row.
  • Category is part of the key because in Fulfil a factory's dress and scarf lines have different factory codes, but in MES both are saved under one factory (Aolong 247), with the PO category telling them apart.
  • ⚠️ A separate Aolong Scarf factory row also exists (INFRA-613). If scarf POs ever move between that row and Aolong (INFRA-633), every existing scarf style looks new to the destination row — copy the StyleLaunch rows across in that migration.

Trigger — after creation, never in the request path​

triggerStyleLaunchNotify in src/controllers/shipment/shipment.controller.ts#create is the last call in the if (_successfulShipments.length) block, next to triggerCarrierReconcile. By then batchCreateChunked has committed every chunk and the 201 is already sent. It's fire-and-forget: .catch → captureSendStyleLaunchEmailFailed. A fully-failed batch returns early and never reaches it.

It is not at PO creation (POST /purchaseorder/v1/create): WO numbers and CS… shipment numbers, which the email needs, only exist after POST /shipment/v1/create.

Flow (src/services/styleLaunch/styleLaunch.service.ts#notifyNewStyleLaunches)​

  1. Skip unless category ∈ {dress, scarf}, the factory resolved, and Gmail is configured (gmailClient.isEnabled()). Without Gmail nothing is claimed, so launches aren't recorded as announced when no email could go out.
  2. Candidate styles come from the request's SKUs via the controller's already-resolved skuNumber2SkuInfoMap — no DB read. This matters for 10k-shipment POs.
  3. StyleLaunchModel.findLaunchedStyleIds — one query; the common case (nothing new) stops here.
  4. Only for new styles: WorkorderModel.findMany({ where: { poRecName, styleId: { in } } }) and pick the smallest WO number per style via compareWorkOrderNumbers, which compares the -S<shipment>-<seq> parts numerically (pad4Digit overflows past 9999, so string order would put S10000 before S9999).
  5. Per style (isolated try/catch, so one failure never blocks another): claim → send → record outcome.

Claim + statuses​

StyleLaunchModel.claim = createMany({ data: [{ ...key, status: Claimed }], skipDuplicates: true }); count === 1 means this caller won and sends. The row must exist before sending — inserting after would let two concurrent same-factory requests (parallel POs, or an n8n retry of a still-running request) both send. Different factories never conflict (different keys); chunks of one PO don't either (the check runs once after all chunks).

StyleLaunchStatus: Baseline (seeded, never emailed) · Claimed (sending) · Sent (+notifiedAt) · Failed (+errorMessage, ≤500 chars, also Sentry) · SkippedNoRecipients (factory contacts empty/inactive). There is no automatic retry (deliberate, confirmed in grooming): any row means "launched". To resend, an admin deletes the row in the launch log and the next WO for that style re-triggers.

Every exit after a successful claim leaves a final status (PR #538 review): _launchOne wraps the send in try/catch and, if anything throws before the email goes out, best-effort records Failed (_markFailedQuietly) before rethrowing to Sentry. If the email was sent and only the Sent update fails, it is deliberately not marked Failed (the factory did get it) — that row stays Claimed, with the error in Sentry. So a row stuck in Claimed now means either that case, a process crash mid-send, or the DB being down when recording Failed.

Recipients​

All recipients live on the factory's FactoryConfiguration row with key style-launch-notify (FactoryConfigurationModel.getStyleLaunchNotifyRecipients → { to, cc }, sharing _findActiveConfig / _parseEmailList with work-order-pdfs-notify):

  • To = configValue, labelled "Email Notify TO List" in AdminJS on this key.
  • CC = ccEmails (nullable column added for this key), labelled "Email Notify CC List", minus anyone already in To (case-insensitive, first spelling kept). sendEmail gained an optional cc.
  • Empty To → SkippedNoRecipients (a CC-only row does not send).

The relabel and the CC field are driven by CC_EMAIL_FACTORY_CONFIG_KEYS (src/constants/factoryConfigurationKeys.ts): ConfigValueInput (edit) and ConfigValueShow (show) switch the configValue label, and CcEmailsInput / ConfigValueShow render ccEmails only for those keys — every other key keeps "Config Value" and never shows CC. ccEmails is hidden from the list and filters. The New handler (newActionHandler.ts, which bypasses the adapter) writes ccEmails explicitly.

History (don't reintroduce): recipients first came from STYLE_LAUNCH_BGC_RECIPIENTS / STYLE_LAUNCH_CC_RECIPIENTS env vars, then from a per-user User.styleLaunchAlert (AlertRecipientType None/To/Cc) dropdown sent for every factory. Both were replaced so each factory's To and CC are maintained in one place; migration 20261112100000_style_launch_cc_list_drop_user_alert adds ccEmails, updates the row description, and drops User.styleLaunchAlert + the AlertRecipientType enum.

  • Migration 20261110100000_seed_style_launch_notify_config seeds the key empty for every factory: migrations run on staging too, and staging's daily n8n test feed would otherwise email real vendors. Contacts are set per environment in AdminJS → System Administration → Factory Configuration.

Email​

gmailClient.notifyStyleLaunch — English subject, English + Chinese body. Subject <Factory> First <category> of <styleNumber> <styleNameEn> — "First dress of" for dress POs, "First scarf of" for scarf POs (poRecord.category is passed through; INFRA-757 originally said "dress" for both, changed after PR review). The factory prefix is factoryNameEn, falling back to factoryCode (same convention as notifyWorkOrderPdfsZip); the style part falls back to the style number alone. Body: the English subject as a heading, then a Chinese line 新款首单礼服:<style> (dress) or 新款首单围巾:<style> (scarf) for the factory, then a one-row table PO Number (poRecName) | PO Ref Number | PO Create Date (YYYY-MM-DD, UTC date, no time) | WO Number | Shipment (CustomerShipment.shipmentRecName, the Fulfil CS number — not shipmentNumber, which is Fulfil's numeric shipment id) | SKU, all HTML-escaped. Returns { success, error } rather than capturing, so the service can record the status.

Go-live baseline​

20261109100000_add_style_launch_table seeds one Baseline row per distinct (style, factory, category) from existing WorkOrder rows on dress/scarf POs — including soft-deleted WOs/POs (raw SQL bypasses softDelExtension), linking the factory's first WO (lowest workOrderId). It deliberately reads work orders, not the Style table: styles are synced from Airtable before any PO uses them, and seeding those would suppress their genuine first email.

Launch log (AdminJS)​

src/routers/admin/resources/styleLaunch/styleLaunch.ts — System Administration, admin-only, default list query, no new/edit; delete/bulkDelete allowed (manual resend). factoryNameEn / styleNumber are virtual columns filled by enrichStyleLaunchRecords (one batched Factory + Style query) because @adminjs/prisma renders relations as raw ids; sku and workOrderNumber are copied onto the row so the list reads without a relation lookup. A soft-deleted style falls back to the SKU prefix.

Scoped to the Current Factory (top-left selector), like Factory Configuration and the order lists: styleLaunchListBefore replaces any filters.factory in the query with getSelectedFactoryId() (no selection → all factories), and AdminJS's list action turns it into where.factoryId. So there is no Factory filter; with Aolong selected the list shows Aolong's dress and scarf launches (scarf is a category, not a factory — the separate Aolong Scarf Factory row from INFRA-613 has no launch rows). Filters: Style uses the default reference select, which is labelled by the Style resource's titleProperty: 'styleNumber' — without it AdminJS falls back to the first property (styleId) and lists ids. Note @adminjs/prisma search is a case-sensitive contains.

Testing gotchas​

  • utils/envConfig's env is frozen (envalid) — mock it with a plain { ...actual.env, ... } copy, not a Proxy (the proxy invariant throws).
  • models/workorder and models/style are mocked globally by src/models/mock; use vi.spyOn, not a spec-level vi.mock.