import fs from 'fs/promises'; import path from 'path'; import { select } from '@evershop/postgres-query-builder'; import { CONSTANTS } from '../../../../lib/helpers.js'; import { translate } from '../../../../lib/locale/translate/translate.js'; import { debug, error } from '../../../../lib/log/logger.js'; import { sendEmail } from '../../../../lib/mail/emailHelper.js'; import { pool } from '../../../../lib/postgres/connection.js'; import { getConfig } from '../../../../lib/util/getConfig.js'; import { getValue } from '../../../../lib/util/registry.js'; import { EventData } from '../../../../types/event.js'; import { getStoreLanguage } from '../../../setting/services/setting.js'; import { decorateAddressForEmail } from '../../services/addressEmailData.js'; import { getCarrier } from '../../services/carrier/registry.js'; import { getOrderEmailLink } from '../../services/orderEmailLink.js'; export const TEMPLATE = `{{#> emailLayout preheader=(t "Your order #\${number} is on the way." number=order.order_number)}}

{{t "Your order is on the way"}}

{{t "Order #\${number}" number=order.order_number}} · {{date order.created_at}}

{{#if shipment.tracking_number}}
{{#if carrierName}}

{{t "Carrier"}}: {{carrierName}}

{{/if}}

{{t "Tracking"}}: {{shipment.tracking_number}}

{{else}}

{{t "We'll send tracking details as soon as the carrier scans the package."}}

{{/if}} {{#if shippingAddress}}

{{t "Shipping to"}}

{{#each shippingAddress.formatted}}{{this}}
{{/each}}

{{/if}} {{#if items.length}}

{{t "Items in this shipment"}}

{{#each items}}{{/each}}
{{this.product_name}} · {{t "Qty"}} {{this.qty}}
{{/if}} {{#if trackingUrl}}{{> button href=trackingUrl label=(t "Track shipment")}}{{else}}{{> button href=trackOrderUrl label=(t "View your order")}}{{/if}} {{/emailLayout}}`; export default async function sendShipmentCreatedEmail( data: EventData<'shipment_created'> ) { try { if (data.notifyCustomer === false) return; const config = getConfig('system.notification_emails.shipment_created', { enabled: true }); if (config?.enabled === false) return; const shipment = await select() .from('shipment') .where('shipment_id', '=', data.shipmentId) .load(pool); if (!shipment) return; const order = await select() .from('order') .where('order_id', '=', shipment.shipment_order_id) .load(pool); if (!order || !order.customer_email) return; const shipmentItems = await select() .from('shipment_item') .where('shipment_id', '=', shipment.shipment_id) .execute(pool); if (shipmentItems.length === 0) return; const orderItems = await select() .from('order_item') .where( 'order_item_id', 'IN', shipmentItems.map((i) => i.order_item_id) ) .execute(pool); const oiByid = new Map(orderItems.map((oi) => [oi.order_item_id, oi])); const items = shipmentItems.map((si) => { const oi = oiByid.get(si.order_item_id); return { qty: si.qty, product_name: oi?.product_name ?? '', product_sku: oi?.product_sku ?? '' }; }); const carrierObj = getCarrier(shipment.carrier); const carrierName = carrierObj?.name ?? shipment.carrier ?? null; // Persisted carrier URL wins; aggregators populate `shipment.tracking_url` // from `LabelResult.trackingUrl` because they can't compose URLs at // resolve time. Falls back to `generateTrackingUrl(ctx)` for // single-carrier extensions that don't return a URL at purchase. const trackingUrl = shipment.tracking_url ?? (carrierObj?.generateTrackingUrl && shipment.tracking_number ? carrierObj.generateTrackingUrl({ trackingNumber: shipment.tracking_number, carrierShipmentId: shipment.carrier_shipment_id ?? undefined, metadata: shipment.carrier_metadata ?? undefined }) : null); const trackOrderUrl = getOrderEmailLink(order.uuid); let template; if (config?.templatePath) { const filePath = path.join(CONSTANTS.ROOTPATH, config.templatePath); try { await fs.access(filePath); template = await fs.readFile(filePath, 'utf8'); } catch { debug( `Shipment created email template not found at ${filePath}. Using default.` ); template = TEMPLATE; } } else { template = TEMPLATE; } // Off-request (event subscriber) — resolve the store locale explicitly (D7). const locale = await getStoreLanguage(); // The delivery address, as `formatted` lines plus the derived names // (spec § 3.6) — the same data the order confirmation prints. const shippingRow = order.shipping_address_id ? await select() .from('order_address') .where('order_address_id', '=', order.shipping_address_id) .load(pool) : null; const shippingAddress = shippingRow ? await decorateAddressForEmail(shippingRow, locale) : null; const dynamicData = await getValue('shipmentCreatedEmailData', { order, shippingAddress, shipment, items, carrierName, trackingUrl, trackOrderUrl }); const subject = translate( 'Your order #${number} is on the way', { number: String(order.order_number) }, locale ); const args = await getValue( 'shipmentCreatedEmailArguments', { to: order.customer_email, subject, template, data: dynamicData, locale }, { order, shipment } ); await sendEmail('shipment_created', args); } catch (e) { error(e); } }