# Analytics: the profit ledger

Management accounting, not bookkeeping (PLAN › Financial analytics). Every revenue and cost event is a row in
`profit_entries`: the day, the type (`Analytics\Data\LedgerType`), the amount in RON minor units **net of VAT**
(revenue positive, costs negative, `NULL` for a cost that is not known: shown as missing, never as 0) and the
dimensions as plain ids (order, line, product, variant, customer, company, channel `web`/`b2b`/`marketplace`/`agent` (`PlacedOrder::channel()`; `agent` for an order whose source starts with `agent:`), payment and delivery
method, a reference such as the voucher code or promotion id).

- **Append-only.** A database trigger refuses `UPDATE` and `DELETE`; a correction is another row. There are no foreign
  keys, so deleting a customer or product never rewrites the ledger.
- **Once per event.** Each row has a unique `source` (`order:12:sale:34`, `return:5:refund:34`); writing goes only
  through `Analytics\Contracts\ProfitLedger::record()`, which skips sources already booked.

## What is booked

`Analytics\Listeners\BookOrders` listens to `OrderStatusChanged` and `ReturnStatusChanged`; `Ledger\OrderEntries`
builds the rows from the order's frozen totals:

| When | Rows |
| --- | --- |
| The order is fulfilled (`orders.fulfilled_at`: shipped, pickup collected, digital delivered) | per line `sale` (line price net of its VAT), one `discount` per adjustment (the amounts it names per variant, or spread by value, net of the line's VAT), `cogs` (the snapshot × quantity); `shipping_charged` net of the delivery VAT |
| The whole order returns (`Returned`) | `refund` of each line's net revenue after discounts and of the delivery, `cost_returned` of the goods |
| A withdrawal is refunded | `refund` and `cost_returned` for the returned units |

Gift card lines are money, not goods (no revenue, no cost); the SGR deposit is pass-through and never booked.
Foreign-currency orders convert at the BNR rate of the day booked (the latest rate, failing that). Nothing is booked
for an order cancelled before it was fulfilled.

## The cost snapshot

`ChangeOrderStatus` freezes `order_lines.unit_cost` once, when the order is fulfilled, from
`Inventory\Contracts\Costs` (weighted average, else manual): digital content without a cost costs 0, a gift card has
none, physical goods without one stay `NULL`. A later cost change never touches what was booked.

## Shipping and payment costs

`Analytics\Listeners\BookCosts` books `shipping_cost` on `Fulfilment\Data\ShipmentBooked` (source
`shipment:{id}:cost`) and gives it back on `ShipmentCancelled` (`shipment:{id}:cancelled`, only when a known cost was
booked), and `payment_fee` on `Checkout\Data\PaymentSettled` (`payment:{id}:fee`). `Ledger\CostEntries` takes what the
driver reported (`ShipmentResult::$cost`, `PaymentResult::$fee`, kept on `shipments.cost` / `payments.fee`), else the
rate card in `Analytics\Settings\CostSettings` (AWB cost per courier; percent plus fixed per processor; Settings →
Costuri, `settings.manage` and `analytics.finance`), else `NULL`.

Not yet: the daily aggregates (`analytics:rollup`), courier invoice and settlement imports, and the reports (Phase 3). Returned goods are booked back at cost; putting them back in stock is
recorded in Inventory separately.

Tests: `tests/Feature/Analytics/ProfitLedgerTest.php`.

## Reports

- `ledger_daily` holds the ledger's sums per day and type (with the count of rows whose amount is NULL and of
  orders), rebuilt by `Reports\Rollup` (`analytics:rollup`: today and yesterday hourly, `--days=35` nightly,
  `--from/--to` on demand). It is a copy, never the record.
- `Reports\Figures` applies the margin model to some sums (net revenue, COGS, gross margin, shipping net, fees,
  contribution) and the missing counts; `Reports\Finance` gives a period's figures, the months, and margins by
  product, brand or category (straight from `profit_entries`, names from `Catalog\Contracts\ProductDimensions`).
- Sales as placed come from `Orders\Contracts\SalesFigures` (RON, BNR-converted per day).
- `admin.analytics.dashboard` needs `analytics.view`; `pnl` and `margins` also `analytics.finance`, as does the
  dashboard's profit block. CSV through `Platform\Data\Csv` (BOM, `;`, formula-injection guard), shared with other modules' exports.
- Charts: `packages/core/resources/js/admin/charts.js` (ApexCharts 8.7.0, its own Vite entry, pushed only on report pages) reads
  `data-chart` JSON; every chart has its numbers in a table too.

- Monthly costs: `period_costs` (kind `fixed|marketing`, category from `Data\PeriodCostKind::categories()`, month,
  amount, revision) holds the last amount entered. `Actions\SavePeriodCosts` books each change into the ledger as
  `fixed_cost` / `marketing` rows for the difference, spread over the month's days (`shares()`: equal parts, leftover
  bani on the first days), source `period:<kind>:<category>:<Y-m>:r<revision>:d<day>`, then rolls the month up.
  `Figures::contribution()` subtracts marketing; `operatingProfit()` subtracts fixed costs.
  `Finance::enteredMonths()` tells the P&L which months have entries, so an empty one reads "neintrodus".

- Customers: `Orders\Contracts\CustomerFigures` (buyer = `lower(email)`, guests included, cancelled out, imported
  history in; index `orders_buyer_placed_index`) gives `summaries()`, `cohorts()` and `period()` (new/returning), with
  no address leaving Orders. `Reports\CustomerReport` turns them into totals, the cohort table and RFM segments on
  fixed thresholds (`SEGMENTS` is the test order, `DISPLAY` the shown order). Route `admin.analytics.customers`
  (`analytics.view`; acquisition cost only with `analytics.finance`).
- `Orders\Contracts\SalesFigures` now includes the imported history (`source = legacy`).
- Receivables: `Orders\Contracts\Receivables` (`open()`: unpaid terms orders, not cancelled or returned, in RON at
  today's BNR rate; `termsSales()` for DSO) and `B2B\Contracts\Companies::credit()` (name, CUI, terms, credit limit).
  `Reports\ReceivablesReport` buckets by days past due, rolls up per company and computes DSO over 90 days. Route
  `admin.analytics.receivables` (`analytics.finance`), CSV with `?format=csv`.

- Stock: `Inventory\Contracts\StockFigures` (`positions()` on hand per variant and location, `lastSales()` from sale
  movements, `unitsOut()` sales less returns), `Inventory\Contracts\Costs::unitCosts()`,
  `Catalog\Contracts\ProductDimensions::variants()` (SKU and product name) and `Stores\Contracts\Locations`.
  `Reports\StockReport` values variants and locations, filters unsold stock (90/180 days) and computes days of stock
  from the ledger's COGS over 365 days. Route `admin.analytics.stock` (`analytics.finance`), CSV of the unsold list.

- Subscriptions: `Subscriptions\Contracts\SubscriptionFigures` (`lines()`: each subscription's monthly value in RON with
  its start, end and current pause; `dunning()`: `payment_failed` orders in a range and how many were later
  `renewed`). `Reports\SubscriptionReport` rebuilds MRR at any moment (`SubscriptionLine::activeAt()`), the 12-month
  series with new and lost revenue and churn. Route `admin.analytics.subscriptions` (`analytics.view`).

- VAT check: `Orders\Contracts\VatFigures` (`split()`: an order's VAT by rate from `totals.vat`, percent keys without
  trailing zeros; `fulfilled()`: orders that need an invoice) and `Invoicing\Contracts\Invoices::issuedBetween()` /
  `invoicedOrders()`. `Reports\VatReport::check()` sums by rate (credit notes negative, RON at the invoice day's BNR
  rate) and lists missing invoices and total mismatches. Route `admin.analytics.vat` (`analytics.finance`).

- API: `Api\LedgerEntriesResource` (`ledger_entries`, model `Models\ProfitEntry`, filters from/to/type/order_id) and
  `Api\PeriodCostsResource` (`period_costs`), list and show only, permission `analytics.finance`, tagged
  `ApiResource::TAG` in the provider. `ledger_daily` is not exposed (no id to page by); BI tools sum the entries.

- Exports: `Reports\Exports` builds the tables (`Reports\Export`: name, header, rows) for P&L, margins, receivables
  and unsold stock, used by the CSV buttons (`Export::download()`) and the e-mails (`Csv::content()`).
- E-mailed reports: `report_subscriptions` (user, `Data\EmailReport`, weekly|monthly, last_sent_on), chosen in
  `admin.analytics.emails`. `Actions\SendScheduledReports` (`analytics:send-reports`, daily 07:00 in the registry)
  sends weekly ones on Mondays and monthly ones on the 1st, once a day, re-checking `analytics.view` and the report's
  permission; `Mail\ScheduledReportMail` is plain Romanian text with the CSV attached.

Tests: `tests/Feature/Analytics/ReportsTest.php`, `PeriodCostsTest.php`, `CustomersReportTest.php`,
`ReceivablesReportTest.php`, `StockReportTest.php`, `SubscriptionsReportTest.php`, `VatCheckTest.php`, `AnalyticsApiTest.php`, `EmailedReportsTest.php`.

## AI traffic

- `Analytics\Data\AiAssistant` knows each assistant's link hosts (subdomains included) and `utm_source` values;
  `AiAssistant::of($referer, $utmSource)` names the assistant (utm first).
- `Storefront\Http\Middleware\MeasureAiTraffic` runs on every storefront page and on robots.txt, llms.txt and the
  sitemaps, after the response, never failing the page, and only for responses below 400 (a made-up address never becomes a
  row). A GET from a user agent naming a crawler in
  `syncshop.seo.bots` (search or training) is `AiTraffic::crawl($bot, $path)`. Otherwise a 2xx/3xx page with an
  assistant's referer or utm_source counts `AiTraffic::visit()` once per session per assistant and keeps the assistant
  in the session (`MeasureAiTraffic::SESSION`).
- `Traffic\DatabaseAiTraffic` upserts per-day counters into `ai_visits` (day, assistant, path) and `ai_crawls` (day,
  bot, path); paths without query strings, 255 characters at most.
- Checkout (`CheckoutController::noteAssistant()`) writes `orders.referrer = 'ai:<assistant>'` through
  `Orders\Contracts\OrderReferrers` when the visitor's consent has statistics; `SalesFigures::referred()` sums orders
  and RON totals with VAT per referrer (cancelled left out, other currencies at the BNR rate of the day).
- `Traffic\AiTrafficReport` + `AiTrafficController` (`admin.analytics.traffic`, `analytics.view`) build the page.
- `Traffic\AiTrafficRetention` (tagged `retention`) drops crawl counts after 13 months and visit counts after 2 years.
- The plan counted crawler hits from the web server's access log; counting them in the app works on any server and
  needs no log access, but sees only requests that reach PHP (static files and images are not counted).

Tests: `tests/Feature/Analytics/AiTrafficTest.php`.

## Copilot

- `Analytics\Copilot\Copilot::ask(question, finance, userId)`:
  - It screens the question (`Ai\Data\PersonalText`).
  - A structured plan call through `AiFeature::Copilot` returns: tool (`TOOLS`: sales, margins, pnl; or none), a period
    preset or custom dates, by, compare and order. Only the tools the person may use are offered and described: finance
    tools need `analytics.finance`.
  - The shop runs a fixed report: `SalesFigures::daily()`, `Finance::margins()` for both periods joined by key and
    ordered by the change in margin %, or `Finance::figures()`.
  - An answer call gets the report rows as data.
  - It returns a `CopilotAnswer` (text, headers, rows, report URL).
- `Reports\Period::preset()` builds a preset period without a request.
- Admin: `CopilotController` (`admin.analytics.copilot`, `analytics.view`, POST throttled 20/min). The answer is kept in
  the session flash only.

Tests: `tests/Feature/Analytics/CopilotTest.php`.

