Skip to content

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 path storefrontPrices() / storefrontPricesBulk() and PriceDropVerdictCalculator::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 ​

FileRole
src/Domains/Product/PriceTracking/Jobs/TrackPrices.phpModern JobCommand; entry point for the cron job
src/Domains/Product/PriceTracking/PriceCalculator.phpPure final-price math (regular + special discount + VAT)
src/Domains/Product/PriceTracking/GraphService.phpLoads 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.phpPure Omnibus timeline + reference-price + eligibility verdict (#876); couldQualify() and noClaimVerdict() short-circuit products that cannot qualify (#912)
src/Domains/Product/PriceTracking/CurrentPrice.phpThe real selling price via PriceResolver (#876)
src/Domains/Product/PriceTracking/PriceDropRefresher.phpEvaluates the candidate products of a page and upserts their persisted verdict (CHUNK_SIZE = 500) (#876)
src/Domains/Product/PriceTracking/PriceDropStore.phpPersistence of product_price_drop: TABLE, FRESH_FOR_SECONDS = 3600, existingIds(), idsWithQualifyingHistory(), upsert() (#876)
src/Domains/Product/Product/Repository/Specification/FilterByPriceDrop.phpThe filter[priceDrop] specification on GET /rest/product/product (reads product_price_drop) (#876)
database/migrations/20261003120000_create_product_price_drop.phpCreates product_price_drop (guarded with hasTable) (#876)
src/Domains/Product/PriceTracking/Options.phpImmutable 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.phpBuilds the priceTracking section of GET /rest/storefront-config (#765); wired in StorefrontConfigProvider.php:46,78
src/Domains/Product/PriceTracking/WriteService.phpInsert/update/delete + recordBatch() for the job
src/Domains/Product/PriceTracking/WriteData.phpValidated write DTO with snake/camel input flexibility
src/Domains/Product/PriceTracking/Validator.phpproductId/price/date validation rules
src/Domains/Product/PriceTracking/Repository/WriteRepository.phpPersistence (insert_batch + last-price lookup)
src/Domains/Product/PriceTracking/Repository/Repository.phpRead repository (Specification pattern)
src/Domains/Product/PriceTracking/Repository/Entity.phpEntity DTO
src/Domains/Product/PriceTracking/Service.phpRead service used by the REST controller
src/Rest/Product/Controllers/PriceTracking.phpREST endpoints (index, show, item, graph, graphBulk)
application/config/jobs.phpJob registration (FQCN; tracking queue, 5-min schedule)
application/config/rest_routes.phpRoute table for the REST endpoints (write routes intentionally commented)

Code Flow ​

Price Recording (Job) ​

  1. Load VAT rates: query all rows from shop_product_vats and index by ID for fast lookup.
  2. Batch processing loop (do...while):
    • Select active, non-deleted products in batches of productLimit (default 5000), paged ORDER BY id ASC with get_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.
  3. 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_DISCOUNTS registry.
    • If a special discount period is active (special_from <= now <= special_to), use special_discount_percent instead of the regular discount_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.
  4. Change detection happens inside WriteService::recordBatch() (src/Domains/Product/PriceTracking/WriteService.php:64-86), not in the job loop: recordBatch() calls WriteRepository::getLatestPriceForProduct() per product and filters out products whose price is unchanged before building the insert batch.
  5. Batch insert: collect all changed prices and insert in one insert_batch() call per batch iteration.
  6. 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 via CurrentPrice::resolve and hands the map to PriceDropRefresher::refresh (see Persisted verdict and filter[priceDrop]). It catches and logs any \Throwable so 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):

  1. Load price changes: GraphService::productPrices(int $productId) delegates to productPricesBulk(), which loads the rows with loadChangesBulk(): 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 by product_id.
  2. Limit to tracking period: configurable via PRICE_TRACK.TRACK_DAYS (default 30 days).
  3. 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).
  4. Calculate reference price and discount eligibility: parseResponse() — determines referencePrice (Omnibus rule), saveValue, and discountPass.
  5. Bulk variant: GraphService::productPricesBulk(array $productIds, ?array $currentPrices = null, ?\DateTimeInterface $now = null) — executes one query and groups results by product_id to avoid N+1 queries. $currentPrices is the real prices when the caller already resolved them (the TrackPrices job). $now is the clock the verdicts and the current-price lookup are computed at; null means 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):

ConditionWhat 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 onprices 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 onThe 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 ​

EndpointMethodDescription
/rest/product/price-tracking/graph/{productId}GETSingle-product graph payload; guest-accessible
/rest/product/price-tracking/graph?productIds=1,2,3GETBulk graph payload (comma-separated IDs); guest-accessible

Data Model ​

Table: price_tracking ​

ColumnTypeRole
idintPK (auto-increment)
product_idintFK to shop_product.id
pricedecimalFinal price including VAT at time of recording
price_datedatetimeTimestamp 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.

ColumnTypeRole
product_idint, PK (not auto-increment)The product the verdict belongs to
reference_pricedecimal(11,2), default 0.00Omnibus reference price from the verdict
current_pricedecimal(11,2), default 0.00Real selling price used for the verdict
qualifiesboolean, default falseWhether the product currently has a genuine price drop
computed_atdatetime NOT NULLLast 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).

TableRole
shop_productSource for current prices and discount percentages
shop_product_vatsVAT 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 ​

OptionTypeDefaultDescription
productIdint(all)Track a single product (used for manual/debugging runs)
productLimitint5000Batch size per iteration

Registry Settings (PRICE_TRACK group) ​

KeyTypeDefaultDescription
ENABLEDboolfalseMaster feature toggle for price tracking
ENABLED_GRAPHboolfalseEnable graph display. Written from settings/index only for an Advisable session (Adv_settings.php:89-96, #1054)
ENABLED_ALL_GRAPHboolfalseShow graphs for all products (vs. only discounted)
ENABLED_GRAPH_PRODUCT_CARDboolfalseShow mini-graph on product cards
ENABLED_GRAPH_PRODUCT_PAGEboolfalseShow full graph on product detail pages
TRACK_DAYSint30Number of days of price history to retain/display
SHOW_DISCOUNT_ON_VALUEfloat10Minimum discount % to show the discount badge
DISCOUNT_LABELstring (MUI)--Label text for the discount indicator (per language)
DISCOUNT_BADGE_LABELstring (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 ​

GroupKeyDescription
OTHERENABLE_SPECIAL_DISCOUNTSWhether 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.

  1. Override the job: Extend Advisable\Domains\Product\PriceTracking\Jobs\TrackPrices with a custom subclass and register it in application/config/jobs.php by replacing the command FQCN with your subclass name, or register a DI alias.

  2. Override price calculation: Extend Advisable\Domains\Product\PriceTracking\PriceCalculator and register a DI alias so the job and any other consumers receive the custom implementation.

  3. Override graph generation: the loading lives in Advisable\Domains\Product\PriceTracking\GraphService; the timeline, reference-price algorithm and discount-eligibility rules live in Advisable\Domains\Product\PriceTracking\PriceDropVerdictCalculator (#876), and the real selling price in CurrentPrice. Extend the class that owns the rule you change and register a DI alias.

  4. Override options/configuration DTO: Extend Advisable\Domains\Product\PriceTracking\Options and register a DI alias to change default values or add custom configuration properties.

Business Rules ​

RuleDescription
Change-only recordingNew records are inserted only when the calculated price differs from the last recorded price
VAT-inclusive pricesPrices are stored with VAT included (final customer-facing price)
Special discount priorityTime-limited special discounts override the regular discount percentage
Batch processingProducts are processed in configurable batches to limit memory usage
Feature gatedThe entire feature requires PRICE_TRACK.ENABLED to be true in registry
Omnibus complianceReference price calculation follows EU Omnibus Directive rules (lowest/highest price in tracking window)
Graph display thresholdDiscount badge only shown when discount meets SHOW_DISCOUNT_ON_VALUE minimum
No display on price increaseGraph is hidden when current price equals or exceeds the reference price
Multi-language labelsDiscount labels and badge text are configurable per language

Known Issues & Security Gaps ​

  1. A stopped or slow job empties filter[priceDrop]=1. FilterByPriceDrop counts only verdicts re-confirmed within PriceDropStore::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, 1 matches nothing (fails toward "no claim", never a stale claim).
  2. Forks still on the legacy AdvTrackPrices job never fill product_price_drop. Only the modern TrackPrices job runs PriceDropRefresher, so on such a fork filter[priceDrop]=1 matches nothing and 0 matches everything (src/Rest/Product/Controllers/Product.php:175-182).
  3. The stored verdict ignores enableOrderVatManipulation and viewer context. It is computed with the product's default VAT rate and no viewer context, so with order-VAT manipulation 1 can list a product whose badge is hidden for a particular viewer (src/Domains/Product/Product/Repository/Specification/FilterByPriceDrop.php:12-16).
  4. With the table missing, 1 matches nothing and 0 applies no restriction. When product_price_drop does not exist (migration not run) the specification adds shop_product.id = -1 for 1 and nothing for 0 (FilterByPriceDrop.php:36-41); with the table present the predicate is IN / NOT IN over the fresh qualifying rows (:43-50).
  5. The set is empty until the first job run after the migration. The table starts empty with no backfill and fills on the next TrackPrices run (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:

ClassWhat it covers
PriceDropVerdictCalculatorTestThe Omnibus verdict (verdict()), its protected helpers (timeline building, reference-price logic, stale-feed and real-price rules) and noClaimVerdict() against verdict() (#912)
GraphServiceTestThe 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)
CurrentPriceTestCurrentPrice against PriceResolver; where the recorded price and the real price legitimately differ (special-window boundary second, VatForOrder-adjusted rate)
OptionsTest, OptionsFromRegistryTestThe Options DTO and its registry reader
ServiceTestThe read Service used by the REST controller
PriceCalculatorTestVAT math and discount application in PriceCalculator::calculateFinalPrice()
ValidatorTestValidation rules in Validator (productId, price, date fields)
WriteDataTestWriteData DTO serialization and snake/camelCase input flexibility
PriceDropRefresherTestPriceDropRefresher
PriceDropRefresherMemoryTestThe 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)
FilterByPriceDropTestfilter[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