Appearance
Price Tracking
Flow ID: SY-04 | Module(s): src/Domains/Product/PriceTracking, src/Rest/Product | Complexity: Medium Last Updated: 2026-11-04 — 4.129.0 resync: #876
productPricesBulk()takes the caller's clock ($now) and the refresher passes its own; previous: 2026-10-13 — 4.127.0 resync: storefront fast pathstorefrontPrices()/storefrontPricesBulk()andPriceDropVerdictCalculator::noClaimVerdict()(#912), citation refresh; previous: 2026-10-02
Business Overview
The price tracking system records product price history to support EU Omnibus Directive compliance and customer-facing price graphs. The modern TrackPrices job (Advisable\Domains\Product\PriceTracking\Jobs\TrackPrices) runs every 5 minutes, calculates the current final price (including VAT, discounts, and time-limited special offers), and writes a new record to the price_tracking table only when the price has actually changed.
The stored history is then consumed by:
- Price history graphs on product cards and product pages (via
GraphService). - Reference price calculation for discount badges (EU Omnibus: lowest price in the last N days).
- REST API for frontend graph rendering (
GET /rest/product/price-tracking/graph[/{productId}]).
Architecture
Jobs\TrackPrices (every 5 min)
|
+--> Load VAT rates from shop_product_vats
+--> Batch-select active products (default 5000 per batch, ORDER BY id ASC)
| |
| +--> PriceCalculator::calculateFinalPrice() apply discounts + VAT (pure)
| +--> WriteService::recordBatch() change-only batch insert
| +--> refreshVerdicts($rows, $now) per page, after recording; failures are logged, never thrown
| +--> CurrentPrice::resolve() the real selling price per product
| +--> PriceDropRefresher::refresh() evaluates candidates in chunks of 500, upserts product_price_drop
|
+--> Repeat until all products processed
GraphService (on-demand, via DI)
|
+--> Repository -> SELECT price_tracking WHERE product_id = ? ORDER BY price_date DESC
+--> Build price timeline for N days
+--> Calculate reference price (Omnibus)
+--> Determine discount badge eligibility
REST Controller PriceTracking
|
+--> GET /rest/product/price-tracking (list)
+--> GET /rest/product/price-tracking/{id} (show)
+--> GET /rest/product/price-tracking/graph/{productId} (single graph)
+--> GET /rest/product/price-tracking/graph?productIds=1,2,3 (bulk graph)Key Files
| File | Role |
|---|---|
src/Domains/Product/PriceTracking/Jobs/TrackPrices.php | Modern JobCommand; entry point for the cron job |
src/Domains/Product/PriceTracking/PriceCalculator.php | Pure final-price math (regular + special discount + VAT) |
src/Domains/Product/PriceTracking/GraphService.php | Loads change rows and the real price, returns the graph payload (#876); storefrontPrices() / storefrontPricesBulk() are the legacy-storefront fast path (#912) |
src/Domains/Product/PriceTracking/PriceDropVerdictCalculator.php | Pure Omnibus timeline + reference-price + eligibility verdict (#876); couldQualify() and noClaimVerdict() short-circuit products that cannot qualify (#912) |
src/Domains/Product/PriceTracking/CurrentPrice.php | The real selling price via PriceResolver (#876) |
src/Domains/Product/PriceTracking/PriceDropRefresher.php | Evaluates the candidate products of a page and upserts their persisted verdict (CHUNK_SIZE = 500) (#876) |
src/Domains/Product/PriceTracking/PriceDropStore.php | Persistence of product_price_drop: TABLE, FRESH_FOR_SECONDS = 3600, existingIds(), idsWithQualifyingHistory(), upsert() (#876) |
src/Domains/Product/Product/Repository/Specification/FilterByPriceDrop.php | The filter[priceDrop] specification on GET /rest/product/product (reads product_price_drop) (#876) |
database/migrations/20261003120000_create_product_price_drop.php | Creates product_price_drop (guarded with hasTable) (#876) |
src/Domains/Product/PriceTracking/Options.php | Immutable DTO populated from the PRICE_TRACK registry group; fromRegistryInstance() (:47) is the one reader of that group, fromRegistry() (:29-35) delegates to it |
src/Domains/StorefrontConfig/PriceTracking/PriceTrackingConfigResolver.php | Builds the priceTracking section of GET /rest/storefront-config (#765); wired in StorefrontConfigProvider.php:46,78 |
src/Domains/Product/PriceTracking/WriteService.php | Insert/update/delete + recordBatch() for the job |
src/Domains/Product/PriceTracking/WriteData.php | Validated write DTO with snake/camel input flexibility |
src/Domains/Product/PriceTracking/Validator.php | productId/price/date validation rules |
src/Domains/Product/PriceTracking/Repository/WriteRepository.php | Persistence (insert_batch + last-price lookup) |
src/Domains/Product/PriceTracking/Repository/Repository.php | Read repository (Specification pattern) |
src/Domains/Product/PriceTracking/Repository/Entity.php | Entity DTO |
src/Domains/Product/PriceTracking/Service.php | Read service used by the REST controller |
src/Rest/Product/Controllers/PriceTracking.php | REST endpoints (index, show, item, graph, graphBulk) |
application/config/jobs.php | Job registration (FQCN; tracking queue, 5-min schedule) |
application/config/rest_routes.php | Route table for the REST endpoints (write routes intentionally commented) |
Code Flow
Price Recording (Job)
- Load VAT rates: query all rows from
shop_product_vatsand index by ID for fast lookup. - Batch processing loop (
do...while):- Select active, non-deleted products in batches of
productLimit(default 5000), pagedORDER BY id ASCwithget_where(..., $limit, $offset)(src/Domains/Product/PriceTracking/Jobs/TrackPrices.php:82-83). - Columns selected:
id,vat_id,discount_persent,special_from,special_to,special_discount_percent,price.
- Select active, non-deleted products in batches of
- For each product, calculate the current final price via
PriceCalculator::calculateFinalPrice()(src/Domains/Product/PriceTracking/PriceCalculator.php):- Check if special discounts are enabled via
OTHER.ENABLE_SPECIAL_DISCOUNTSregistry. - If a special discount period is active (
special_from <= now <= special_to), usespecial_discount_percentinstead of the regulardiscount_persent. - Apply discount:
price * (1 - discount/100). - Apply VAT (inlined math):
round($net + (($vatPercent / 100) * $net), 2)— no CI helper called. - Format to standard precision:
sprintf('%.2f', $withVat)— no CI helper called.
- Check if special discounts are enabled via
- Change detection happens inside
WriteService::recordBatch()(src/Domains/Product/PriceTracking/WriteService.php:64-86), not in the job loop:recordBatch()callsWriteRepository::getLatestPriceForProduct()per product and filters out products whose price is unchanged before building the insert batch. - Batch insert: collect all changed prices and insert in one
insert_batch()call per batch iteration. - Refresh the persisted verdict: after each page is recorded,
refreshVerdicts($rows, $now)is called (TrackPrices.php:112; method at:127-146). It resolves each product's real selling price viaCurrentPrice::resolveand hands the map toPriceDropRefresher::refresh(see Persisted verdict andfilter[priceDrop]). It catches and logs any\Throwableso price recording continues for later pages; a page whose refresh failed keeps its old verdict rows, which stop counting after one hour.
Price Graph Generation (GraphService)
GraphService (src/Domains/Product/PriceTracking/GraphService.php) produces the graph payload on demand. It receives Options as a constructor-injected dependency (src/Domains/Product/PriceTracking/Options.php; same public properties as the legacy options class; built by Options::fromRegistryInstance(Registry $registry, array $adminLanguages) at Options.php:47, which fromRegistry() (Options.php:29-35) delegates to):
- Load price changes:
GraphService::productPrices(int $productId)delegates toproductPricesBulk(), which loads the rows withloadChangesBulk(): one query,from('price_tracking')->where_in('product_id', $productIds)->order_by('product_id', 'ASC')->order_by('price_date', 'DESC')(src/Domains/Product/PriceTracking/GraphService.php:134-138), grouped byproduct_id. - Limit to tracking period: configurable via
PRICE_TRACK.TRACK_DAYS(default 30 days). - Build daily price timeline (in
PriceDropVerdictCalculator):setPriceTimeline()— for each day in the period, determine the applicable price (most recent change on or before that date). - Calculate reference price and discount eligibility:
parseResponse()— determinesreferencePrice(Omnibus rule),saveValue, anddiscountPass. - Bulk variant:
GraphService::productPricesBulk(array $productIds, ?array $currentPrices = null, ?\DateTimeInterface $now = null)— executes one query and groups results byproduct_idto avoid N+1 queries.$currentPricesis the real prices when the caller already resolved them (theTrackPricesjob).$nowis the clock the verdicts and the current-price lookup are computed at;nullmeans the wall clock (new DateTimeImmutable()) (src/Domains/Product/PriceTracking/GraphService.php:34-51).
Storefront fast path (#912)
The legacy storefront asks for a verdict for every parsed product on every render: Adv_product_parser_model calls GraphService::storefrontPricesBulk() for the whole product list (ecommercen/eshop/models/Adv_product_parser_model.php:128) and storefrontPrices() for a single product (Adv_product_parser_model.php:680). The REST graph endpoints, the legacy /api/priceTracking endpoint and the TrackPrices job keep using productPrices() / productPricesBulk() unchanged. The storefront methods return the same keys (referencePrice, saveValue, shouldDisplay, discountPass) with the same values, but skip work that cannot change them (src/Domains/Product/PriceTracking/GraphService.php:93-125):
| Condition | What happens |
|---|---|
PRICE_TRACK.ENABLED off and no graph setting on (enabledGraph, enabledOnAllGraphs, enabledGraphOnProductCard, enabledGraphOnProductPage) | Every id gets the empty verdict (calculator->verdict([], null, $now)) with no database access. A graph setting alone keeps the gate open, because client views read shouldDisplay / prices under a graph flag without ENABLED |
ENABLED on, no graph setting on | prices is never read, so PriceDropVerdictCalculator::noClaimVerdict() is tried first: a product that provably cannot qualify gets the verdict without the daily timeline and with prices empty |
| Any graph setting on | The full verdict() is built, so prices is identical to productPricesBulk() |
noClaimVerdict() (src/Domains/Product/PriceTracking/PriceDropVerdictCalculator.php:114-157) applies when couldQualify() (:90-94: at least two tracked changes and the newest not older than newestChangeCutoff(), :76-81) is false. Every day of the timeline would then be priced at the newest row, so the reference price is that row's price, shouldDisplay is false, and applyCurrentPrice() (:362, extracted from parseResponse() and shared by both paths) derives saveValue and discountPass from the real current price. It returns null, and the caller runs the full verdict(), when there are no rows, couldQualify() is true, a price_date is malformed, the newest change is dated after today, or days is below 1. The real current price is still resolved for every id (CurrentPrice::resolveBulk), so a stale feed can still only hide a claim (#876).
Real current price (#876)
The verdict itself lives in PriceDropVerdictCalculator (pure: change rows, real price, clock); GraphService only loads rows and the real selling price (CurrentPrice, i.e. PriceResolver) and calls it. "Current" is never the newest tracked row: if that row differs from the real price by half a cent or more (a stale feed), or the real price is unknown, shouldDisplay and discountPass are false; discountPass also requires referencePrice strictly above the real price. A stale feed can therefore only hide a claim.
Persisted verdict and filter[priceDrop]
After recording prices, TrackPrices calls PriceDropRefresher for the page. The candidates are idsWithQualifyingHistory(...) (products with at least two tracked rows, the newest within TRACK_DAYS + 1 days) plus array_filter($existing) (src/Domains/Product/PriceTracking/PriceDropRefresher.php:52-55). existingIds() returns product_id => (bool) qualifies (PriceDropStore.php:36-51), so the second term is "any product whose stored row still says qualifies = 1": a qualifies = 0 row is never re-evaluated or rewritten while it stays 0 (docblock PriceDropRefresher.php:11-14, continue at :78-80). The refresher asks GraphService::productPricesBulk() (same calculator, real prices already resolved by the job) and passes its own $now as the third argument (PriceDropRefresher.php:68-72), so a verdict is computed at the same instant the refresher used to pick its candidates (:53) and stamp computed_at (:61). Before the #876 fix the verdicts were computed at the wall clock, not the refresh's clock. TrackPrices hands the refresher that clock (src/Domains/Product/PriceTracking/Jobs/TrackPrices.php:140). It then upserts product_price_drop: a row for every product that qualifies, plus a qualifies = 0 flip for one that had a qualifying row and stopped. Every qualifying row is re-written each run, so computed_at is a heartbeat.
Memory is bounded by chunking: the refresher evaluates candidates in chunks of 500 (PriceDropRefresher::CHUNK_SIZE = 500, :23; loop :65-92; verdicts are unset before the next chunk, :92), PriceDropStore::upsert() writes in chunks of 500 (:92), the id lookups (existingIds(), idsWithQualifyingHistory()) run in chunks of 1000 (:39, :64), and CurrentPrice::CHUNK is 1000 (CurrentPrice.php:17).
filter[priceDrop] on GET /rest/product/product (FilterByPriceDrop) counts only qualifies = 1 rows confirmed within PriceDropStore::FRESH_FOR_SECONDS (1 hour); 0 is the exact complement. With PRICE_TRACK.ENABLED off nothing qualifies. The caveats of this design (job cadence, legacy job, VAT manipulation, missing table, empty set after migration) are listed under Known Issues & Security Gaps.
API Endpoints
| Endpoint | Method | Description |
|---|---|---|
/rest/product/price-tracking/graph/{productId} | GET | Single-product graph payload; guest-accessible |
/rest/product/price-tracking/graph?productIds=1,2,3 | GET | Bulk graph payload (comma-separated IDs); guest-accessible |
Data Model
Table: price_tracking
| Column | Type | Role |
|---|---|---|
id | int | PK (auto-increment) |
product_id | int | FK to shop_product.id |
price | decimal | Final price including VAT at time of recording |
price_date | datetime | Timestamp of the price snapshot |
Table: product_price_drop (#876)
Created by database/migrations/20261003120000_create_product_price_drop.php:29-36; the migration returns early when the table already exists (hasTable, :25-27). Written only by PriceDropStore::upsert(), read by FilterByPriceDrop.
| Column | Type | Role |
|---|---|---|
product_id | int, PK (not auto-increment) | The product the verdict belongs to |
reference_price | decimal(11,2), default 0.00 | Omnibus reference price from the verdict |
current_price | decimal(11,2), default 0.00 | Real selling price used for the verdict |
qualifies | boolean, default false | Whether the product currently has a genuine price drop |
computed_at | datetime NOT NULL | Last time the row was (re)confirmed; the freshness heartbeat |
Index idx_qualifies_computed_at (qualifies, computed_at) serves the filter predicate qualifies = 1 AND computed_at >= ? (migration:35).
Related Tables
| Table | Role |
|---|---|
shop_product | Source for current prices and discount percentages |
shop_product_vats | VAT rate lookup (indexed by vat_id) |
Configuration
Job Scheduling (application/config/jobs.php)
php
// tracking queue (application/config/jobs.php:100; the queue starts at :94)
['command' => \Advisable\Domains\Product\PriceTracking\Jobs\TrackPrices::class, 'schedule' => '*/5 * * * *', 'graceTime' => 60, 'retryTimes' => 0, 'options' => ['productLimit' => '5000']]Runs every 5 minutes in the dedicated tracking queue. The tracking queue has lockJobs: false (no job locking needed).
Job Options
| Option | Type | Default | Description |
|---|---|---|---|
productId | int | (all) | Track a single product (used for manual/debugging runs) |
productLimit | int | 5000 | Batch size per iteration |
Registry Settings (PRICE_TRACK group)
| Key | Type | Default | Description |
|---|---|---|---|
ENABLED | bool | false | Master feature toggle for price tracking |
ENABLED_GRAPH | bool | false | Enable graph display. Written from settings/index only for an Advisable session (Adv_settings.php:89-96, #1054) |
ENABLED_ALL_GRAPH | bool | false | Show graphs for all products (vs. only discounted) |
ENABLED_GRAPH_PRODUCT_CARD | bool | false | Show mini-graph on product cards |
ENABLED_GRAPH_PRODUCT_PAGE | bool | false | Show full graph on product detail pages |
TRACK_DAYS | int | 30 | Number of days of price history to retain/display |
SHOW_DISCOUNT_ON_VALUE | float | 10 | Minimum discount % to show the discount badge |
DISCOUNT_LABEL | string (MUI) | -- | Label text for the discount indicator (per language) |
DISCOUNT_BADGE_LABEL | string (MUI) | -- | Badge label for the discount indicator (per language) |
Storefront Config Publication (priceTracking section)
GET /rest/storefront-config publishes a priceTracking section (#765), built by src/Domains/StorefrontConfig/PriceTracking/PriceTrackingConfigResolver.php and wired in src/Domains/StorefrontConfig/StorefrontConfigProvider.php:47,78. It carries enabled (= PRICE_TRACK.ENABLED, fails closed to false, independent of the ENABLED_GRAPH* keys) plus per-admin-language discountLabel / badgeLabel. TRACK_DAYS and SHOW_DISCOUNT_ON_VALUE are deliberately not published because the graph endpoint applies them server-side. The PRICE_TRACK group is read through Options::fromRegistryInstance() (src/Domains/Product/PriceTracking/Options.php:47).
Other Registry Settings
| Group | Key | Description |
|---|---|---|
OTHER | ENABLE_SPECIAL_DISCOUNTS | Whether time-limited special discounts are active |
Client Extension Points
All override points are in the modern domain layer. PR #128 deleted ten price-tracking classes, five per layer (each application/modules/ class a thin subclass of its ecommercen/ counterpart); #703 restores only the two controllers below. The other eight stay deleted, including AdvPriceTrackingGraphs, AdvPriceTrackingModel, AdvTrackPrices (ecommercen/) and Price_tracking_graphs.php, PriceTrackingOptions.php (application/modules/eshop/libraries/).
application/modules/api/controllers/Api_price_tracking.php — deleted by the same PR — was restored by Advisable-com/ecommercen#703, but not with its old implementation: it is now a thin extends AdvApiPriceTrackingController {} shim (ecommercen/api/controllers/AdvApiPriceTrackingController.php), which delegates to the same GraphService as the REST controller below. The legacy storefront price chart (ProductPriceChart.vue) calls this restored /api/priceTracking/productPrices/{id} endpoint again — /rest/product/price-tracking/graph/{id} remains available unchanged for headless/API consumers (Velora, MCP), registered only when APP_REST_API_ENABLED is true. See docs/decisions/703-restore-legacy-price-tracking-api.md for the full rationale.
Override the job: Extend
Advisable\Domains\Product\PriceTracking\Jobs\TrackPriceswith a custom subclass and register it inapplication/config/jobs.phpby replacing thecommandFQCN with your subclass name, or register a DI alias.Override price calculation: Extend
Advisable\Domains\Product\PriceTracking\PriceCalculatorand register a DI alias so the job and any other consumers receive the custom implementation.Override graph generation: the loading lives in
Advisable\Domains\Product\PriceTracking\GraphService; the timeline, reference-price algorithm and discount-eligibility rules live inAdvisable\Domains\Product\PriceTracking\PriceDropVerdictCalculator(#876), and the real selling price inCurrentPrice. Extend the class that owns the rule you change and register a DI alias.Override options/configuration DTO: Extend
Advisable\Domains\Product\PriceTracking\Optionsand register a DI alias to change default values or add custom configuration properties.
Business Rules
| Rule | Description |
|---|---|
| Change-only recording | New records are inserted only when the calculated price differs from the last recorded price |
| VAT-inclusive prices | Prices are stored with VAT included (final customer-facing price) |
| Special discount priority | Time-limited special discounts override the regular discount percentage |
| Batch processing | Products are processed in configurable batches to limit memory usage |
| Feature gated | The entire feature requires PRICE_TRACK.ENABLED to be true in registry |
| Omnibus compliance | Reference price calculation follows EU Omnibus Directive rules (lowest/highest price in tracking window) |
| Graph display threshold | Discount badge only shown when discount meets SHOW_DISCOUNT_ON_VALUE minimum |
| No display on price increase | Graph is hidden when current price equals or exceeds the reference price |
| Multi-language labels | Discount labels and badge text are configurable per language |
Known Issues & Security Gaps
- A stopped or slow job empties
filter[priceDrop]=1.FilterByPriceDropcounts only verdicts re-confirmed withinPriceDropStore::FRESH_FOR_SECONDS = 3600(PriceDropStore.php:25). The 1-hour window presumes the modern job runs every 5 minutes, so with the job stopped, or a fork scheduling it less often than hourly,1matches nothing (fails toward "no claim", never a stale claim). - Forks still on the legacy
AdvTrackPricesjob never fillproduct_price_drop. Only the modernTrackPricesjob runsPriceDropRefresher, so on such a forkfilter[priceDrop]=1matches nothing and0matches everything (src/Rest/Product/Controllers/Product.php:175-182). - The stored verdict ignores
enableOrderVatManipulationand viewer context. It is computed with the product's default VAT rate and no viewer context, so with order-VAT manipulation1can list a product whose badge is hidden for a particular viewer (src/Domains/Product/Product/Repository/Specification/FilterByPriceDrop.php:12-16). - With the table missing,
1matches nothing and0applies no restriction. Whenproduct_price_dropdoes not exist (migration not run) the specification addsshop_product.id = -1for1and nothing for0(FilterByPriceDrop.php:36-41); with the table present the predicate isIN/NOT INover the fresh qualifying rows (:43-50). - The set is empty until the first job run after the migration. The table starts empty with no backfill and fills on the next
TrackPricesrun (database/migrations/20261003120000_create_product_price_drop.php:16-17).
Tests
11 unit-test classes in tests/Unit/Domains/Product/PriceTracking/, 3 integration classes in tests/Integration/Domains/Product/PriceTracking/, and the filter[priceDrop] specification test tests/Unit/Domains/Product/Product/Repository/FilterByPriceDropTest.php:
| Class | What it covers |
|---|---|
PriceDropVerdictCalculatorTest | The Omnibus verdict (verdict()), its protected helpers (timeline building, reference-price logic, stale-feed and real-price rules) and noClaimVerdict() against verdict() (#912) |
GraphServiceTest | The storefront fast path (#912): gate off gives the empty verdict with no database access, a graph flag alone opens the gate, non-qualifying ids skip the timeline, productPricesBulk() unchanged, and productPricesBulk() uses the clock it is given (current-price lookup and verdict, #876) |
CurrentPriceTest | CurrentPrice against PriceResolver; where the recorded price and the real price legitimately differ (special-window boundary second, VatForOrder-adjusted rate) |
OptionsTest, OptionsFromRegistryTest | The Options DTO and its registry reader |
ServiceTest | The read Service used by the REST controller |
PriceCalculatorTest | VAT math and discount application in PriceCalculator::calculateFinalPrice() |
ValidatorTest | Validation rules in Validator (productId, price, date fields) |
WriteDataTest | WriteData DTO serialization and snake/camelCase input flexibility |
PriceDropRefresherTest | PriceDropRefresher |
PriceDropRefresherMemoryTest | The verdict step of TrackPrices stays bounded by a chunk, not by the page (a 5,000-product page with a 30-day history previously ran a 128M php.ini out of memory) |
FilterByPriceDropTest | filter[priceDrop]: the persisted verdict, qualifying and fresh (tests/Unit/Domains/Product/Product/Repository/) |
PriceDropVerdictTest (integration) | The persisted verdict end to end against a live database: the job writes it, filter[priceDrop] reads it, and the storefront graph agrees |
TrackPricesResilienceTest (integration) | The verdict refresh that follows each page must never be able to stop price recording |
GraphServiceRealPriceTest (integration) | GraphService against a database: the verdict is built on the real price, a stale feed hides the claim, the bulk read prices each product |
Related Flows
- SY-01 Cron Job Framework -- job scheduling and execution
- CF-02 Product Detail -- storefront price graph rendering
- AD-02 Product Management -- product pricing fields that feed the tracker
- AD-43 New Product Prices -- ERP price imports that may trigger price changes