diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..0dbe9ce --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,58 @@ +# Dependabot version updates. The related GitHub settings (dependency graph, alerts and +# security updates) are not stored in this file; see docs/github-settings.md. +version: 2 + +updates: + - package-ecosystem: npm + directory: /apps/web + schedule: + interval: weekly + open-pull-requests-limit: 5 + commit-message: + prefix: "chore(deps)" + groups: + # next and eslint-config-next are pinned to the same exact version in package.json. + nextjs: + patterns: + - "next" + - "eslint-config-next" + react: + patterns: + - "react" + - "react-dom" + - "@types/react" + - "@types/react-dom" + ignore: + # Major versions are adopted deliberately. ESLint 10 is not yet supported by + # eslint-plugin-import, eslint-plugin-jsx-a11y and eslint-plugin-react, which + # eslint-config-next installs. Minor and patch updates still arrive. + - dependency-name: "typescript" + update-types: ["version-update:semver-major"] + - dependency-name: "eslint" + update-types: ["version-update:semver-major"] + + - package-ecosystem: nuget + directory: /backend + schedule: + interval: weekly + open-pull-requests-limit: 5 + commit-message: + prefix: "chore(deps)" + groups: + # dotnet-ef (backend/dotnet-tools.json) must match the EF Core version, and the Npgsql + # provider requires a minimum EF Core version, so these move together. + efcore-aspnetcore-extensions: + patterns: + - "Microsoft.EntityFrameworkCore*" + - "Npgsql.EntityFrameworkCore.*" + - "Microsoft.AspNetCore.*" + - "Microsoft.Extensions.*" + - "dotnet-ef" + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 + commit-message: + prefix: "chore(deps)" diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 321666a..bb51929 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -59,10 +59,22 @@ representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -**[CONTACT EMAIL — to be added by the maintainer]**. +reported to the community leaders responsible for enforcement. +**A private contact for conduct reports has not been published yet.** Until it +is, please do not describe an incident in a public issue, pull request or +comment. Open an issue that says only that you need a private conduct contact, +without any details about the incident, so that a maintainer can arrange a +private channel. All complaints will be reviewed and investigated promptly and fairly. + + All community leaders are obligated to respect the privacy and security of the reporter of any incident. diff --git a/SECURITY.md b/SECURITY.md index 3391ffb..4c6939a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,8 +8,20 @@ PureFreshMilk is pre-release (0.x). Only the latest commit on `main` receives se **Please do not report security vulnerabilities through public issues, discussions or pull requests.** -Report them privately through GitHub's private vulnerability reporting: open the repository's -**Security** tab and choose **Report a vulnerability**. +Report them privately through GitHub Security Advisories (GitHub's private vulnerability +reporting): + +1. Open the [Security tab](https://github.com/Coding-Professional/PureFreshMilk/security). +2. Choose **Advisories**, then **Report a vulnerability**. The direct link is + . +3. Fill in the form and submit it. + +Only you and the project maintainers can see the report. + +If there is no **Report a vulnerability** button, private reporting is not available on the +repository right now. Do not post details publicly. Open an issue that says only that you need a +private security contact, without any technical detail, so that a maintainer can arrange a +private channel. Please include: diff --git a/docs/architecture/decisions/0004-domain-model-for-household-deliveries.md b/docs/architecture/decisions/0004-domain-model-for-household-deliveries.md new file mode 100644 index 0000000..2499301 --- /dev/null +++ b/docs/architecture/decisions/0004-domain-model-for-household-deliveries.md @@ -0,0 +1,198 @@ +# 0004. Domain model for households, recipients, milk rates and daily deliveries + +- **Status:** Proposed +- **Date:** 2026-10-30 +- **Deciders:** Project maintainer (pending review) + +## Context + +The foundation stores nothing. The first working slice persists four things: a household, the +recipients who get milk, the price of milk over time, and one delivery record per recipient per day. +Monthly bills and payments come later. They are designed here, but not built, so that the tables +created now never have to change shape when billing arrives. + +What makes these choices hard to reverse: + +- Money and dates end up in every bill. Changing how they are represented later means migrating + history that people rely on. +- [ADR 0002](0002-quantities-in-whole-millilitres.md) fixed quantities as whole millilitres and left + money to a later decision. This is that decision. +- Authentication and household isolation come later, but every table created now must already be + ready for them. +- The Today prototype (`apps/web/src/features/today`) already defines vocabulary: a recipient has an + `expectedMl`, an entry has a status and a `deliveredMl`. + +The design details live in two companion documents so that this record stays about decisions: + +- [Domain model](../domain-model.md): entities, tables, constraints and the invariants that need tests. +- [Slice 1 plan](../../plans/slice-1-recipients-and-deliveries.md): API endpoints, the two pull + requests, and the questions that still need a decision. + +## Decision + +The maintainer proposed seven decisions. Each was checked against the code and the prototype. All +seven stand; five need changes to be safe, and those changes are what this record adds. + +| # | Proposed decision | Verdict | +| --- | --- | --- | +| 1 | Money as whole paise (`long`) | Confirmed, with a rounding rule | +| 2 | Milk rates with an effective-from date | Confirmed, but prices are derived, not stored on deliveries | +| 3 | One delivery per recipient per day, delivered or missed | Confirmed | +| 4 | Recipients are archived, never deleted | Confirmed, but with dates instead of a flag | +| 5 | `HouseholdId` on every aggregate | Confirmed, but a column alone is not isolation | +| 6 | `DateOnly` in the household's time zone | Confirmed | +| 7 | Bills calculated on demand, then frozen | Confirmed, with the ledger rules spelled out | + +### 1. Money is whole paise, rounded once per bill line + +- Money is a signed `long` of **paise** (PostgreSQL `bigint`). The only currency is INR; a second + currency would need its own decision. Names carry the unit, as with millilitres: + `price_per_litre_paise` in the database and `pricePerLitrePaise` in JSON. +- **Change.** Prices are per litre and quantities are millilitres, so an amount is not automatically + a whole number of paise: 250 ml at ₹62.50 a litre is 1562.5 paise. The rule is + `amount = round_half_up(millilitres × paise_per_litre ÷ 1000)`, applied **once per bill line** + (one recipient at one rate), never per delivery. +- Why per line: 30 days of 250 ml at ₹62.50 is 7,500 ml. One rounding gives 46,875 paise, the figure + a calculator gives for 7.5 L × ₹62.50. Rounding each delivery gives 30 × 1,563 = 46,890 paise, which + overstates the bill by 15 paise and cannot be reproduced by hand. +- Bounds keep the arithmetic safe in `long`: a price is 1 to 1,000,000 paise a litre (₹10,000) and a + delivery is at most 20,000 ml. Arithmetic is `checked`, as in `Quantity`. +- Quantities stay non-negative. Money may be negative, because adjustments can be. + +### 2. Rates are effective-dated, and prices are derived + +- A rate is a price per litre with an **effective-from** date. A delivery is priced at the rate with + the latest effective-from on or before its delivery date. There is one rate per household per + effective-from date. +- **Change.** Deliveries store no price and no amount. A delivery records what arrived; its price is + a policy applied later. Storing the price on the delivery would either leave early deliveries + unpriced when the rate is entered late (the normal case: the price rise is announced, and entered a + few days afterwards) or force stored prices to be rewritten. +- So "rate changes never rewrite past amounts" holds for **finalised** bills (decision 7). Amounts + for months that are not finalised always follow the current rate table, including a back-dated + rate, and the UI must label them as not final. Once a finalised bill covers a date, the rate that + governs that date can no longer be changed or deleted. +- A date before the first rate has no price. Deliveries can still be recorded, and finalising a + month that has delivered milk on an unpriced date is refused rather than billed at zero. +- One price series per household. Whether recipients can have their own price is an open question. + +### 3. One delivery per recipient per day + +- Confirmed as proposed: unique per recipient and calendar day; status `delivered` or `missed`; the + actual quantity is stored. A day with no record is **not recorded**, never assumed delivered. +- The default quantity is **copied** into the row when the delivery is recorded. A later change to the + recipient's usual quantity does not alter history. +- Added rules: `delivered` needs a quantity of at least 1 ml; `missed` has quantity 0; a date after + the household's today is rejected; the recipient must be active on that date (decision 4). +- "Not recorded" is the absence of a row, not a `pending` row. A pending row would have to be created + for every recipient every day, and a job that did not run would look like a decision. The API + reports it as `notRecorded`; the prototype's `pending` is renamed to match. +- Whether one record a day is enough (a morning and an evening delivery) is an open question. + +### 4. Recipients are archived with dates, never deleted + +- Confirmed: no hard delete, no DELETE endpoint, and the foreign key from deliveries is `RESTRICT`. +- **Change.** A recipient has a required `starts_on` and an optional `archived_from` (the first day + without deliveries). The recipient is active on date *d* when `starts_on ≤ d < archived_from`. + "Not recorded" only means something on days when a delivery was expected. A flag cannot say that a + recipient added on 20 November owed nothing before then, and someone who starts using the app + mid-month needs to enter earlier days. +- Names are unique among active recipients, ignoring case, so a double tap cannot create the same + person twice and the Today list is unambiguous. An archived name can be reused. +- Archiving is not erasure. If a person asks for their name to be removed, the name is replaced and + the billing history stays. + +### 5. Every aggregate carries `HouseholdId`, and the database enforces it + +- Confirmed: every household-owned table has a `NOT NULL household_id`, and it is the first column + of that table's indexes. +- **Change.** A column alone does not stop a delivery pointing at another household's recipient. + Child tables use composite foreign keys, `(household_id, recipient_id)` into + `recipients (household_id, id)`. In the Domain, ids are typed (`HouseholdId`, `RecipientId`) so one + cannot be passed where the other is expected. +- Until authentication exists there is no current household. Slice 1 runs in **single-household + mode** behind an `ICurrentHousehold` abstraction in Application. URLs carry no household id, so + the later change (a claims-based implementation plus an EF Core global filter) alters no API route. +- Single-household mode reads and writes without a login. It is therefore proposed that the data + endpoints are not mapped outside Development and Testing unless a setting turns them on. + +### 6. Dates are `DateOnly` in the household's time zone + +- Confirmed: `DateOnly` in the domain, `date` in PostgreSQL, `YYYY-MM-DD` in JSON. Default time zone + `Asia/Kolkata`, stored as an IANA id on the household. +- The **server** decides what "today" is, from `TimeProvider` and the household's zone. The web app + never sends a "today" it computed itself: a phone abroad would record against the wrong day. +- A month is a calendar month in the household's zone. Instants such as `created_at` are `timestamptz` + in UTC. +- Time zone ids need time zone data at runtime. Slim container images can lack it, so a test must + fail early if `Asia/Kolkata` does not resolve. + +### 7. Bills are calculated on demand until finalised, then frozen + +- Confirmed: no bill is stored until it is finalised. A finalised bill is an immutable snapshot, and a + later correction is an adjustment, never an edit. +- Planned shape, not built in slice 1: a finalised bill stores its lines (the recipient's name as it + was, millilitres, price per litre, amount; one line per recipient and rate) and its totals. +- A balance is never a stored number. It is derived: finalised bills, plus adjustments, minus payments. + Adjustments are signed and carry a reason; an opening balance is an adjustment. Payments are + positive and are voided rather than deleted. +- Deliveries inside a finalised month become read-only. A correction goes in as an adjustment. + Voiding or reopening a bill is deliberately not designed yet. + +### Further decisions + +- **`Delivery` is its own aggregate**, not a child of `Recipient`: it grows without bound, and + loading a recipient must not load years of deliveries. `Household`, `Recipient`, `MilkRate` and + `Delivery` are separate roots. Rules that span rows live in a pure Domain type (`RateSchedule`) or + in an Application handler. +- **Identifiers** are UUIDv7 (`Guid.CreateVersion7`), created in the application and held in typed + wrappers. They are ordered by time, so inserts stay index-friendly, and they cannot be guessed. +- **Status** is stored as text with a `CHECK` constraint, not a native PostgreSQL enum (awkward to + migrate) and not a number (unreadable in SQL). +- **Names for units** follow ADR 0002: `expected_ml`, `delivered_ml`, `…_paise`. + +## Consequences + +- Totals stay exact and agree between the server and any client. Billing adds tables; it does not + change the four created in slice 1. +- Past months stay stable once finalised, and a late price change still reaches months that are open. +- The database refuses cross-household references, so isolation does not depend on every query being + written correctly. +- Pricing needs a rate lookup wherever an amount is shown. The tables are tiny, so this costs little. +- The Today screen has to handle "not recorded" as a real state, and the unrecorded days of a month + have to be shown before it is finalised. +- Composite keys, typed ids and a generated column make the EF Core configuration longer than a + basic model. +- **Risks to manage:** single-household mode has no login, so slice 1 is for local use only; there is + no backup for the local Docker volume, and `docker compose down --volumes` deletes real data; time + zone data may be missing in some container images. +- **Follow-up work:** the two pull requests in the slice plan; a billing ADR (rounding of the monthly + total, the lock policy for finalised months); delivery pauses; authentication and household + isolation. + +## Alternatives considered + +- **Money as decimal rupees or floating point.** The same objection as in ADR 0002: every boundary + between .NET, JSON and JavaScript must keep the decimal exact. Floating point drifts. +- **Rounding each delivery, or storing a price per millilitre.** Per-delivery rounding overstates + bills and cannot be checked with a calculator. A price in thousandths of a paisa is exact but + unnatural to enter and read. +- **A price stored on every delivery.** Simple to read, but wrong when a rate is entered late and + duplicated across thousands of rows. +- **Rates with a from and a to date.** Ranges can overlap or leave gaps. An effective-from date + cannot. +- **A `pending` delivery row for every recipient and day.** Needs a job to create it, and turns a + missed job into false data. +- **An `is_archived` flag, or deleting recipients with cascading deletes.** A flag loses when the + recipient was active. Cascades destroy billing history. +- **Only a `household_id` column plus a query filter.** One missed filter leaks data. PostgreSQL + row-level security is a good extra layer later, but it needs a per-request session setting and a + database role that does not own the tables. A schema or database per household is far too heavy. +- **`DateTime` or `DateTimeOffset` for dates, or a "today" sent by the browser.** Midnight + conventions and zone conversions cause off-by-one days. +- **Always recomputing bills, never freezing them.** History would change whenever a rate does. +- **A stored running balance.** It cannot be audited and would be exposed to lost updates. +- **Editable finalised bills with an audit log.** More machinery than adjustments, and a weaker + guarantee. +- **Database-generated ids (identity columns).** Predictable, and unable to create a record without + a round trip. diff --git a/docs/architecture/decisions/README.md b/docs/architecture/decisions/README.md index 71cff6a..1069888 100644 --- a/docs/architecture/decisions/README.md +++ b/docs/architecture/decisions/README.md @@ -8,5 +8,6 @@ decided and why. Copy [0000-template.md](0000-template.md) to the next number to | [0001](0001-monorepo-and-onion-architecture.md) | Monorepo with a Next.js web app and an Onion-architecture ASP.NET Core API | Proposed | | [0002](0002-quantities-in-whole-millilitres.md) | Store and transmit milk quantities as whole millilitres | Proposed | | [0003](0003-web-app-calls-api-directly.md) | The web app calls the API directly (CORS) until authentication is designed | Proposed | +| [0004](0004-domain-model-for-household-deliveries.md) | Domain model for households, recipients, milk rates and daily deliveries; money as whole paise | Proposed | Statuses: **Proposed** (awaiting maintainer review) → **Accepted** → optionally **Superseded by NNNN**. diff --git a/docs/architecture/domain-model.md b/docs/architecture/domain-model.md new file mode 100644 index 0000000..d22d213 --- /dev/null +++ b/docs/architecture/domain-model.md @@ -0,0 +1,300 @@ +# Domain model + +> **Status: proposed.** Nothing on this page is implemented yet. It is the design behind +> [ADR 0004](decisions/0004-domain-model-for-household-deliveries.md), which records why. The +> [slice 1 plan](../plans/slice-1-recipients-and-deliveries.md) says how and when it gets built. + +This page covers the model for the first working slice (households, recipients, milk rates and daily +deliveries) and sketches the billing tables that come later, so you can see that the slice-1 tables +do not have to change when billing is added. + +## Aggregates and value objects + +Four aggregate roots, each with its own repository. All live in `PureFreshMilk.Domain`, which stays +free of any package reference. + +| Aggregate | Holds | Notes | +| --- | --- | --- | +| `Household` | Name, time zone id | Owns the notion of "today". In slice 1 there is exactly one. | +| `Recipient` | Name, usual quantity, `starts_on`, `archived_from` | Never deleted. Knows whether it is active on a date. | +| `MilkRate` | Effective-from date, price per litre | `RateSchedule` (a pure type built from a household's rates) answers "which rate applies on this date". | +| `Delivery` | Recipient, date, status, delivered quantity | Unbounded growth, so it is not a child of `Recipient`. | + +| Value object | State | Status | +| --- | --- | --- | +| `Quantity` | Whole millilitres, non-negative | Exists ([ADR 0002](decisions/0002-quantities-in-whole-millilitres.md)) | +| `PricePerLitre` | Whole paise per litre, 1 to 1,000,000 | New in the first pull request | +| `Money` | Signed whole paise, checked arithmetic | New with billing | +| `HouseholdId`, `RecipientId`, `MilkRateId`, `DeliveryId` | A UUIDv7 each | New, one per aggregate | +| `DeliveryStatus` | `Delivered` or `Missed` | New in the second pull request | + +Dates are `DateOnly`. There is no wrapper type. + +Relationships: a household has many recipients, many rates and many deliveries; a recipient has many +deliveries. A delivery belongs to a recipient *and* carries the household's id, and the database +requires the two to agree. + +## Tables for slice 1 + +Planned PostgreSQL tables. Types are PostgreSQL types. `households`, `recipients` and `milk_rates` +arrive with the first pull request and `deliveries` with the second. + +```mermaid +erDiagram + households ||--o{ recipients : "has" + households ||--o{ milk_rates : "sets prices" + households ||--o{ deliveries : "owns" + recipients ||--o{ deliveries : "receives" + + households { + uuid id PK "UUIDv7" + varchar(80) name + varchar(64) time_zone_id "IANA id, for example Asia/Kolkata" + timestamptz created_at + timestamptz updated_at + } + + recipients { + uuid id PK "UUIDv7" + uuid household_id FK + varchar(80) name + varchar(80) name_key "generated: lower(name)" + integer expected_ml "usual daily quantity, 1 to 20000" + date starts_on "first day a delivery is expected" + date archived_from "null while active; first day without deliveries" + timestamptz created_at + timestamptz updated_at + } + + milk_rates { + uuid id PK "UUIDv7" + uuid household_id FK + date effective_from "in force from this day" + bigint price_per_litre_paise "1 to 1000000" + timestamptz created_at + timestamptz updated_at + } + + deliveries { + uuid id PK "UUIDv7" + uuid household_id FK "with recipient_id, a composite FK" + uuid recipient_id FK + date delivery_date "in the household time zone" + varchar(16) status "delivered or missed" + integer delivered_ml "0 when missed" + timestamptz created_at + timestamptz updated_at + } +``` + +### Constraints and indexes + +The diagram cannot show composite keys, checks or indexes, so they are listed here. + +| Table | Constraint or index | Why | +| --- | --- | --- | +| `households` | `CHECK (length(btrim(name)) BETWEEN 1 AND 80)` | No blank names. | +| `recipients` | `UNIQUE (household_id, id)` | The target for composite foreign keys from child tables. | +| `recipients` | `FK household_id → households (id)`, `ON DELETE RESTRICT` | History must outlive any deletion attempt. | +| `recipients` | `CHECK (expected_ml BETWEEN 1 AND 20000)` | A sane daily quantity. | +| `recipients` | `CHECK (archived_from IS NULL OR archived_from > starts_on)` | A recipient is active for at least one day. | +| `recipients` | `CHECK (length(btrim(name)) BETWEEN 1 AND 80)` | No blank names. | +| `recipients` | `UNIQUE (household_id, name_key) WHERE archived_from IS NULL` | Active names are unique, ignoring case. `name_key` is a stored generated column; archived names can be reused. | +| `milk_rates` | `FK household_id → households (id)`, `ON DELETE RESTRICT` | | +| `milk_rates` | `UNIQUE (household_id, effective_from)` | One price per household per start date. | +| `milk_rates` | `CHECK (price_per_litre_paise BETWEEN 1 AND 1000000)` | Positive, and small enough that amounts cannot overflow. | +| `deliveries` | `FK (household_id, recipient_id) → recipients (household_id, id)`, `ON DELETE RESTRICT` | A delivery cannot point at another household's recipient. | +| `deliveries` | `UNIQUE (recipient_id, delivery_date)` | One delivery per recipient per day. Also serves per-recipient date ranges. | +| `deliveries` | `INDEX (household_id, delivery_date)` | The day sheet and every history range filter on exactly these two columns. | +| `deliveries` | `CHECK (status IN ('delivered', 'missed'))` | Status as text, readable in SQL. | +| `deliveries` | `CHECK ((status = 'delivered' AND delivered_ml BETWEEN 1 AND 20000) OR (status = 'missed' AND delivered_ml = 0))` | The quantity matches the status. | + +There are no other secondary indexes. The tables are small; add an index when a real query needs one. + +The rule "a delivery date cannot be after today" depends on the household's time zone, so it is +enforced by the Application, not by a `CHECK`. + +## Billing tables (planned, not built in slice 1) + +Shown so that the model is judged complete. None of these tables exists in either pull request of +the slice. Every table carries `household_id`, and references use composite keys like the ones above. + +A **bill** exists only once it is finalised. Before that, the month's figures are calculated from +deliveries and rates on request. A **balance** is never stored: it is the sum of finalised bills and +adjustments, minus payments that are not voided. `households` and `recipients` appear below without +columns; they are the tables defined above. + +```mermaid +erDiagram + households ||--o{ bills : "has" + bills ||--|{ bill_lines : "contains" + recipients ||--o{ bill_lines : "billed on" + households ||--o{ adjustments : "has" + bills |o--o{ adjustments : "may correct" + recipients |o--o{ adjustments : "may concern" + households ||--o{ payments : "has" + recipients |o--o{ payments : "may be for" + + bills { + uuid id PK + uuid household_id FK + date period_start "first day of the month, household zone" + date period_end "last day of the month" + bigint delivered_ml "sum of the lines" + bigint total_paise "sum of the lines" + timestamptz finalised_at + } + + bill_lines { + uuid id PK + uuid bill_id FK + uuid household_id FK + uuid recipient_id FK + varchar(80) recipient_name "as it was when finalised" + date from_date "first day this rate applied in the month" + date to_date "last day this rate applied in the month" + bigint delivered_ml + bigint price_per_litre_paise + bigint amount_paise "rounded once, see ADR 0004" + } + + adjustments { + uuid id PK + uuid household_id FK + uuid bill_id FK "null if not tied to a bill" + uuid recipient_id FK "null if for the household" + date entered_on + bigint amount_paise "signed, never zero" + varchar(200) reason + timestamptz created_at + } + + payments { + uuid id PK + uuid household_id FK + uuid recipient_id FK "null if for the household" + date paid_on + bigint amount_paise "greater than zero" + varchar(32) method "optional" + varchar(200) note "optional" + timestamptz created_at + timestamptz voided_at "null unless voided" + } +``` + +Why the slice-1 tables fit this without change: + +- Deliveries hold facts only (date and millilitres), so no money column ever has to be added to them + or rewritten. +- Rates are effective-dated, so a bill line can be derived for any period, and a line's own price is + copied into `bill_lines` when the bill is finalised. +- The household's time zone defines month boundaries, so periods need no extra data. +- `starts_on` and `archived_from` say which days a delivery was expected, which is what "unrecorded + days" in a month means. +- `bills` has one row per household and month (`UNIQUE (household_id, period_start)`). If each + recipient turns out to be billed separately, that is the one place a column has to be added, which + is why the question is listed before billing starts. + +### Worked examples for the rounding rule + +Rates are in paise per litre. `amount = round_half_up(delivered_ml × price ÷ 1000)`. + +| Case | Calculation | Result | +| --- | --- | --- | +| One delivery of 250 ml at ₹62.50 (6,250) | 250 × 6,250 ÷ 1,000 = 1,562.5 | 1,563 paise | +| 30 days of 250 ml at ₹62.50, rounded once | 7,500 × 6,250 ÷ 1,000 | 46,875 paise (₹468.75) | +| The same, rounded per delivery (rejected) | 30 × 1,563 | 46,890 paise (15 paise too much) | +| Rate change on 15 October, 1 L a day: ₹60.00 to 14 October, ₹64.00 from 15 October | 14,000 × 6,000 ÷ 1,000 + 17,000 × 6,400 ÷ 1,000 = 84,000 + 108,800 | 192,800 paise (₹1,928.00), as two lines | + +## Invariants that need tests + +Each rule below needs a test before the pull request that introduces it can merge. The level says +where the test belongs: + +- **D**: a Domain unit test, with no framework and no database. +- **A**: an Application handler test, using in-memory repositories. +- **I**: an integration test against real PostgreSQL (the database checks cannot be tested any other + way). +- **API**: a contract test through the in-memory HTTP pipeline. + +Rules already covered by `QuantityTests` (non-negative, whole millilitres, checked addition) are not +repeated. + +### Household + +| ID | Rule | Level | PR | +| --- | --- | --- | --- | +| H-1 | The name is trimmed and has 1 to 80 characters. | D | A | +| H-2 | The time zone must be a valid IANA id; an unknown id is rejected. | D | A | +| H-3 | `Today(utcNow)` uses the household's zone. At 18:29 UTC on 30 Oct 2026 it is 30 Oct in `Asia/Kolkata`; at 18:30 UTC it is 31 Oct. | D | A | +| H-4 | `Asia/Kolkata` resolves on every platform CI runs on, so missing time zone data fails loudly. | D | A | +| H-5 | Single-household mode never serves more than one household. | A | A | + +### Recipient + +| ID | Rule | Level | PR | +| --- | --- | --- | --- | +| R-1 | The name is trimmed and has 1 to 80 characters. | D | A | +| R-2 | The usual quantity is 1 to 20,000 ml. | D | A | +| R-3 | The start date is required (the default `DateOnly` is rejected). | D | A | +| R-4 | `IsActiveOn(d)`: false before `starts_on`, true on it, true on the day before `archived_from`, false on `archived_from` and after, always true after `starts_on` when not archived. | D | A | +| R-5 | `Archive(from)` needs `from > starts_on`; archiving an archived recipient is rejected; `Unarchive` clears the date. | D | A | +| R-6 | Archiving needs `archived_from` after the recipient's latest delivery date. | A | B | +| R-7 | Moving `starts_on` later than the earliest delivery is rejected. | A | B | +| R-8 | Active names are unique, ignoring case ("Recipient A" and "recipient a" collide); an archived name can be reused; unarchiving into a taken name is rejected. | A, I | A | +| R-9 | The default list hides archived recipients; `includeArchived` shows them. | A | A | +| R-10 | Changing the usual quantity leaves existing deliveries unchanged. | A | B | + +### Milk rate and rate schedule + +| ID | Rule | Level | PR | +| --- | --- | --- | --- | +| T-1 | A price is 1 to 1,000,000 paise a litre; zero and negative are rejected. | D | A | +| T-2 | `RateSchedule.RateOn(d)`: no rate before the first; the new rate applies on its effective-from day; the old rate applies the day before; the result does not depend on the order rates were added (back-dating works). | D | A | +| T-3 | A second rate with the same effective-from date is rejected with a conflict. | A, I | A | +| T-4 | A first rate dated in the past is accepted. | A | A | +| T-5 | `in-effect` with no applicable rate answers "none", not zero. | A, API | A | +| T-6 | A rate that governs any date in a finalised bill cannot be changed or deleted. | A | Billing | + +### Delivery + +| ID | Rule | Level | PR | +| --- | --- | --- | --- | +| L-1 | `delivered` needs at least 1 ml. | D | B | +| L-2 | `missed` has 0 ml; a `missed` request carrying a positive quantity is rejected. | D | B | +| L-3 | A quantity above 20,000 ml is rejected. | D | B | +| L-4 | An omitted quantity copies the recipient's usual quantity into the row. | D | B | +| L-5 | A date after the household's today is rejected; today is accepted. | A | B | +| L-6 | A recipient who is not active on the date is rejected. | D | B | +| L-7 | Recording again replaces the record rather than adding a second. `delivered` → `missed` sets 0 ml; `missed` → `delivered` without a quantity uses the usual quantity. | D, A | B | +| L-8 | Clearing returns the day to `notRecorded`; clearing a day with no record is a no-op. | A | B | +| L-9 | A delivery cannot reference a recipient of another household. | I | B | +| L-10 | Two simultaneous records for the same recipient and day leave exactly one row, and the loser is handled. | I | B | +| L-11 | A recipient with deliveries cannot be deleted. | I | B | +| L-12 | The status and quantity checks reject `(delivered, 0)`, `(missed, 500)` and an unknown status. | I | B | +| L-13 | The day sheet lists the recipients active that day; those without a row are `notRecorded`; the totals add up. | A | B | +| L-14 | "Deliver remaining" touches only `notRecorded` rows, uses each usual quantity, and is atomic. | A, I | B | +| L-15 | A range of more than 366 days, or `from` after `to`, is rejected. | A | B | + +### Persistence + +| ID | Rule | Level | PR | +| --- | --- | --- | --- | +| P-1 | The migration applies to an empty database, and the model has no changes beyond it. | I | A | +| P-2 | Dates round-trip as `DateOnly` with no shift, and typed ids round-trip. | I | A | +| P-3 | With the global filter (later), a query as one household never returns another's rows. | I | Auth | + +### Billing (designed now, tested when built) + +| ID | Rule | Level | +| --- | --- | --- | +| B-1 | Month boundaries follow the household zone, including a delivery near midnight. | D | +| B-2 | A month with a rate change splits into one line per rate (the 192,800 paise example above). | D | +| B-3 | Rounding happens once per line (the 46,875 paise example above), with exact midpoints rounding up. | D | +| B-4 | Arithmetic is checked; overflow throws. | D | +| B-5 | Finalising a month with delivered milk on an unpriced date is refused. | A | +| B-6 | Finalising the same month twice is rejected. | A | +| B-7 | A finalised bill does not change when a rate, a recipient or a delivery is changed later. | A, I | +| B-8 | Changing or clearing a delivery in a finalised month is rejected. | A | +| B-9 | Balance = bills + adjustments − non-voided payments, whatever order they were entered in. | D | +| B-10 | A payment is greater than zero; an adjustment is not zero and has a reason. | D | diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index b23faf3..a18e2e9 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -164,11 +164,16 @@ Rules: ## What is not implemented yet +The model for the next slice (households, recipients, milk rates and daily deliveries) is proposed +in [ADR 0004](decisions/0004-domain-model-for-household-deliveries.md), with the tables and the +invariants that need tests in [Domain model](domain-model.md) and the build order in the +[slice 1 plan](../plans/slice-1-recipients-and-deliveries.md). + | Area | State | | --- | --- | -| Persistence | `PureFreshMilkDbContext` exists with no entities and no migrations. | +| Persistence | `PureFreshMilkDbContext` exists with no entities and no migrations. The first model is designed, not built. | | Recipients, deliveries, history, month view | Web screens are placeholders or demo-data prototypes. No API endpoints. | -| Billing: prices, charges, payments, balances | Not started. Will be server-side only. | +| Billing: prices, charges, payments, balances | Not started. Will be server-side only. Money is designed as whole paise in ADR 0004. | | Authentication and households | Not started. Login and sign-up are disabled previews. | | Household data isolation | Designed (above), not built. | | Deployment, TLS termination, forwarded headers, rate limiting | Not decided. No hosting target yet. | diff --git a/docs/github-settings.md b/docs/github-settings.md new file mode 100644 index 0000000..c82b60e --- /dev/null +++ b/docs/github-settings.md @@ -0,0 +1,121 @@ +# GitHub settings for maintainers + +Some protections live in the repository's GitHub settings, not in files. Files in this repository +cannot turn them on, and this page does not record whether they are on. Use the checklist at the +end to see what is left. GitHub renames menu entries now and then; if a label differs, search the +settings page for the feature name. + +## Dependabot + +`.github/dependabot.yml` configures weekly version updates for the web app (npm), the backend +(NuGet) and the GitHub Actions in `.github/workflows`. It starts working once it is on `main`. +Check **Insights → Dependency graph → Dependabot** afterwards for configuration errors. + +Turn on the parts that are settings, in **Settings → Advanced Security** (labelled **Code security** +in some versions): + +1. **Dependency graph**: Enable. +2. **Dependabot alerts**: Enable. +3. **Dependabot security updates**: Enable. + +Things to know: + +- Each ecosystem opens at most 5 pull requests. Updates to `next`/`eslint-config-next`, to the React + packages, and to the EF Core / ASP.NET Core / Extensions packages arrive as one grouped pull + request each. Commit messages start with `chore(deps):`. +- TypeScript and ESLint major versions are ignored on purpose; minor and patch updates still arrive. +- The backend builds with warnings as errors and NuGet audit is on. A newly published advisory for + a package we use fails the build until the package is updated, which the security-update pull + request does for you. + +## CodeQL code scanning + +Use GitHub's **default setup**. Do not add a custom `codeql.yml` for now: + +- Nothing here needs custom queries, path filters or build commands. Both stacks build with the + plain commands CI already uses. +- Default setup has no workflow file to maintain or update. +- The repository is public, so scanning on GitHub-hosted runners is free. + +Steps: + +1. Open **Settings → Advanced Security**. +2. Under **Code scanning**, find **CodeQL analysis** and choose **Set up → Default**. +3. Check that the languages are **Actions**, **C#** and **JavaScript / TypeScript**. +4. Leave **Query suite** on **Default** and the runner on **Standard GitHub runner**. +5. Choose **Enable CodeQL**. + +Results appear under **Security → Code scanning**. Switch to an advanced workflow only if you later +need custom queries, path filters, a manual build, or a self-hosted runner. + +## Private vulnerability reporting + +`SECURITY.md` tells reporters to use GitHub Security Advisories. That only works once you enable it: + +1. Open **Settings → Advanced Security**. +2. Next to **Private vulnerability reporting**, choose **Enable**. +3. Check it: open + in a private + window. You should see the report form. +4. To get notified, choose **Watch → Custom → Security alerts** on the repository. + +Until it is enabled, the fallback paragraph in `SECURITY.md` applies. + +## Ruleset for `main` + +The ruleset blocks force pushes and deletion of `main` and requires the three CI checks. It does +not require review approvals, because there is a single maintainer. + +1. Open **Settings → Rules → Rulesets → New ruleset → New branch ruleset**. +2. **Ruleset name**: `Protect main`. **Enforcement status**: **Active**. +3. **Bypass list**: leave it empty. +4. **Target branches**: **Add target → Include default branch**. +5. Under **Branch rules**, tick: + - **Restrict deletions** + - **Block force pushes** + - **Require status checks to pass**, then **Add checks** and add these three. Pick them from + the list instead of typing; the dash is an em dash (U+2014): + - `Web — format, lint, types, tests, build` + - `API — format, build, tests` + - `Database — Compose PostgreSQL + API readiness` + - Leave **Require branches to be up to date before merging** unticked. +6. Leave every review option unticked. Choose **Create**. + +Checks are matched by name. If a job's `name:` changes in `.github/workflows/ci.yml`, update the +ruleset in the same change, or merges wait for a check that no longer exists. + +CI runs on pull requests and on pushes to `main` only. A commit pushed straight to `main` has no +passing checks yet, so GitHub rejects it. In practice, changes reach `main` through a pull request +with no required approvals. If you want that to be explicit, you can also tick **Require a pull +request before merging** with **Required approvals** set to `0`. + +### Emergency recovery + +For an ordinary mistake, fix forward with a revert pull request. Do not force-push. + +For a real emergency, such as publishing a secret or the wrong history, keep the exception +deliberate instead of giving anyone a standing bypass: + +1. **Settings → Rules → Rulesets → Protect main → Enforcement status → Disabled**, then **Update**. +2. Rewrite `main` with a lease, naming the commit you expect it to be on: + `git push --force-with-lease=main: origin :main` +3. Set **Enforcement status** back to **Active** immediately. + +A bypass actor, even one limited to repository admins, could force-push at any time without these +steps. Rotate any exposed secret; rewriting history does not remove it from clones and forks. + +## Code of Conduct contact + +This is not a GitHub setting. `CODE_OF_CONDUCT.md` has no private contact for conduct reports yet. +Pick a private contact you control and monitor, replace the paragraph marked +`MAINTAINER ACTION REQUIRED` in that file, and delete the comment. Do not use private vulnerability +reporting for conduct reports. + +## Checklist + +- [ ] Dependency graph, Dependabot alerts and Dependabot security updates enabled +- [ ] `.github/dependabot.yml` on `main`, and **Insights → Dependency graph → Dependabot** shows no errors +- [ ] CodeQL default setup enabled for Actions, C# and JavaScript / TypeScript +- [ ] Private vulnerability reporting enabled and verified in a private window +- [ ] `Protect main` ruleset active with the three status checks +- [ ] Code of Conduct contact published diff --git a/docs/plans/slice-1-recipients-and-deliveries.md b/docs/plans/slice-1-recipients-and-deliveries.md new file mode 100644 index 0000000..1a1d999 --- /dev/null +++ b/docs/plans/slice-1-recipients-and-deliveries.md @@ -0,0 +1,390 @@ +# Slice 1 plan: recipients, milk rates and daily deliveries + +> **Status: proposed, awaiting maintainer review.** This plan changes no code. The model it builds is +> described in [Domain model](../architecture/domain-model.md) and justified in +> [ADR 0004](../architecture/decisions/0004-domain-model-for-household-deliveries.md). + +Slice 1 is the first time PureFreshMilk stores anything. It replaces the demo data behind the +Recipients and Today screens with a real household, in two pull requests: + +| PR | Delivers | Replaces demo data on | +| --- | --- | --- | +| A | Household, recipients and milk rates, end to end | Recipients, Settings | +| B | Daily deliveries and history, end to end | Today, History | + +Out of scope for the slice: monthly bills, payments, authentication, multiple households, delivery +pauses, deployment. Money appears only as the milk price a household enters. + +## API + +All routes are under `/api/v1`. They follow the conventions already in +[the architecture overview](../architecture/overview.md): feature folders, thin endpoints, explicit +request and response records, RFC 9457 Problem Details. + +### Conventions + +| Topic | Rule | +| --- | --- | +| Names | camelCase JSON. Units are in the name: `expectedMl`, `deliveredMl`, `pricePerLitrePaise`. | +| Dates and times | A date is `"2026-10-30"`. An instant is ISO 8601 in UTC. Never a `Date` built from a date-only string in the browser. | +| Enums | Camel-case strings (`"delivered"`), never numbers. | +| Ids | UUID strings. | +| Lists | An object with an `items` array, so fields can be added later without breaking clients. | +| Errors | `400` for input that is invalid, `404` for something that does not exist, `409` for a clash with stored data. Problem Details with an extra `code` member that clients can branch on (for example `recipient-name-taken`). No stack traces. | +| Retries | `PUT` and `DELETE` are idempotent, so a flaky phone connection can safely retry them. | +| Household | Not in any URL. The server resolves it ([single-household mode](#questions-to-decide-before-pr-a)). | +| Authentication | None yet. Adding it later changes no route. | + +### Household and recipients (PR A) + +| Method and path | What it does | Success | Errors | +| --- | --- | --- | --- | +| `GET /household` | Reads the household, including `today` in its time zone. | 200 | 404 `household-not-set-up` | +| `PUT /household` | Creates the household the first time, then updates it. Body: `name`, `timeZoneId`. | 201, then 200 | 400 | +| `GET /recipients?includeArchived=false` | Lists recipients, ordered by name. | 200 | | +| `POST /recipients` | Adds a recipient. Body: `name`, `expectedMl`, optional `startsOn` (default: today). | 201 and `Location` | 400, 409 `recipient-name-taken` | +| `GET /recipients/{id}` | Reads one. | 200 | 404 | +| `PUT /recipients/{id}` | Replaces the editable fields: `name`, `expectedMl`, `startsOn`. | 200 | 400, 404, 409 | +| `POST /recipients/{id}/archive` | Archives from `archivedFrom` (default: the later of today and the day after the latest delivery). | 200 | 400, 404, 409 `recipient-already-archived` | +| `POST /recipients/{id}/unarchive` | Clears the archive date. | 200 | 404, 409 `recipient-name-taken` | + +There is deliberately no `DELETE /recipients/{id}`. + +```json +{ + "id": "0199f3a2-7c1e-7b52-9d0a-3f1c2a4b5c60", + "name": "Recipient A", + "expectedMl": 1000, + "startsOn": "2026-10-01", + "archivedFrom": null +} +``` + +### Milk rates (PR A) + +| Method and path | What it does | Success | Errors | +| --- | --- | --- | --- | +| `GET /milk-rates` | Lists rates, newest effective date first. | 200 | | +| `GET /milk-rates/in-effect?on=2026-10-30` | The rate in force on a date (default: today). | 200 | 404 `no-rate-in-effect` | +| `POST /milk-rates` | Adds a rate. Body: `effectiveFrom`, `pricePerLitrePaise`. | 201 | 400, 409 `rate-date-taken` | +| `PUT /milk-rates/{id}` | Changes a rate. | 200 | 400, 404, 409 | +| `DELETE /milk-rates/{id}` | Removes a rate. | 204 | 404 | + +```json +{ "id": "0199f3a2-8d4f-7e10-a6b3-1c9d0e7f2a11", "effectiveFrom": "2026-10-01", "pricePerLitrePaise": 6250 } +``` + +Once billing exists, `PUT` and `DELETE` also answer `409 period-finalised` for a rate that governs a +finalised month. + +### Day sheets and history (PR B) + +`{date}` is `YYYY-MM-DD` or the word `today`, which the server resolves in the household's zone. + +| Method and path | What it does | Success | Errors | +| --- | --- | --- | --- | +| `GET /day-sheets/{date}` | One row per recipient active that day, with its state and the day's totals. | 200 | 400 `future-date` | +| `PUT /recipients/{recipientId}/deliveries/{date}` | Records a delivery. Body: `status`, optional `deliveredMl` (default: the usual quantity). | 201 new, 200 replaced | 400, 404, 409 `recipient-not-active` | +| `DELETE /recipients/{recipientId}/deliveries/{date}` | Clears the record; the day returns to `notRecorded`. | 204 | 404 (recipient) | +| `POST /day-sheets/{date}/deliver-remaining` | Records every `notRecorded` recipient as delivered at the usual quantity, in one transaction. Returns the day sheet. | 200 | 400 `future-date` | +| `GET /day-summaries?from=2026-10-01&to=2026-10-31` | One line of totals per day, newest first. At most 366 days. | 200 | 400 | + +`PUT` and `DELETE` also answer `409 period-finalised` once billing exists. + +```json +{ + "date": "2026-10-30", + "isToday": true, + "rows": [ + { "recipientId": "0199f3a2-7c1e-7b52-9d0a-3f1c2a4b5c60", "name": "Recipient A", "expectedMl": 1000, "status": "delivered", "deliveredMl": 1000 }, + { "recipientId": "0199f3a2-7c9a-7d33-8e41-6b2f9a0c1d72", "name": "Recipient B", "expectedMl": 500, "status": "notRecorded", "deliveredMl": 0 } + ], + "totals": { "expectedMl": 1500, "deliveredMl": 1000, "delivered": 1, "missed": 0, "notRecorded": 1 } +} +``` + +The server computes the totals. `features/today/today-state.ts` does that arithmetic on the client +today only because nothing is stored; PR B removes it. + +## Test strategy + +- **No new dependencies.** Fakes are hand-written; PostgreSQL is the Compose container that CI + already starts. +- **`dotnet test` stays database-free by default.** Tests that need PostgreSQL carry + `[Trait("Category", "Database")]`, live in `PureFreshMilk.Infrastructure.Tests`, and are excluded + from the `api` job and from `scripts/check.*`. xUnit v3 supports trait filters; the exact option for + `dotnet test` on Microsoft.Testing.Platform is confirmed when PR A wires it in. The `database` job + runs them. A database test never skips silently: with no connection string it fails and says how + to start PostgreSQL. +- **Each database test class gets a throwaway database**, created from the migrations and dropped + afterwards, through `ConnectionStrings__PureFreshMilkTests`. +- **Contract tests for the API use in-memory repositories**, registered in + `PureFreshMilkApiFactory`, so they need no database. The database behaviour is covered by the + Infrastructure tests. +- **The `database` CI job gets more steps, not a new name.** The ruleset on `main` matches check + names literally, so `Database — Compose PostgreSQL + API readiness` must not change. +- **Browser tests keep running without an API** (demo mode). Real-data flows are covered by Vitest + with a stubbed `fetch` and by the API tests. + +## PR A: household, recipients and milk rates + +Branch `feat/households-recipients-rates`. Suggested commit order inside the pull request, so it can +be reviewed layer by layer: Domain with tests, Application with tests, Infrastructure with migration +and database tests, Api with contract tests, web app, CI and docs. + +### Domain (`backend/src/PureFreshMilk.Domain/`) + +New: + +- `Households/HouseholdId.cs`, `Households/Household.cs` +- `Recipients/RecipientId.cs`, `Recipients/Recipient.cs` +- `Rates/MilkRateId.cs`, `Rates/PricePerLitre.cs`, `Rates/MilkRate.cs`, `Rates/RateSchedule.cs` + +### Application (`backend/src/PureFreshMilk.Application/`) + +New: + +- `Common/NotFoundException.cs`, `Common/ConflictException.cs` (both carry a stable `Code`) +- `Persistence/IUnitOfWork.cs` +- `Households/ICurrentHousehold.cs`, `Households/IHouseholdRepository.cs`, + `Households/HouseholdDetails.cs`, `Households/GetHouseholdHandler.cs`, + `Households/SetUpHouseholdHandler.cs` +- `Recipients/IRecipientRepository.cs`, `Recipients/RecipientDetails.cs`, + `Recipients/ListRecipientsHandler.cs`, `Recipients/GetRecipientHandler.cs`, + `Recipients/AddRecipientHandler.cs`, `Recipients/UpdateRecipientHandler.cs`, + `Recipients/ArchiveRecipientHandler.cs`, `Recipients/UnarchiveRecipientHandler.cs` +- `Rates/IMilkRateRepository.cs`, `Rates/MilkRateDetails.cs`, `Rates/ListMilkRatesHandler.cs`, + `Rates/GetRateInEffectHandler.cs`, `Rates/AddMilkRateHandler.cs`, + `Rates/UpdateMilkRateHandler.cs`, `Rates/DeleteMilkRateHandler.cs` + +Edited: `ApplicationServiceCollectionExtensions.cs` (register the handlers). + +### Infrastructure (`backend/src/PureFreshMilk.Infrastructure/`) + +New: + +- `Persistence/Configurations/HouseholdConfiguration.cs`, `RecipientConfiguration.cs`, + `MilkRateConfiguration.cs` +- `Persistence/Repositories/HouseholdRepository.cs`, `RecipientRepository.cs`, + `MilkRateRepository.cs` +- `Persistence/UnitOfWork.cs` +- `Persistence/MigrationsAppliedHealthCheck.cs` (optional: `/health/ready` fails while migrations are + pending, instead of every request failing with "relation does not exist") +- `Households/SingleHouseholdProvider.cs` (the `ICurrentHousehold` for single-household mode) +- `Persistence/Migrations/_AddHouseholdsRecipientsAndMilkRates.cs`, its `.Designer.cs`, + and `PureFreshMilkDbContextModelSnapshot.cs` (generated with `dotnet ef`, see + [development.md](../development.md#database-migrations)) + +Edited: `Persistence/PureFreshMilkDbContext.cs` (sets, `ApplyConfigurationsFromAssembly`, converters +for typed ids), `InfrastructureServiceCollectionExtensions.cs`, `PureFreshMilk.Infrastructure.csproj` +(`InternalsVisibleTo` for the new test project; the context stays `internal`). + +### Api (`backend/src/PureFreshMilk.Api/`) + +New: + +- `Features/Households/HouseholdEndpoints.cs`, `HouseholdResponse.cs`, `SetUpHouseholdRequest.cs` +- `Features/Recipients/RecipientEndpoints.cs`, `RecipientResponse.cs`, `RecipientRequests.cs` +- `Features/MilkRates/MilkRateEndpoints.cs`, `MilkRateResponse.cs`, `MilkRateRequests.cs` +- `Hosting/ApplicationExceptionHandler.cs` (maps `DomainException` to 400, + `NotFoundException` to 404, `ConflictException` to 409, all as Problem Details) +- `Hosting/UnauthenticatedAccess.cs` (the guard described under the questions below) + +Edited: `Program.cs` (map the endpoints, string enums, the guard), `appsettings.Development.json` +(`Access:AllowUnauthenticated`: `true`). + +### Backend tests (`backend/tests/`) + +New: + +- `PureFreshMilk.Domain.Tests/Households/HouseholdTests.cs`, + `Recipients/RecipientTests.cs`, `Rates/PricePerLitreTests.cs`, `Rates/MilkRateTests.cs`, + `Rates/RateScheduleTests.cs` +- `PureFreshMilk.TestSupport/` (class library): in-memory repositories, `FixedTimeProvider` +- `PureFreshMilk.Application.Tests/` (project): `Households/…`, `Recipients/…`, `Rates/…` handler tests +- `PureFreshMilk.Infrastructure.Tests/` (project): `DatabaseFixture.cs`, `MigrationTests.cs`, + `RecipientConstraintTests.cs`, `MilkRateConstraintTests.cs`, `RepositoryRoundTripTests.cs` +- `PureFreshMilk.Api.Tests/Features/Households/HouseholdEndpointTests.cs`, + `Features/Recipients/RecipientEndpointTests.cs`, `Features/MilkRates/MilkRateEndpointTests.cs`, + `Hosting/UnauthenticatedAccessTests.cs` + +Edited: `PureFreshMilk.Api.Tests/PureFreshMilkApiFactory.cs`, `backend/PureFreshMilk.slnx` (three +projects). The invariants covered are marked **PR A** in the +[invariant tables](../architecture/domain-model.md#invariants-that-need-tests). + +### Web app (`apps/web/`) + +New: + +- `src/services/household-service.ts`, `recipient-service.ts`, `milk-rate-service.ts` +- `src/lib/money.ts` (display only: 6250 paise → "₹62.50") +- `src/features/household/household-setup.tsx` (first-run form: name and time zone) +- `src/features/recipients/recipients-screen.tsx`, `recipient-form.tsx`, `recipient-row.tsx` +- `src/features/settings/milk-rate-card.tsx` +- `tests/unit/lib/money.test.ts`, `tests/unit/lib/dates.test.ts`, + `tests/unit/services/recipient-service.test.ts`, `tests/unit/features/recipients-screen.test.tsx`, + `tests/unit/features/milk-rate-card.test.tsx` + +Edited: + +- `src/services/api-client.ts` (adds POST, PUT and DELETE, and reads Problem Details into `ApiError`) +- `src/types/api.ts`, `src/types/household.ts` (add `startsOn` and `archivedFrom`) +- `src/lib/dates.ts` (ISO date helpers) +- `src/app/app/recipients/page.tsx`, `src/app/app/settings/page.tsx` +- `tests/unit/services/api-client.test.ts` + +Behaviour: + +- With no `NEXT_PUBLIC_API_BASE_URL`, the Recipients page stays in **demo mode** and keeps its "Demo + data" badge. +- If the API is configured but unreachable, the page shows an error with a retry button. It never + falls back to demo data silently. +- The price is edited in Settings, in the milk-rate card, with its history listed below. + +### CI, scripts and docs + +Edited: `.github/workflows/ci.yml` (the `api` job excludes database tests; the `database` job applies +migrations, runs them, and adds a curl smoke test with `Access__AllowUnauthenticated=true`; **no job +`name:` changes**), `scripts/check.sh` and `scripts/check.ps1` (exclude database tests; opt in with a +flag), `docs/development.md` (first migration, database tests, single-household mode), +`docs/architecture/overview.md` (what now exists), and ADR 0004's status once accepted. + +## PR B: daily deliveries and history + +Branch `feat/daily-deliveries`. Depends on PR A. + +### Backend + +New, in `backend/src/`: + +- `PureFreshMilk.Domain/Deliveries/DeliveryId.cs`, `DeliveryStatus.cs`, `Delivery.cs` +- `PureFreshMilk.Application/Deliveries/IDeliveryRepository.cs`, `DaySheet.cs`, `DaySummary.cs`, + `GetDaySheetHandler.cs`, `RecordDeliveryHandler.cs`, `ClearDeliveryHandler.cs`, + `DeliverRemainingHandler.cs`, `ListDaySummariesHandler.cs` +- `PureFreshMilk.Infrastructure/Persistence/Configurations/DeliveryConfiguration.cs`, + `Persistence/Repositories/DeliveryRepository.cs`, + `Persistence/Migrations/_AddDeliveries.cs` and its designer +- `PureFreshMilk.Api/Features/Deliveries/DeliveryEndpoints.cs`, `DaySheetEndpoints.cs`, + `DeliveryRequests.cs`, `DaySheetResponse.cs`, `DaySummaryResponse.cs` + +Edited: `PureFreshMilkDbContext.cs` (model snapshot regenerated), +`ApplicationServiceCollectionExtensions.cs`, `InfrastructureServiceCollectionExtensions.cs`, +`Program.cs`, `UpdateRecipientHandler.cs` and `ArchiveRecipientHandler.cs` (rules R-6 and R-7, which +need deliveries to exist). + +### Backend tests + +New, in `backend/tests/`: + +- `PureFreshMilk.Domain.Tests/Deliveries/DeliveryTests.cs` +- `PureFreshMilk.Application.Tests/Deliveries/…` (one file per handler) +- `PureFreshMilk.Infrastructure.Tests/DeliveryConstraintTests.cs`, `DeliveryConcurrencyTests.cs` +- `PureFreshMilk.Api.Tests/Features/Deliveries/DeliveryEndpointTests.cs`, + `Features/Deliveries/DaySheetEndpointTests.cs` + +Edited: the in-memory repositories in `PureFreshMilk.TestSupport/`. The invariants marked **PR B** +in the invariant tables are covered here. + +### Web app + +New: + +- `src/services/delivery-service.ts` +- `src/features/history/history-screen.tsx`, `day-summary-row.tsx` +- `src/app/app/history/[date]/page.tsx` (a past day, using the same delivery cards as Today) +- `tests/unit/services/delivery-service.test.ts`, `tests/unit/features/history-screen.test.tsx` + +Edited: + +- `src/types/household.ts`, `src/types/api.ts` (`pending` becomes `notRecorded`; day sheet types) +- `src/features/today/today-screen.tsx`, `delivery-card.tsx`, `today-summary.tsx`, `day-measure.tsx`, + `use-today-label.ts` (the date comes from the server) +- `src/features/today/today-state.ts` (shrinks to optimistic updates and rollback; the totals + arithmetic is removed) +- `src/app/app/today/page.tsx`, `src/app/app/history/page.tsx` +- `tests/unit/features/today-state.test.ts`, `tests/unit/features/today-screen.test.tsx`, + `tests/e2e/today.spec.ts` (still runs in demo mode) + +Behaviour: + +- Taps update the screen immediately and are sent in the background. A failed request restores the + previous state and says so. Because `PUT` is idempotent, a retry is safe. +- A past day opens from History and reuses the same cards. +- Demo mode stays available when no API is configured. + +### Docs + +Edited: `docs/architecture/overview.md`, `docs/development.md`, and the status of ADR 0004. + +## Questions to decide before PR A + +These change what PR A builds. Each has a recommendation, so a plain "yes" is enough. + +1. **One delivery a day, or morning and evening?** + Recommended: one record per recipient per day, holding the day's total. If you need two, the + recipient's usual quantity and the delivery key must carry a slot, and that has to be in PR A's + migration instead of being added later. +2. **One price for the whole household, or a price per recipient? One kind of milk?** + Recommended: one price series for the household, one kind of milk. If prices can differ per + recipient, `milk_rates` gets a nullable `recipient_id` now (empty means "everyone"), which is + cheap today and awkward later. +3. **Single-household mode with no login.** Until authentication exists, the API serves one + household to anyone who can reach it. Recommended: the data endpoints are mapped only in + Development and Testing, or when `Access__AllowUnauthenticated=true` is set explicitly, so a + deployed copy cannot expose data by accident. The alternative is to build authentication before + slice 1, which delays everything, or to leave the endpoints always on, which is unsafe to deploy. +4. **Recipient dates.** Recommended: a required `starts_on` and an optional `archived_from` + (decision 4 in the ADR). The alternative is a plain archived flag, which cannot tell whether a + recipient was expected on a given day, and which makes "unrecorded days" meaningless. + +## Questions that can wait + +Before PR B: + +5. **How far back can a day be edited?** Recommended: any past day in the recipient's active window, + until that month is finalised. The alternative is a limit such as the last 60 days. +6. **Does a missed delivery need a reason?** Recommended: no. + +Before billing starts: + +7. **Who is billed: the household as a whole, or each recipient separately?** Recommended: the + household, with a line per recipient. Separate bills would add a recipient to the bill's key. +8. **Is the monthly total rounded to whole rupees, or kept to the paisa?** This depends on how your + milkman bills. The model supports either. +9. **Finalised months: block changes to deliveries, or create an adjustment automatically?** + Recommended: block, and correct with an adjustment that has a reason. +10. **Pauses and non-delivery days** (travel, festivals, weekdays only). The Settings screen already + lists "Delivery days and pauses". Without them, every such day is a "not recorded" warning. +11. **A request to remove someone's data.** Recommended: replace the name and keep the billing + history. Decide before real people's names are stored for long. + +## Defaults assumed + +These were chosen without asking. Say so if any is wrong. + +- Recipients hold only a name, a usual quantity and dates. No phone number, address or photo. +- A quantity is at most 20 L per delivery in the domain. The Today screen still steps in 250 ml + and stops at 5 L. +- A price is at most ₹10,000 a litre. +- Recipient names are unique among active recipients, ignoring case. +- Migrations are applied explicitly (`dotnet ef database update`), never automatically at start-up. +- Errors map to 400, 404 and 409 only. +- Demo mode stays whenever the web app has no API address. + +## Risks + +- **No login.** Slice 1 is for local use. Do not put it on the internet before authentication + exists (question 3). +- **Real data, no backup.** The database lives in a local Docker volume. `docker compose down + --volumes` deletes it. Once real deliveries are entered, someone has to decide how they are backed + up. +- **Time zone data.** `Asia/Kolkata` needs time zone data on the machine. Slim container images may + not have it, which is why H-4 is a test. +- **A bad connection at the door.** The Today screen is used on a phone, standing at the gate. + Optimistic updates with a clear failure message are the minimum; saving taps while offline is out of + scope and will be asked for. +- **Review size.** PR A touches every layer. The commit order above is there so it can be reviewed in + pieces; if it is still too large, the natural split is backend first, then web. +- **Tool version.** Generate migrations with the `dotnet-ef` version pinned in + `backend/dotnet-tools.json` (`dotnet tool restore`), and keep it in step with the EF Core package + version, so the generated migration files do not depend on who ran the command.