Skip to content

Push Notifications ​

Flow ID: SY-35 | Module(s): src/Domains/Notification/, src/Rest/Notification/, application/models/Adv_mailer.php, ecommercen/helpers/shopmodule_helper.php | Complexity: High Last Updated: 2026-11-04 — 4.129.0 resync: citations re-anchored; previous: 2026-10-14 — ecommercen#930: the after-response send declares 3 s and every HTTP call of a send is capped by its deadline; a call with less than 1 s left is not started. 2026-10-13 — ecommercen#926: message and deliveries are stored atomically

Business Context ​

Customer notifications let the mobile apps (Velora Android and iOS) receive push messages through Firebase Cloud Messaging (FCM). Two kinds of message exist:

  • Order notifications (category orders) follow the order e-mails and SMS the customer already gets: order confirmation, the admin status-update "inform", and "ready for collection". They are transactional and are never held or capped.
  • Marketing campaigns (categories promos, news) are composed by staff on the admin page described in AD-61 Push Notification Campaigns. They need an express opt-in and obey a per-device daily cap and quiet hours.

The design is a channel-agnostic NotificationService that turns a logical notification into one queued delivery per consenting device (an outbox), and a Dispatcher that sends due deliveries. Push is the only channel today; e-mail and SMS keep their own paths (src/Domains/Notification/NotificationService.php:10-12). Nothing is sent until the shop enables push in Settings and the Firebase service-account secret is deployed (src/Domains/Notification/PushConfig.php:24-27).

The decision record is docs/decisions/559-customer-notifications.md. The shop-side settings page is documented in AD-13 Admin Settings.

API Reference ​

REST Endpoints (Modern Layer) ​

All five endpoints are guest-callable. A customer bearer token is optional: with one, the device is linked to that customer; without one, it is a signed-out device identified by its push token. Policy: Notification::class => ['defaults' => ['auth' => 'guest']] (application/config/rest_policies.php:1005-1007). Routes, with locale-prefixed twins, are at application/config/rest_routes.php:1774-1784. The API change is logged as REST version 1.111 (application/config/rest_api_versions.php:139).

MethodPathController methodPurpose
POST/rest/notification/devicesregisterDevice() (src/Rest/Notification/Controllers/Notification.php:72)Register or refresh an app install; idempotent on the token. Answers with the consent that applies
POST/rest/notification/devices/unregisterunregisterDevice() (:101)Disable the device and unlink it; always 200, also for an unknown token
GET/rest/notification/preferencespreferences() (:124)Signed in: the customer's consent. Signed out: the device's own, identified by the X-Device-Token header; 404 for an unknown device
POST/rest/notification/preferencessavePreferences() (:169)Save consent: three categories when signed in, the two marketing categories for a signed-out device (identified by token)
POST/rest/notification/openedopened() (:223)Record that the customer opened a delivery; counted once, only from the device it went to; always 200

Request rules:

  • registerDevice validates through DeviceRegistration::fromArray(): token (1-512 chars), kind (fcm), platform (android or ios), locale (el or el-GR shape; stored as the first two letters), optional appVersion (32) and deviceModel (100) (src/Domains/Notification/Device/DeviceRegistration.php:10-11,24-60). A failure answers 422 with the fields named (Notification.php:76-79).
  • savePreferences requires boolean promos and news and a consentVersion of 1-32 chars; orders is optional and defaults to true (Notification.php:173-178,190).
  • Invalid bearer is 401, not "signed out". customerId() returns false after a 401 when a bearer token is sent but invalid or expired, so an expired session cannot silently unlink the device from its customer and stop their order pushes (Notification.php:236-254). unregister and opened ignore the bearer and use the device token alone.
  • Throttle. registerDevice (by device token) and the POST of savePreferences (by device token, or customer:{id} when signed in) count every call, plus the IP,, and answer 429 with Retry-After when over budget (Notification.php:261-279). Realm notification-device; defaults 20 per device and 120 per IP per 600 s, from REST_NOTIFICATION_THROTTLE_MAX_PER_DEVICE, _MAX_PER_IP, _WINDOW_SECONDS and _ENABLED (src/Rest/Notification/container.php:12-19), using LoginThrottle on cache.l2 (:28-34).

Response shape of the consent (OpenAPI schema NotificationPreferences, src/Domains/Notification/Consent/Consent.php:8-19): scope (customer or device), orders, promos, news, consentVersion, updatedAt.

Legacy Entry Points ​

Order pushes are triggered from three legacy sites, not from a route:

SiteHook
Adv_mailer::order_complete()orderEmailEnabled() gates the customer e-mail, then notifyOrderEvent(..., OrderComplete) (application/models/Adv_mailer.php:168,187)
Adv_mailer::order_has_been_updated()same, event OrderUpdate with the new status (:210,222)
Adv_mailer::order_is_on_store()same, event OrderOnStore (:374,386)
sendSmsForOrderId() (store-ready SMS)replacesSms() before sending, orderEvent() after (ecommercen/helpers/shopmodule_helper.php:286-291,324)
sendSmsForOrder() (courier or store SMS from the admin inform)same; event is OrderOnStore for a store order, else OrderUpdate with status SENT (:371-379,448)

Code Flow ​

1. Order event to queued delivery ​

Adv_mailer::order_* / sendSmsForOrder*()                 [application/models/Adv_mailer.php:188,222,386 ; shopmodule_helper.php:324,448]
  |-- (SMS only) OrderNotifier::replacesSms()            [OrderNotifier.php:96]
  |       mode instead_of_sms AND customer has an order-consenting device -> push now, SMS skipped (helper returns sms_status 2)
  |-- OrderNotifier::orderEvent()                        [OrderNotifier.php:77]
  |       PushMode::Off -> nothing
  |       push(): one per order per request (pushedThisRequest)   [:133-138]
  |             texts per shop language, {serial}/{status} filled  [:146-160]
  |             NotificationService::notify()                     [:162]
  |                 PushConfig::isActive()? else null            [NotificationService.php:30]
  |                 DeviceStore::recipients()                    [:36]
  |                 OutboxStore::enqueue()  one transaction       [:63, OutboxStore.php:38-90]
  |                     INSERT IGNORE on dedupe_key, then one row per device
  |             dispatchAfterResponse(): DeferredTaskRunner task, cost 3 s, every HTTP call cut at its deadline     [OrderNotifier.php:36,192-211]
  |                 Dispatcher::dispatch(50, messageId, deadline)
  v
FCM  (or, if the deferred send did not run, the DispatchNotifications job picks it up within a minute)

OrderNotifier must never break the e-mail or SMS that called it: every failure is logged and swallowed (OrderNotifier.php:26,84-89,124-130), and orderNotifierOrNull() returns null when the container cannot build it (shopmodule_helper.php:255-265). Adv_mailer does the same through orderNotifier() (Adv_mailer.php:238-246).

2. Marketing campaign to queued delivery ​

Campaign save, send, test and cancel are driven from the admin page (AD-61); the domain side is CampaignService:

CampaignService::sendNow()                                [Campaign/CampaignService.php:61]
  |-- CampaignStore::transition(draft|scheduled -> queued)    [:69]
  |-- NotificationService::notify(request(campaign, Campaign))  [:75]
  |       dedupe key "campaign:{id}", target -> customerIds / customerSql / includeGuests   [:137-162]
  |-- no message (nobody can receive) or exception -> back to the previous status          [:77-82]

DispatchNotifications job (every minute)                  [Jobs/DispatchNotifications.php:39]
  |-- CampaignService::queueDueScheduled()                    [:45]
  |-- loop Dispatcher::dispatch(500, deadline) until a short batch or the time budget      [:48-55]

3. Dispatch and send-time re-check ​

Dispatcher::dispatch() (src/Domains/Notification/Dispatcher.php:50) returns 0 when the key is missing or push is off (:56-59), claims due deliveries with OutboxStore::claimDue() (:62) and handles each in handle() (:93). Every delivery is re-checked against the device as it is now:

CheckResultCitation
Device disabledskipped device_disabledDispatcher.php:97-99
Addressed to a customer but the device now belongs to someone else (or no one)skipped recipient_changed:103-105
Device no longer accepts the category (device_accepts, same SQL as queueing)skipped no_consent:108-110
Marketing inside quiet hoursrescheduled to the end of the window, not counted as an attempt:113-121
Marketing and the device already got MARKETING_DAILY_CAP todayskipped daily_cap:123-127
OtherwiseFcmClient::send() then record():130-131

record() (:134) maps the FCM outcome:

FCM resultDeliveryDevice
Sentsent, FCM message id stored; one PUSH row in the customer message history per message and customer (logToHistory(), :212-235)-
UNREGISTERED, SENDER_ID_MISMATCH, or INVALID_ARGUMENT whose BadRequest names message.tokenfaileddisabled with the lower-cased code as reason (:144-148; Push/FcmResult.php:9,54-58)
INVALID_ARGUMENT about any other fieldfailed, logged as an error (a defect of ours, every device would refuse it)kept (:150-159; FcmResult.php:61-64)
UNAVAILABLE, INTERNAL, QUOTA_EXCEEDED, HTTP 429, 5xx or transport error (status 0)retry with Retry-After or 60 s doubling per attempt, up to MAX_ATTEMPTS = 5, then failedkept (:161-165; FcmResult.php:10,66-72)
No OAuth token (FcmException)this delivery backed off like any error, the rest of the batch released untouchedDispatcher.php:76-82
Less than 1 s left before the deadline (FcmDeadlineReached)this delivery and the rest of the batch released untouched, no attempt counted; nothing was sentDispatcher.php:72-75

An unexpected exception on one delivery is retried with backoff without stranding the batch (:83-87,175-200).

4. FCM transport ​

  • Credentials come from the FCM_SERVICE_ACCOUNT_JSON environment variable (a deployment secret, never the registry), parsed by FcmCredentials::fromJson(); anything that is not a service_account key with project_id, client_email and private_key yields null, i.e. push inactive (Push/FcmCredentials.php:20-43, Notification/container.php:26-27).
  • FcmAccessTokenProvider::token() signs an RS256 JWT assertion (1 h lifetime) and exchanges it at https://oauth2.googleapis.com/token; the access token is cached in CachePool until 5 minutes before expiry (Push/FcmAccessTokenProvider.php:16-19,32-76).
  • FcmClient::send() posts to https://fcm.googleapis.com/v1/projects/{project}/messages:send; a transport error is a retryable result with status 0, never an exception (Push/FcmClient.php:13,27-77). The shared Guzzle client has a 3 s connect and 10 s request timeout (Push/FcmTimeouts.php:11-12, Notification/container.php:19-23). A send given a deadline lowers both to the time left before it, for the token request and the send alike (FcmTimeouts::until(), Push/FcmTimeouts.php:27-42; Dispatcher.php:71,130). A call is not started with less than 1 s left (MIN_CALL_SECONDS, :18): a call cut short reads as a failure, and a message FCM had already accepted would be sent again. FcmDeadlineReached is thrown instead, and the dispatcher releases that delivery and the rest of the batch with no attempt counted (Dispatcher.php:72-75).
  • FcmMessageFactory::build() always includes a notification block, flat-string data (type, route, deliveryId, and orderId for order messages), the Android channel id equal to the category, and for orders high priority, a 24 h TTL and a collapse key per order; marketing is normal priority with a 72 h TTL. An optional image sets the Android image and the APNs mutable-content (Push/FcmMessageFactory.php:15-66).

Data Model ​

Six tables, created by database/migrations/20261009120000_create_notification_tables.php (utf8mb4, because campaign texts carry emoji; each table is guarded by hasTable() so a fork that already has one does not fail). No customer_id column in these tables has a foreign key (the only keys are on notification_campaign_mui.parent_id, notification_delivery.message_id and device_id), so erasure deletes by customer_id explicitly (see Business Rules).

TablePurposeKey columns
notification_deviceOne row per app install, unique on token_hash (SHA-256; the token can exceed an indexable length)token, token_hash, kind, platform, customer_id (null = signed out), locale, promos_consent, news_consent, consent_version, consent_updated_at, last_seen_at, disabled_at, disabled_reason (:29-52)
notification_customer_consentOne row per customer; absent row = defaultscustomer_id (PK), orders (default 1), promos (0), news (0), consent_version, updated_at (:54-64)
notification_campaignA marketing campaignname, category, target, audience_id, customer_id, route, image, status, scheduled_at, queued_at, canceled_at, created_by (:66-85)
notification_campaign_muiCampaign title and body per language, FK to the campaign with cascadeparent_id, lang, title, body; unique (parent_id, lang) (:87-96)
notification_messageOne logical notificationcategory, event_type, campaign_id, customer_id, order_id, route, image, dedupe_key (unique), created_at (:98-115)
notification_deliveryOne row per device; the outboxmessage_id, device_id (both FK, cascade), customer_id, rendered title/body, status, attempts, not_before, claimed_at, fcm_message_id, error_code, error_message, sent_at, opened_at; unique (message_id, device_id) (:117-142)

Delivery statuses (Outbox/DeliveryStatus.php:7-12): queued, sending, retry, sent, failed, skipped. Campaign statuses (Campaign/CampaignStatus.php): draft, scheduled, queued, canceled; only draft and scheduled are editable.

The customer message history gains a channel: MessageChannel::PUSH (src/Domains/Customer/CustomerMessageHistory/MessageChannel.php:9), see AD-41 Customer Mail History.

Domain Layer ​

Modern Domain (src/Domains/Notification/) ​

FileResponsibility
NotificationService.phpnotify(): resolve recipients, create the message (deduped), queue one delivery per device in the right language, apply quiet-hours not_before for marketing
NotificationRequest.phpThe logical notification: category, event type, route, per-language texts, recipients (customerIds, customerSql, includeGuests), image, dedupe key
NotificationCategory.phporders, promos, news; isMarketing() is true for all but orders; the value is also the Android channel id
NotificationEvent.phpORDER_COMPLETE, ORDER_UPDATE, ORDER_ON_STORE, CAMPAIGN, CAMPAIGN_TEST; the order values equal the type the e-mail and SMS channels write to the message history; CAMPAIGN_TEST ignores cap and quiet hours (:16-34)
NotificationSettings.phpRegistry group NOTIFICATIONS reader with defaults (see Configuration)
PushConfig.php, PushMode.phpisActive() = key deployed and switch on; push mode off, with, instead_of_sms
QuietHours.phpDaily window, possibly across midnight; endIfInside() returns when it ends
Dispatcher.phpSend-time re-check, FCM send, retry and history (above)
Device/DeviceStore.phpRegistration upsert, unregister, disable, recipients(), and the single consent SQL rule acceptsSql()
Consent/ConsentStore.phpCustomer consent upsert and signed-out device consent
Outbox/OutboxStore.phpMessage and delivery persistence, claiming, state changes, stats, retention delete
Campaign/*CampaignService, CampaignStore, CampaignInput (validation), CampaignStatus, CampaignTarget (all, audience, customer)
Order/OrderNotifier.phpBridge from the order e-mail and SMS paths
Push/*FcmClient, FcmAccessTokenProvider, FcmCredentials, FcmMessageFactory, FcmResult, FcmException
Jobs/DispatchNotifications.php, Jobs/PruneNotifications.phpThe two scheduled jobs
container.phpWiring; registered as a container module at application/config/container/modules.php:38 (REST at :61)

REST (src/Rest/Notification/) ​

Controllers/Notification.php (extends Base_c, uses ApiEndpointTrait and TokenProtect) and container.php (throttle parameters and the rest.notification.throttle service).

Other ​

  • src/Support/Http/SameHostRequest.php: matches($origin, $referer, $ownHosts) is true only when the request's Origin (else Referer) names one of the site's own hosts; used as the CSRF check for the admin campaign POSTs (:22-37). See AD-61.
  • src/Domains/Customer/Customer/Erasure/Step/NotificationRecordsStep.php: part of the customer erasure (SY-09).

Configuration ​

Environment ​

VariableDefaultPurpose
FCM_SERVICE_ACCOUNT_JSONempty (push inactive)Firebase service-account key; should belong to an account holding only the FCM role (.env.example:95, Notification/container.php:27)
REST_NOTIFICATION_THROTTLE_ENABLEDtrueDevice and consent write throttle (.env.example:88)
REST_NOTIFICATION_THROTTLE_MAX_PER_DEVICE20Per device (or customer) per window
REST_NOTIFICATION_THROTTLE_MAX_PER_IP120Per IP per window
REST_NOTIFICATION_THROTTLE_WINDOW_SECONDS600Window length

Registry group NOTIFICATIONS ​

Edited on Settings, Customer notifications (AD-13). Every value has a default, so a shop that never opened the page keeps push off and every e-mail on (NotificationSettings.php:7-11).

KeyDefaultMeaning
PUSH_ENABLED0Master switch (:16,59-62)
EMAIL_<EVENT>onWhether the customer e-mail for an order event is sent; the admin notification e-mail is unaffected (:39-42,65-70; Adv_mailer.php:168-187)
PUSH_<EVENT>withPush mode per order event; off when push is disabled (:72-79)
PUSH_TITLE_<EVENT>, PUSH_BODY_<EVENT>language-file textPer language; {serial} and {status} placeholders. Defaults notifications.push.<EVENT>.title/body in adv_advisable_lang.php (:87-96)
MARKETING_DAILY_CAP1Marketing pushes per device per day; 0 allowed (:98-101,144-149)
QUIET_HOURS_START / QUIET_HOURS_END21:00 / 09:00Equal values disable quiet hours (:25-26,115-122)
TEST_CUSTOMER_IDSemptyCustomers whose devices receive a campaign test send (:124-130)
DEVICE_RETENTION_DAYS90Inactive or disabled devices deleted after this (:27,104-107)
HISTORY_RETENTION_MONTHS12Deliveries older than this deleted (:28,110-113)

EVENT is one of ORDER_COMPLETE, ORDER_UPDATE, ORDER_ON_STORE (NotificationEvent::orderEvents(), NotificationEvent.php:19-23).

Jobs ​

Group notifications in application/config/jobs.php:106-115; options registered at :229-230.

JobScheduleBehaviour
DispatchNotificationsevery minute, timeBudget option 50 s, grace 50 s, no retriesNo-op unless PushConfig::isActive(). Queues due scheduled campaigns, then dispatches 500 at a time until a short batch or the deadline. Budget is capped at claim timeout minus 60 s = 240 s (Jobs/DispatchNotifications.php:17-20,39-56)
PruneNotificationsdaily 03:40, grace 300 s, 3 retriesDeletes devices not seen or disabled for the retention period (their deliveries cascade), then deliveries past the history retention, then messages left with no delivery. Runs whether or not push is enabled (Jobs/PruneNotifications.php:34-40)

Client Extension Points ​

Per the decision record's "Client forks" section (docs/decisions/559-customer-notifications.md):

  • A fork with its own jobs.php must add the two job lines; a fork with its own rest_routes.php must add the notification routes.
  • A fork overriding Adv_mailer's order methods, sendSmsForOrder() or sendSmsForOrderId() must call OrderNotifier the same way.
  • A fork overriding the settings/notification_settings view or Adv_settings misses the new controls.
  • The admin controller follows the usual pair: Adv_push_notifications_admin (ecommercen/push_notifications/controllers/) and the empty Push_notifications_admin (application/modules/push_notifications/controllers/) for overrides.

Business Rules ​

  1. Consent is one SQL rule, used when queuing and again when sending. A device linked to a customer follows that customer's consent row; an absent row means orders on, marketing off. A signed-out device follows its own two marketing columns and can never receive an order notification (Device/DeviceStore.php:129-203; acceptsSql() is also embedded in claimDue(), Outbox/OutboxStore.php:126-130).
  2. Marketing to "everyone" includes signed-out devices only when the target is all (includeGuests), never for an audience or a single customer (DeviceStore.php:165-167; CampaignService.php:165).
  3. Language. A marketing message uses the device's locale; an order message prefers the customer's language, then the device locale; falling back to the shop's default language and then the first text given (NotificationService.php:63-69,98-103).
  4. Registration re-sets customer_id from the caller on every call. Signing in links the device, a signed-out call unlinks it, and a token already registered to another customer moves to the caller; the row is re-enabled (disabled_at cleared) (DeviceStore.php:28-55).
  5. Dedupe. ORDER_COMPLETE and ORDER_ON_STORE use the permanent key order:{id}:{event}:, so the store-ready e-mail and the job's later SMS are one push. ORDER_UPDATE carries a per-request nonce, so a resent "inform" or a status that returns to an earlier value is pushed again, as it is e-mailed again. At most one push per order per request (OrderNotifier.php:40-50,181-190). A campaign uses campaign:{id}.
  6. instead_of_sms skips the SMS only when the customer has at least one active device with orders consent, otherwise the SMS goes as before. A push already made for the event counts as the replacement; for ORDER_UPDATE that holds only within the same request (OrderNotifier.php:92-123).
  7. Cap and quiet hours apply to marketing only, and not to CAMPAIGN_TEST. Quiet hours hold a delivery until the window ends (the check runs at queue time, setting not_before, and again at send time). Both use the PHP default timezone (NotificationService.php:83-96, QuietHours.php:21-41).
  8. Delivery claiming. claimDue() selects due queued/retry rows plus sending rows whose claim is older than 300 s, then claims each with a conditional UPDATE, so two runners never send one delivery twice (Outbox/OutboxStore.php:19,82-120). A runner past its deadline releases unstarted claims without counting an attempt (:196-208).
  9. Cancel moves a draft, scheduled or queued campaign to canceled and marks its queued/retry deliveries skipped with code canceled; deliveries already sending or sent are not recalled (CampaignService.php:106-121, OutboxStore.php:295-304).
  10. Open tracking stamps opened_at only for a sent delivery that belongs to the reporting device and is not yet opened (OutboxStore.php:238-248).
  11. Account erasure deletes notification data. NotificationRecordsStep deletes the customer's deliveries, messages, devices and consent row, and clears customer_id on a single-customer campaign, which is kept for the merchant's records (Erasure/Step/NotificationRecordsStep.php:25-45; ErasureCoverage::RETAINED lists notification_campaign.name as staff-chosen text, ErasureCoverage.php:51). The step runs eighth of nine, between SessionsStep and AuditTrailStep (src/Domains/Customer/container.php:36,47).
  12. Retention. See the PruneNotifications job above. Campaign counts start from what is left after pruning (OutboxStore.php:210-212).

Known Issues & Security Gaps ​

  1. Fixed (ecommercen#926): a failure while queueing deliveries no longer leaves a dedupe-keyed message behind. OutboxStore::enqueue() stores the message and its deliveries in one transaction (Outbox/OutboxStore.php:38-90, Support/Transactional.php); a failed write or a short delivery count rolls both back and throws, so a retry is not refused as a duplicate and the failure is logged by the caller.
  2. Campaigns have no "sent" or "finished" state. After queued a campaign stays queued forever; progress is only visible in the delivery counts (Campaign/CampaignStatus.php).
  3. The CSRF origin check covers only the push-campaign POSTs. SameHostRequest is used in exactly one place, Adv_push_notifications_admin::refuseForeignPost() (ecommercen/push_notifications/controllers/Adv_push_notifications_admin.php:175-188), because csrf_protection is off platform-wide. Other admin POSTs, including the settings page that switches push on and edits the texts, have no such check.
  4. Throttle counts successful calls. withinBudget() records every call with recordFailure() (Notification.php:276), so a legitimate device that registers on every start plus consent saves shares the same 20-per-10-minutes budget as an abuser; the per-IP 120 is generous because carrier NAT puts many phones behind one address (decision D21).
  5. OneSignal is deprecated but still on the settings page. Nothing on the platform sends through it any more; the fields stay for one release and are marked deprecated (application/views/admin/settings/notification_settings.php:340-349, decision D20).
  6. opened and unregister are not throttled. They are identified by the device token alone (Notification.php:101-109,223-234); the token is the secret only the app holds.

Tests ​

FileTestsCovers
tests/Integration/Domains/Notification/NotificationFlowTest.php28Registration idempotency and sign-in linking, consent defaults, queueing per device and language, dedupe, quiet hours, cap, dead token and retry backoff, history once per customer, opens, audience campaigns and cancel, unsendable campaign stays draft, order dedupe and instead_of_sms, send-time consent and recipient re-checks, access-token failure, deadline release, batch robustness, INVALID_ARGUMENT handling, retention, erasure
tests/Unit/Domains/Notification/NotificationUnitTest.php10Unit rules of the domain classes
tests/Unit/Rest/Notification/Controllers/NotificationEndpointTest.php9Endpoint behaviour, 401 vs signed-out, validation, throttle answer
tests/Integration/Rest/Notification/NotificationThrottleContainerTest.php1Throttle service wiring
tests/Unit/Support/Http/SameHostRequestTest.php3Origin and Referer host matching

Coverage gaps: no test for the partial failure in Known Issue 1, none for the Adv_mailer hooks themselves (the order paths are exercised through OrderNotifier), and none against a real FCM endpoint (the payload shapes were validated against the staging project with validate_only, per the decision record).