From 0b95337b5efd9924c2047d7d67ca6d10f657914f Mon Sep 17 00:00:00 2001
From: Satyam Yadav <114805086+Coding-Professional@users.noreply.github.com>
Date: Mon, 23 Nov 2026 18:44:36 +0530
Subject: [PATCH 1/3] chore(web): update Next.js to patched 16.4.6
---
apps/web/package-lock.json | 100 ++++++++++++++++++-------------------
apps/web/package.json | 4 +-
2 files changed, 52 insertions(+), 52 deletions(-)
diff --git a/apps/web/package-lock.json b/apps/web/package-lock.json
index 2694f37..04ac5c1 100644
--- a/apps/web/package-lock.json
+++ b/apps/web/package-lock.json
@@ -1,17 +1,17 @@
{
- "name": "web",
+ "name": "purefreshmilk-web",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
- "name": "web",
+ "name": "purefreshmilk-web",
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"clsx": "^2.1.1",
"lucide-react": "^1.64.0",
- "next": "16.4.3",
+ "next": "16.4.6",
"react": "19.3.1",
"react-dom": "19.3.1",
"tailwind-merge": "^3.7.0"
@@ -29,7 +29,7 @@
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.2",
"eslint": "^9.39.5",
- "eslint-config-next": "16.4.3",
+ "eslint-config-next": "16.4.6",
"jsdom": "^30.1.3",
"prettier": "^3.9.10",
"tailwindcss": "^4.3.3",
@@ -1416,15 +1416,15 @@
}
},
"node_modules/@next/env": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.3.tgz",
- "integrity": "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.6.tgz",
+ "integrity": "sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA==",
"license": "MIT"
},
"node_modules/@next/eslint-plugin-next": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.3.tgz",
- "integrity": "sha512-oxuC06wt/71h6ACYCV9GbKOfnf5a7VlRe/p80YHTut15TNgDEmynDnaq8t/xhy5rlvk7dhItIPs6H3rvIM4kyw==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.6.tgz",
+ "integrity": "sha512-HdqERVOafOD8JaUSAkwf9aSu/1rsHlkN8C5GcXYBH3C/z1MxBhZFxB5rz/xqMMRiIj7r9tIv8OCLQ9JWUxCvWA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -1465,9 +1465,9 @@
}
},
"node_modules/@next/swc-darwin-arm64": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.3.tgz",
- "integrity": "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.6.tgz",
+ "integrity": "sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg==",
"cpu": [
"arm64"
],
@@ -1481,9 +1481,9 @@
}
},
"node_modules/@next/swc-darwin-x64": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.3.tgz",
- "integrity": "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.6.tgz",
+ "integrity": "sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA==",
"cpu": [
"x64"
],
@@ -1497,9 +1497,9 @@
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.3.tgz",
- "integrity": "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.6.tgz",
+ "integrity": "sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA==",
"cpu": [
"arm64"
],
@@ -1516,9 +1516,9 @@
}
},
"node_modules/@next/swc-linux-arm64-musl": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.3.tgz",
- "integrity": "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.6.tgz",
+ "integrity": "sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA==",
"cpu": [
"arm64"
],
@@ -1535,9 +1535,9 @@
}
},
"node_modules/@next/swc-linux-x64-gnu": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.3.tgz",
- "integrity": "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.6.tgz",
+ "integrity": "sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ==",
"cpu": [
"x64"
],
@@ -1554,9 +1554,9 @@
}
},
"node_modules/@next/swc-linux-x64-musl": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.3.tgz",
- "integrity": "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.6.tgz",
+ "integrity": "sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA==",
"cpu": [
"x64"
],
@@ -1573,9 +1573,9 @@
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.3.tgz",
- "integrity": "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.6.tgz",
+ "integrity": "sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ==",
"cpu": [
"arm64"
],
@@ -1589,9 +1589,9 @@
}
},
"node_modules/@next/swc-win32-x64-msvc": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.3.tgz",
- "integrity": "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.6.tgz",
+ "integrity": "sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g==",
"cpu": [
"x64"
],
@@ -4366,13 +4366,13 @@
}
},
"node_modules/eslint-config-next": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.3.tgz",
- "integrity": "sha512-j9IqBma6abp800frdUURaizYMgXOK+jNGyq6CsYcM9AxpSJs5D/TgMNGeAmRUilZvA7g9V1Tr71gNg9/SVTuMQ==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.6.tgz",
+ "integrity": "sha512-IBGGrVf9E6pL0NGL0hmeicVGeSyv1VEzIWq6IecDqkw+YFByhEtDJS9u1r6s6a1VxK6rssh69KyNFQUgfaacqw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@next/eslint-plugin-next": "16.4.3",
+ "@next/eslint-plugin-next": "16.4.6",
"eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2",
"eslint-plugin-import": "^2.32.0",
@@ -6415,12 +6415,12 @@
"license": "MIT"
},
"node_modules/next": {
- "version": "16.4.3",
- "resolved": "https://registry.npmjs.org/next/-/next-16.4.3.tgz",
- "integrity": "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==",
+ "version": "16.4.6",
+ "resolved": "https://registry.npmjs.org/next/-/next-16.4.6.tgz",
+ "integrity": "sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA==",
"license": "MIT",
"dependencies": {
- "@next/env": "16.4.3",
+ "@next/env": "16.4.6",
"@swc/helpers": "0.5.23",
"baseline-browser-mapping": "^2.9.19",
"caniuse-lite": "^1.0.30001579",
@@ -6434,14 +6434,14 @@
"node": ">=20.9.0"
},
"optionalDependencies": {
- "@next/swc-darwin-arm64": "16.4.3",
- "@next/swc-darwin-x64": "16.4.3",
- "@next/swc-linux-arm64-gnu": "16.4.3",
- "@next/swc-linux-arm64-musl": "16.4.3",
- "@next/swc-linux-x64-gnu": "16.4.3",
- "@next/swc-linux-x64-musl": "16.4.3",
- "@next/swc-win32-arm64-msvc": "16.4.3",
- "@next/swc-win32-x64-msvc": "16.4.3",
+ "@next/swc-darwin-arm64": "16.4.6",
+ "@next/swc-darwin-x64": "16.4.6",
+ "@next/swc-linux-arm64-gnu": "16.4.6",
+ "@next/swc-linux-arm64-musl": "16.4.6",
+ "@next/swc-linux-x64-gnu": "16.4.6",
+ "@next/swc-linux-x64-musl": "16.4.6",
+ "@next/swc-win32-arm64-msvc": "16.4.6",
+ "@next/swc-win32-x64-msvc": "16.4.6",
"sharp": "^0.35.5"
},
"peerDependencies": {
diff --git a/apps/web/package.json b/apps/web/package.json
index 232d324..a468987 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -21,7 +21,7 @@
"dependencies": {
"clsx": "^2.1.1",
"lucide-react": "^1.64.0",
- "next": "16.4.3",
+ "next": "16.4.6",
"react": "19.3.1",
"react-dom": "19.3.1",
"tailwind-merge": "^3.7.0"
@@ -39,7 +39,7 @@
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.2",
"eslint": "^9.39.5",
- "eslint-config-next": "16.4.3",
+ "eslint-config-next": "16.4.6",
"jsdom": "^30.1.3",
"prettier": "^3.9.10",
"tailwindcss": "^4.3.3",
From 35e798d08a159acc0af16d001fa6a2fdf7fb6be4 Mon Sep 17 00:00:00 2001
From: Satyam Yadav <114805086+Coding-Professional@users.noreply.github.com>
Date: Mon, 23 Nov 2026 18:44:49 +0530
Subject: [PATCH 2/3] feat(backend): persist daily deliveries and expose day
sheets
---
.../Features/Deliveries/DaySheetEndpoints.cs | 34 +++
.../Features/Deliveries/DaySheetResponse.cs | 25 ++
.../Features/Deliveries/DeliveryEndpoints.cs | 41 +++
.../Hosting/ApplicationExceptionHandler.cs | 7 +
backend/src/PureFreshMilk.Api/Program.cs | 3 +
.../ApplicationServiceCollectionExtensions.cs | 7 +
.../Common/ErrorCodes.cs | 3 +
.../Common/FutureDateException.cs | 7 +
.../Deliveries/ClearDeliveryHandler.cs | 24 ++
.../Deliveries/DaySheet.cs | 9 +
.../Deliveries/DeliverRemainingHandler.cs | 27 ++
.../Deliveries/DeliveryRules.cs | 38 +++
.../Deliveries/GetDaySheetHandler.cs | 34 +++
.../Deliveries/IDeliveryRepository.cs | 15 ++
.../Deliveries/ListDaySummariesHandler.cs | 48 ++++
.../Deliveries/RecordDeliveryHandler.cs | 42 +++
.../Recipients/ArchiveRecipientHandler.cs | 17 +-
.../Recipients/UpdateRecipientHandler.cs | 9 +
.../Deliveries/Delivery.cs | 61 +++++
.../Deliveries/DeliveryId.cs | 11 +
.../Deliveries/DeliveryStatus.cs | 7 +
...frastructureServiceCollectionExtensions.cs | 2 +
.../Configurations/DeliveryConfiguration.cs | 41 +++
.../20261123124513_AddDeliveries.Designer.cs | 255 ++++++++++++++++++
.../20261123124513_AddDeliveries.cs | 64 +++++
.../PureFreshMilkDbContextModelSnapshot.cs | 69 ++++-
.../Persistence/PureFreshMilkDbContext.cs | 4 +
.../Repositories/DeliveryRepository.cs | 33 +++
.../Persistence/UnitOfWork.cs | 2 +
.../Persistence/ValueConverters.cs | 4 +
.../Deliveries/DeliveryEndpointTests.cs | 74 +++++
.../Deliveries/DeliveryHandlerTests.cs | 61 +++++
.../TestHousehold.cs | 18 +-
.../Deliveries/DeliveryTests.cs | 42 +++
.../DeliveryConstraintTests.cs | 103 +++++++
.../HandlerFlowTests.cs | 8 +-
.../MigrationTests.cs | 19 +-
.../InMemoryDatabase.cs | 3 +
.../InMemoryDeliveryRepository.cs | 30 +++
.../InMemoryPersistenceExtensions.cs | 3 +
40 files changed, 1292 insertions(+), 12 deletions(-)
create mode 100644 backend/src/PureFreshMilk.Api/Features/Deliveries/DaySheetEndpoints.cs
create mode 100644 backend/src/PureFreshMilk.Api/Features/Deliveries/DaySheetResponse.cs
create mode 100644 backend/src/PureFreshMilk.Api/Features/Deliveries/DeliveryEndpoints.cs
create mode 100644 backend/src/PureFreshMilk.Application/Common/FutureDateException.cs
create mode 100644 backend/src/PureFreshMilk.Application/Deliveries/ClearDeliveryHandler.cs
create mode 100644 backend/src/PureFreshMilk.Application/Deliveries/DaySheet.cs
create mode 100644 backend/src/PureFreshMilk.Application/Deliveries/DeliverRemainingHandler.cs
create mode 100644 backend/src/PureFreshMilk.Application/Deliveries/DeliveryRules.cs
create mode 100644 backend/src/PureFreshMilk.Application/Deliveries/GetDaySheetHandler.cs
create mode 100644 backend/src/PureFreshMilk.Application/Deliveries/IDeliveryRepository.cs
create mode 100644 backend/src/PureFreshMilk.Application/Deliveries/ListDaySummariesHandler.cs
create mode 100644 backend/src/PureFreshMilk.Application/Deliveries/RecordDeliveryHandler.cs
create mode 100644 backend/src/PureFreshMilk.Domain/Deliveries/Delivery.cs
create mode 100644 backend/src/PureFreshMilk.Domain/Deliveries/DeliveryId.cs
create mode 100644 backend/src/PureFreshMilk.Domain/Deliveries/DeliveryStatus.cs
create mode 100644 backend/src/PureFreshMilk.Infrastructure/Persistence/Configurations/DeliveryConfiguration.cs
create mode 100644 backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/20261123124513_AddDeliveries.Designer.cs
create mode 100644 backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/20261123124513_AddDeliveries.cs
create mode 100644 backend/src/PureFreshMilk.Infrastructure/Persistence/Repositories/DeliveryRepository.cs
create mode 100644 backend/tests/PureFreshMilk.Api.Tests/Features/Deliveries/DeliveryEndpointTests.cs
create mode 100644 backend/tests/PureFreshMilk.Application.Tests/Deliveries/DeliveryHandlerTests.cs
create mode 100644 backend/tests/PureFreshMilk.Domain.Tests/Deliveries/DeliveryTests.cs
create mode 100644 backend/tests/PureFreshMilk.Infrastructure.Tests/DeliveryConstraintTests.cs
create mode 100644 backend/tests/PureFreshMilk.TestSupport/InMemoryDeliveryRepository.cs
diff --git a/backend/src/PureFreshMilk.Api/Features/Deliveries/DaySheetEndpoints.cs b/backend/src/PureFreshMilk.Api/Features/Deliveries/DaySheetEndpoints.cs
new file mode 100644
index 0000000..c3da165
--- /dev/null
+++ b/backend/src/PureFreshMilk.Api/Features/Deliveries/DaySheetEndpoints.cs
@@ -0,0 +1,34 @@
+using PureFreshMilk.Api.Hosting;
+using PureFreshMilk.Application.Deliveries;
+using PureFreshMilk.Domain.Common;
+
+namespace PureFreshMilk.Api.Features.Deliveries;
+
+internal static class DaySheetEndpoints
+{
+ public static IEndpointRouteBuilder MapDaySheetEndpoints(this IEndpointRouteBuilder api)
+ {
+ var sheets = api.MapGroup("/day-sheets").WithTags("Day sheets");
+ sheets.MapGet("/{date}", async (string date, GetDaySheetHandler handler, CancellationToken cancellationToken) =>
+ TypedResults.Ok(DaySheetResponse.From(await handler.HandleAsync(date, cancellationToken)))).WithName("GetDaySheet");
+ sheets.MapPost("/{date}/deliver-remaining", async (string date, DeliverRemainingHandler handler,
+ CancellationToken cancellationToken) =>
+ TypedResults.Ok(DaySheetResponse.From(await handler.HandleAsync(date, cancellationToken)))).WithName("DeliverRemaining");
+ api.MapGet("/day-summaries", async (string? from, string? to, ListDaySummariesHandler handler,
+ CancellationToken cancellationToken) =>
+ {
+ if (!DateOnly.TryParseExact(from, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture,
+ System.Globalization.DateTimeStyles.None, out var first) ||
+ !DateOnly.TryParseExact(to, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture,
+ System.Globalization.DateTimeStyles.None, out var last))
+ {
+ throw new DomainException("Both from and to must be dates in YYYY-MM-DD format.", "from");
+ }
+
+ var summaries = await handler.HandleAsync(first, last, cancellationToken);
+ return TypedResults.Ok(new ItemsResponse(
+ [.. summaries.Select(DaySummaryResponse.From)]));
+ }).WithName("ListDaySummaries").WithTags("Day sheets");
+ return api;
+ }
+}
diff --git a/backend/src/PureFreshMilk.Api/Features/Deliveries/DaySheetResponse.cs b/backend/src/PureFreshMilk.Api/Features/Deliveries/DaySheetResponse.cs
new file mode 100644
index 0000000..60217b8
--- /dev/null
+++ b/backend/src/PureFreshMilk.Api/Features/Deliveries/DaySheetResponse.cs
@@ -0,0 +1,25 @@
+using PureFreshMilk.Application.Deliveries;
+
+namespace PureFreshMilk.Api.Features.Deliveries;
+
+internal sealed record DayRowResponse(Guid RecipientId, string Name, int ExpectedMl, string Status, int DeliveredMl)
+{
+ public static DayRowResponse From(DayRow row) => new(row.RecipientId, row.Name, row.ExpectedMl, row.Status, row.DeliveredMl);
+}
+
+internal sealed record DayTotalsResponse(int ExpectedMl, int DeliveredMl, int Delivered, int Missed, int NotRecorded)
+{
+ public static DayTotalsResponse From(DayTotals totals) => new(
+ totals.ExpectedMl, totals.DeliveredMl, totals.Delivered, totals.Missed, totals.NotRecorded);
+}
+
+internal sealed record DaySheetResponse(DateOnly Date, bool IsToday, IReadOnlyList Rows, DayTotalsResponse Totals)
+{
+ public static DaySheetResponse From(DaySheet sheet) => new(sheet.Date, sheet.IsToday,
+ [.. sheet.Rows.Select(DayRowResponse.From)], DayTotalsResponse.From(sheet.Totals));
+}
+
+internal sealed record DaySummaryResponse(DateOnly Date, DayTotalsResponse Totals)
+{
+ public static DaySummaryResponse From(DaySummary summary) => new(summary.Date, DayTotalsResponse.From(summary.Totals));
+}
diff --git a/backend/src/PureFreshMilk.Api/Features/Deliveries/DeliveryEndpoints.cs b/backend/src/PureFreshMilk.Api/Features/Deliveries/DeliveryEndpoints.cs
new file mode 100644
index 0000000..2268f5e
--- /dev/null
+++ b/backend/src/PureFreshMilk.Api/Features/Deliveries/DeliveryEndpoints.cs
@@ -0,0 +1,41 @@
+using System.Globalization;
+using Microsoft.AspNetCore.Http.HttpResults;
+using PureFreshMilk.Api.Hosting;
+using PureFreshMilk.Application.Deliveries;
+using PureFreshMilk.Domain.Deliveries;
+
+namespace PureFreshMilk.Api.Features.Deliveries;
+
+internal sealed record RecordDeliveryRequest(string? Status, int? DeliveredMl);
+internal sealed record DeliveryResponse(Guid Id, Guid RecipientId, DateOnly Date, string Status, int DeliveredMl)
+{
+ public static DeliveryResponse From(Delivery delivery) => new(delivery.Id.Value, delivery.RecipientId.Value,
+ delivery.DeliveryDate, delivery.Status == DeliveryStatus.Delivered ? "delivered" : "missed",
+ delivery.DeliveredQuantity.Millilitres);
+}
+
+internal static class DeliveryEndpoints
+{
+ public static IEndpointRouteBuilder MapDeliveryEndpoints(this IEndpointRouteBuilder api)
+ {
+ var deliveries = api.MapGroup("/recipients/{recipientId:guid}/deliveries").WithTags("Deliveries");
+ deliveries.MapPut("/{date}", async Task, Ok>> (
+ Guid recipientId, string date, RecordDeliveryRequest request, RecordDeliveryHandler handler,
+ CancellationToken cancellationToken) =>
+ {
+ var result = await handler.HandleAsync(new RecordDeliveryCommand(recipientId, date,
+ request.Status, request.DeliveredMl), cancellationToken);
+ var response = DeliveryResponse.From(result.Delivery);
+ return result.Created
+ ? TypedResults.Created($"{ApiRoutes.Prefix}/recipients/{recipientId}/deliveries/{result.Delivery.DeliveryDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}", response)
+ : TypedResults.Ok(response);
+ }).WithName("RecordDelivery");
+ deliveries.MapDelete("/{date}", async (Guid recipientId, string date, ClearDeliveryHandler handler,
+ CancellationToken cancellationToken) =>
+ {
+ await handler.HandleAsync(recipientId, date, cancellationToken);
+ return TypedResults.NoContent();
+ }).WithName("ClearDelivery");
+ return api;
+ }
+}
diff --git a/backend/src/PureFreshMilk.Api/Hosting/ApplicationExceptionHandler.cs b/backend/src/PureFreshMilk.Api/Hosting/ApplicationExceptionHandler.cs
index 64a68ca..48914a8 100644
--- a/backend/src/PureFreshMilk.Api/Hosting/ApplicationExceptionHandler.cs
+++ b/backend/src/PureFreshMilk.Api/Hosting/ApplicationExceptionHandler.cs
@@ -18,6 +18,13 @@ public async ValueTask TryHandleAsync(
{
var problem = exception switch
{
+ FutureDateException future => new ValidationProblemDetails(
+ new Dictionary { [future.Field!] = [future.Message] })
+ {
+ Status = StatusCodes.Status400BadRequest,
+ Title = "A future date cannot be requested.",
+ Extensions = { ["code"] = ErrorCodes.FutureDate },
+ },
DomainException { Field: { } field } domain => new ValidationProblemDetails(
new Dictionary { [field] = [domain.Message] })
{
diff --git a/backend/src/PureFreshMilk.Api/Program.cs b/backend/src/PureFreshMilk.Api/Program.cs
index b3a679a..8fa114d 100644
--- a/backend/src/PureFreshMilk.Api/Program.cs
+++ b/backend/src/PureFreshMilk.Api/Program.cs
@@ -1,3 +1,4 @@
+using PureFreshMilk.Api.Features.Deliveries;
using PureFreshMilk.Api.Features.Households;
using PureFreshMilk.Api.Features.MilkRates;
using PureFreshMilk.Api.Features.Recipients;
@@ -46,6 +47,8 @@
api.MapHouseholdEndpoints();
api.MapRecipientEndpoints();
api.MapMilkRateEndpoints();
+ api.MapDeliveryEndpoints();
+ api.MapDaySheetEndpoints();
}
app.Run();
diff --git a/backend/src/PureFreshMilk.Application/ApplicationServiceCollectionExtensions.cs b/backend/src/PureFreshMilk.Application/ApplicationServiceCollectionExtensions.cs
index 1f4c840..170728c 100644
--- a/backend/src/PureFreshMilk.Application/ApplicationServiceCollectionExtensions.cs
+++ b/backend/src/PureFreshMilk.Application/ApplicationServiceCollectionExtensions.cs
@@ -1,5 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
+using PureFreshMilk.Application.Deliveries;
using PureFreshMilk.Application.Households;
using PureFreshMilk.Application.Rates;
using PureFreshMilk.Application.Recipients;
@@ -35,6 +36,12 @@ public static IServiceCollection AddApplication(this IServiceCollection services
services.AddScoped();
services.AddScoped();
+ services.AddScoped();
+ services.AddScoped();
+ services.AddScoped();
+ services.AddScoped();
+ services.AddScoped();
+
return services;
}
}
diff --git a/backend/src/PureFreshMilk.Application/Common/ErrorCodes.cs b/backend/src/PureFreshMilk.Application/Common/ErrorCodes.cs
index 6b8c736..cb3c8af 100644
--- a/backend/src/PureFreshMilk.Application/Common/ErrorCodes.cs
+++ b/backend/src/PureFreshMilk.Application/Common/ErrorCodes.cs
@@ -13,4 +13,7 @@ public static class ErrorCodes
public const string RateNotFound = "rate-not-found";
public const string RateDateTaken = "rate-date-taken";
public const string NoRateInEffect = "no-rate-in-effect";
+ public const string RecipientNotActive = "recipient-not-active";
+ public const string DeliveryDateTaken = "delivery-date-taken";
+ public const string FutureDate = "future-date";
}
diff --git a/backend/src/PureFreshMilk.Application/Common/FutureDateException.cs b/backend/src/PureFreshMilk.Application/Common/FutureDateException.cs
new file mode 100644
index 0000000..0ab2597
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Common/FutureDateException.cs
@@ -0,0 +1,7 @@
+using PureFreshMilk.Domain.Common;
+
+namespace PureFreshMilk.Application.Common;
+
+/// A request refers to a household date after today.
+public sealed class FutureDateException(string field)
+ : DomainException("A future date cannot be recorded or requested.", field);
diff --git a/backend/src/PureFreshMilk.Application/Deliveries/ClearDeliveryHandler.cs b/backend/src/PureFreshMilk.Application/Deliveries/ClearDeliveryHandler.cs
new file mode 100644
index 0000000..b7bda02
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Deliveries/ClearDeliveryHandler.cs
@@ -0,0 +1,24 @@
+using PureFreshMilk.Application.Households;
+using PureFreshMilk.Application.Persistence;
+using PureFreshMilk.Application.Recipients;
+
+namespace PureFreshMilk.Application.Deliveries;
+
+public sealed class ClearDeliveryHandler(ICurrentHousehold currentHousehold, IRecipientRepository recipients,
+ IDeliveryRepository deliveries, IUnitOfWork unitOfWork, TimeProvider timeProvider)
+{
+ public async Task HandleAsync(Guid recipientId, string requestedDate, CancellationToken cancellationToken)
+ {
+ var household = await currentHousehold.RequireAsync(cancellationToken);
+ var date = DeliveryRules.ResolveDate(requestedDate, household, timeProvider.GetUtcNow());
+ var recipient = await RecipientRules.RequireAsync(recipients, household.Id, recipientId, cancellationToken);
+ var delivery = await deliveries.FindAsync(household.Id, recipient.Id, date, cancellationToken);
+ if (delivery is null)
+ {
+ return;
+ }
+
+ deliveries.Remove(delivery);
+ await unitOfWork.SaveChangesAsync(cancellationToken);
+ }
+}
diff --git a/backend/src/PureFreshMilk.Application/Deliveries/DaySheet.cs b/backend/src/PureFreshMilk.Application/Deliveries/DaySheet.cs
new file mode 100644
index 0000000..e476cfe
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Deliveries/DaySheet.cs
@@ -0,0 +1,9 @@
+namespace PureFreshMilk.Application.Deliveries;
+
+public sealed record DayRow(Guid RecipientId, string Name, int ExpectedMl, string Status, int DeliveredMl);
+
+public sealed record DayTotals(int ExpectedMl, int DeliveredMl, int Delivered, int Missed, int NotRecorded);
+
+public sealed record DaySheet(DateOnly Date, bool IsToday, IReadOnlyList Rows, DayTotals Totals);
+
+public sealed record DaySummary(DateOnly Date, DayTotals Totals);
diff --git a/backend/src/PureFreshMilk.Application/Deliveries/DeliverRemainingHandler.cs b/backend/src/PureFreshMilk.Application/Deliveries/DeliverRemainingHandler.cs
new file mode 100644
index 0000000..35b32f1
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Deliveries/DeliverRemainingHandler.cs
@@ -0,0 +1,27 @@
+using PureFreshMilk.Application.Households;
+using PureFreshMilk.Application.Persistence;
+using PureFreshMilk.Application.Recipients;
+using PureFreshMilk.Domain.Deliveries;
+
+namespace PureFreshMilk.Application.Deliveries;
+
+public sealed class DeliverRemainingHandler(ICurrentHousehold currentHousehold, IRecipientRepository recipients,
+ IDeliveryRepository deliveries, IUnitOfWork unitOfWork, GetDaySheetHandler sheets, TimeProvider timeProvider)
+{
+ public async Task HandleAsync(string requestedDate, CancellationToken cancellationToken)
+ {
+ var household = await currentHousehold.RequireAsync(cancellationToken);
+ var now = timeProvider.GetUtcNow();
+ var date = DeliveryRules.ResolveDate(requestedDate, household, now);
+ var people = await recipients.ListAsync(household.Id, true, household.Today(now), cancellationToken);
+ var recorded = await deliveries.ListAsync(household.Id, date, date, cancellationToken);
+ var recordedIds = recorded.Select(delivery => delivery.RecipientId).ToHashSet();
+ foreach (var person in people.Where(person => person.IsActiveOn(date) && !recordedIds.Contains(person.Id)))
+ {
+ deliveries.Add(Delivery.Record(person, date, DeliveryStatus.Delivered, null, now));
+ }
+
+ await unitOfWork.SaveChangesAsync(cancellationToken);
+ return await sheets.HandleAsync(requestedDate, cancellationToken);
+ }
+}
diff --git a/backend/src/PureFreshMilk.Application/Deliveries/DeliveryRules.cs b/backend/src/PureFreshMilk.Application/Deliveries/DeliveryRules.cs
new file mode 100644
index 0000000..c95ab52
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Deliveries/DeliveryRules.cs
@@ -0,0 +1,38 @@
+using PureFreshMilk.Application.Common;
+using PureFreshMilk.Domain.Common;
+using PureFreshMilk.Domain.Deliveries;
+using PureFreshMilk.Domain.Households;
+
+namespace PureFreshMilk.Application.Deliveries;
+
+internal static class DeliveryRules
+{
+ public static DateOnly ResolveDate(string value, Household household, DateTimeOffset now)
+ {
+ var today = household.Today(now);
+ if (value.Equals("today", StringComparison.OrdinalIgnoreCase))
+ {
+ return today;
+ }
+
+ if (!DateOnly.TryParseExact(value, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture,
+ System.Globalization.DateTimeStyles.None, out var date))
+ {
+ throw new DomainException("Use a date in YYYY-MM-DD format or 'today'.", "date");
+ }
+
+ if (date > today)
+ {
+ throw new FutureDateException("date");
+ }
+
+ return date;
+ }
+
+ public static DeliveryStatus ParseStatus(string? status) => status switch
+ {
+ "delivered" => DeliveryStatus.Delivered,
+ "missed" => DeliveryStatus.Missed,
+ _ => throw new DomainException("Status must be delivered or missed.", "status"),
+ };
+}
diff --git a/backend/src/PureFreshMilk.Application/Deliveries/GetDaySheetHandler.cs b/backend/src/PureFreshMilk.Application/Deliveries/GetDaySheetHandler.cs
new file mode 100644
index 0000000..54c97be
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Deliveries/GetDaySheetHandler.cs
@@ -0,0 +1,34 @@
+using PureFreshMilk.Application.Households;
+using PureFreshMilk.Application.Recipients;
+using PureFreshMilk.Domain.Deliveries;
+
+namespace PureFreshMilk.Application.Deliveries;
+
+public sealed class GetDaySheetHandler(ICurrentHousehold currentHousehold, IRecipientRepository recipients,
+ IDeliveryRepository deliveries, TimeProvider timeProvider)
+{
+ public async Task HandleAsync(string requestedDate, CancellationToken cancellationToken)
+ {
+ var household = await currentHousehold.RequireAsync(cancellationToken);
+ var now = timeProvider.GetUtcNow();
+ var date = DeliveryRules.ResolveDate(requestedDate, household, now);
+ var people = await recipients.ListAsync(household.Id, true, household.Today(now), cancellationToken);
+ var recorded = await deliveries.ListAsync(household.Id, date, date, cancellationToken);
+ var byRecipient = recorded.ToDictionary(delivery => delivery.RecipientId);
+ var rows = people.Where(person => person.IsActiveOn(date)).Select(person =>
+ {
+ byRecipient.TryGetValue(person.Id, out var delivery);
+ return new DayRow(person.Id.Value, person.Name, person.ExpectedQuantity.Millilitres,
+ delivery?.Status switch
+ {
+ DeliveryStatus.Delivered => "delivered",
+ DeliveryStatus.Missed => "missed",
+ _ => "notRecorded",
+ }, delivery?.DeliveredQuantity.Millilitres ?? 0);
+ }).ToArray();
+ return new DaySheet(date, date == household.Today(now), rows, new DayTotals(
+ rows.Sum(row => row.ExpectedMl), rows.Sum(row => row.DeliveredMl),
+ rows.Count(row => row.Status == "delivered"), rows.Count(row => row.Status == "missed"),
+ rows.Count(row => row.Status == "notRecorded")));
+ }
+}
diff --git a/backend/src/PureFreshMilk.Application/Deliveries/IDeliveryRepository.cs b/backend/src/PureFreshMilk.Application/Deliveries/IDeliveryRepository.cs
new file mode 100644
index 0000000..0b67282
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Deliveries/IDeliveryRepository.cs
@@ -0,0 +1,15 @@
+using PureFreshMilk.Domain.Deliveries;
+using PureFreshMilk.Domain.Households;
+using PureFreshMilk.Domain.Recipients;
+
+namespace PureFreshMilk.Application.Deliveries;
+
+public interface IDeliveryRepository
+{
+ Task FindAsync(HouseholdId householdId, RecipientId recipientId, DateOnly date, CancellationToken cancellationToken);
+ Task> ListAsync(HouseholdId householdId, DateOnly from, DateOnly to, CancellationToken cancellationToken);
+ Task FirstDateAsync(HouseholdId householdId, RecipientId recipientId, CancellationToken cancellationToken);
+ Task LastDateAsync(HouseholdId householdId, RecipientId recipientId, CancellationToken cancellationToken);
+ void Add(Delivery delivery);
+ void Remove(Delivery delivery);
+}
diff --git a/backend/src/PureFreshMilk.Application/Deliveries/ListDaySummariesHandler.cs b/backend/src/PureFreshMilk.Application/Deliveries/ListDaySummariesHandler.cs
new file mode 100644
index 0000000..a041145
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Deliveries/ListDaySummariesHandler.cs
@@ -0,0 +1,48 @@
+using PureFreshMilk.Application.Common;
+using PureFreshMilk.Application.Households;
+using PureFreshMilk.Application.Recipients;
+using PureFreshMilk.Domain.Common;
+using PureFreshMilk.Domain.Deliveries;
+
+namespace PureFreshMilk.Application.Deliveries;
+
+public sealed class ListDaySummariesHandler(ICurrentHousehold currentHousehold, IRecipientRepository recipients,
+ IDeliveryRepository deliveries,
+ TimeProvider timeProvider)
+{
+ public async Task> HandleAsync(DateOnly from, DateOnly to, CancellationToken cancellationToken)
+ {
+ var household = await currentHousehold.RequireAsync(cancellationToken);
+ if (from == default || to == default || from > to || to.DayNumber - from.DayNumber >= 366)
+ {
+ throw new DomainException("Choose a date range of at most 366 days, from oldest to newest.", "from");
+ }
+
+ if (to > household.Today(timeProvider.GetUtcNow()))
+ {
+ throw new FutureDateException("to");
+ }
+
+ var recorded = await deliveries.ListAsync(household.Id, from, to, cancellationToken);
+ var people = await recipients.ListAsync(household.Id, true, household.Today(timeProvider.GetUtcNow()), cancellationToken);
+ var byDate = recorded.GroupBy(delivery => delivery.DeliveryDate)
+ .ToDictionary(group => group.Key, group => group.ToArray());
+ var summaries = new List();
+ for (var date = to; date >= from; date = date.AddDays(-1))
+ {
+ var active = people.Where(person => person.IsActiveOn(date)).ToArray();
+ var day = byDate.GetValueOrDefault(date) ?? [];
+ summaries.Add(new DaySummary(date, new DayTotals(
+ active.Sum(person => person.ExpectedQuantity.Millilitres),
+ day.Sum(delivery => delivery.DeliveredQuantity.Millilitres),
+ day.Count(delivery => delivery.Status == DeliveryStatus.Delivered),
+ day.Count(delivery => delivery.Status == DeliveryStatus.Missed),
+ active.Length - day.Length)));
+ if (date == DateOnly.MinValue)
+ {
+ break;
+ }
+ }
+ return summaries;
+ }
+}
diff --git a/backend/src/PureFreshMilk.Application/Deliveries/RecordDeliveryHandler.cs b/backend/src/PureFreshMilk.Application/Deliveries/RecordDeliveryHandler.cs
new file mode 100644
index 0000000..46677ac
--- /dev/null
+++ b/backend/src/PureFreshMilk.Application/Deliveries/RecordDeliveryHandler.cs
@@ -0,0 +1,42 @@
+using PureFreshMilk.Application.Common;
+using PureFreshMilk.Application.Households;
+using PureFreshMilk.Application.Persistence;
+using PureFreshMilk.Application.Recipients;
+using PureFreshMilk.Domain.Deliveries;
+
+namespace PureFreshMilk.Application.Deliveries;
+
+public sealed record RecordDeliveryCommand(Guid RecipientId, string Date, string? Status, int? DeliveredMl);
+public sealed record RecordDeliveryResult(Delivery Delivery, bool Created);
+
+public sealed class RecordDeliveryHandler(ICurrentHousehold currentHousehold, IRecipientRepository recipients,
+ IDeliveryRepository deliveries, IUnitOfWork unitOfWork, TimeProvider timeProvider)
+{
+ public async Task HandleAsync(RecordDeliveryCommand command, CancellationToken cancellationToken)
+ {
+ var household = await currentHousehold.RequireAsync(cancellationToken);
+ var now = timeProvider.GetUtcNow();
+ var date = DeliveryRules.ResolveDate(command.Date, household, now);
+ var recipient = await RecipientRules.RequireAsync(recipients, household.Id, command.RecipientId, cancellationToken);
+ if (!recipient.IsActiveOn(date))
+ {
+ throw new ConflictException(ErrorCodes.RecipientNotActive, "The recipient is not active on this date.");
+ }
+
+ var status = DeliveryRules.ParseStatus(command.Status);
+ var existing = await deliveries.FindAsync(household.Id, recipient.Id, date, cancellationToken);
+ var created = existing is null;
+ if (existing is null)
+ {
+ existing = Delivery.Record(recipient, date, status, command.DeliveredMl, now);
+ deliveries.Add(existing);
+ }
+ else
+ {
+ existing.Replace(status, command.DeliveredMl, recipient.ExpectedQuantity, now);
+ }
+
+ await unitOfWork.SaveChangesAsync(cancellationToken);
+ return new RecordDeliveryResult(existing, created);
+ }
+}
diff --git a/backend/src/PureFreshMilk.Application/Recipients/ArchiveRecipientHandler.cs b/backend/src/PureFreshMilk.Application/Recipients/ArchiveRecipientHandler.cs
index 4954210..f9b5b61 100644
--- a/backend/src/PureFreshMilk.Application/Recipients/ArchiveRecipientHandler.cs
+++ b/backend/src/PureFreshMilk.Application/Recipients/ArchiveRecipientHandler.cs
@@ -1,5 +1,6 @@
using System.Globalization;
using PureFreshMilk.Application.Common;
+using PureFreshMilk.Application.Deliveries;
using PureFreshMilk.Application.Households;
using PureFreshMilk.Application.Persistence;
using PureFreshMilk.Domain.Recipients;
@@ -17,6 +18,7 @@ public sealed record ArchiveRecipientCommand(Guid Id, DateOnly? ArchivedFrom);
public sealed class ArchiveRecipientHandler(
ICurrentHousehold currentHousehold,
IRecipientRepository recipients,
+ IDeliveryRepository deliveries,
IUnitOfWork unitOfWork,
TimeProvider timeProvider)
{
@@ -33,17 +35,26 @@ public async Task HandleAsync(ArchiveRecipientCommand command,
$"The recipient is already archived from {archivedFrom.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}. Bring them back before archiving again.");
}
- recipient.Archive(command.ArchivedFrom ?? DefaultArchiveDate(recipient, household.Today(now)), now);
+ var latest = await deliveries.LastDateAsync(household.Id, recipient.Id, cancellationToken);
+ var from = command.ArchivedFrom ?? DefaultArchiveDate(recipient, household.Today(now), latest);
+ if (latest is { } lastDate && from <= lastDate)
+ {
+ throw new ConflictException(ErrorCodes.RecipientNotActive,
+ "The archive date must be after the latest recorded delivery.");
+ }
+
+ recipient.Archive(from, now);
await unitOfWork.SaveChangesAsync(cancellationToken);
return RecipientDetails.From(recipient);
}
- private static DateOnly DefaultArchiveDate(Recipient recipient, DateOnly today)
+ private static DateOnly DefaultArchiveDate(Recipient recipient, DateOnly today, DateOnly? latest)
{
// Not past the last representable day: the domain then rejects the date with its own message.
var dayAfterStart = recipient.StartsOn == DateOnly.MaxValue ? recipient.StartsOn : recipient.StartsOn.AddDays(1);
- return dayAfterStart > today ? dayAfterStart : today;
+ var afterLatest = latest is { } date && date < DateOnly.MaxValue ? date.AddDays(1) : today;
+ return new[] { dayAfterStart, afterLatest, today }.Max();
}
}
diff --git a/backend/src/PureFreshMilk.Application/Recipients/UpdateRecipientHandler.cs b/backend/src/PureFreshMilk.Application/Recipients/UpdateRecipientHandler.cs
index 391aacf..1fcaec0 100644
--- a/backend/src/PureFreshMilk.Application/Recipients/UpdateRecipientHandler.cs
+++ b/backend/src/PureFreshMilk.Application/Recipients/UpdateRecipientHandler.cs
@@ -1,3 +1,5 @@
+using PureFreshMilk.Application.Common;
+using PureFreshMilk.Application.Deliveries;
using PureFreshMilk.Application.Households;
using PureFreshMilk.Application.Persistence;
using PureFreshMilk.Domain.Recipients;
@@ -10,6 +12,7 @@ public sealed record UpdateRecipientCommand(Guid Id, string? Name, int ExpectedM
public sealed class UpdateRecipientHandler(
ICurrentHousehold currentHousehold,
IRecipientRepository recipients,
+ IDeliveryRepository deliveries,
IUnitOfWork unitOfWork,
TimeProvider timeProvider)
{
@@ -17,6 +20,12 @@ public async Task HandleAsync(UpdateRecipientCommand command,
{
var household = await currentHousehold.RequireAsync(cancellationToken);
var recipient = await RecipientRules.RequireAsync(recipients, household.Id, command.Id, cancellationToken);
+ var earliest = await deliveries.FirstDateAsync(household.Id, recipient.Id, cancellationToken);
+ if (earliest is { } firstDate && command.StartsOn > firstDate)
+ {
+ throw new ConflictException(ErrorCodes.RecipientNotActive,
+ "The start date cannot be moved after the first recorded delivery.");
+ }
// Look for a clash before changing anything, so a rejected request leaves the recipient as it was.
var name = Recipient.NormalizeName(command.Name);
diff --git a/backend/src/PureFreshMilk.Domain/Deliveries/Delivery.cs b/backend/src/PureFreshMilk.Domain/Deliveries/Delivery.cs
new file mode 100644
index 0000000..926a9ee
--- /dev/null
+++ b/backend/src/PureFreshMilk.Domain/Deliveries/Delivery.cs
@@ -0,0 +1,61 @@
+using PureFreshMilk.Domain.Common;
+using PureFreshMilk.Domain.Households;
+using PureFreshMilk.Domain.Recipients;
+
+namespace PureFreshMilk.Domain.Deliveries;
+
+/// One recorded outcome for one recipient on one household calendar day.
+public sealed class Delivery
+{
+ private Delivery() { }
+
+ public DeliveryId Id { get; private set; }
+ public HouseholdId HouseholdId { get; private set; }
+ public RecipientId RecipientId { get; private set; }
+ public DateOnly DeliveryDate { get; private set; }
+ public DeliveryStatus Status { get; private set; }
+ public Quantity DeliveredQuantity { get; private set; }
+ public DateTimeOffset CreatedAt { get; private set; }
+ public DateTimeOffset UpdatedAt { get; private set; }
+
+ public static Delivery Record(Recipient recipient, DateOnly date, DeliveryStatus status, int? deliveredMl, DateTimeOffset now)
+ {
+ if (!recipient.IsActiveOn(date))
+ {
+ throw new DomainException("The recipient is not active on this date.", "date");
+ }
+
+ var delivery = new Delivery
+ {
+ Id = DeliveryId.New(now),
+ HouseholdId = recipient.HouseholdId,
+ RecipientId = recipient.Id,
+ DeliveryDate = date,
+ CreatedAt = now,
+ };
+ delivery.Replace(status, deliveredMl, recipient.ExpectedQuantity, now);
+ return delivery;
+ }
+
+ public void Replace(DeliveryStatus status, int? deliveredMl, Quantity usualQuantity, DateTimeOffset now)
+ {
+ var ml = status switch
+ {
+ DeliveryStatus.Delivered => deliveredMl ?? usualQuantity.Millilitres,
+ DeliveryStatus.Missed => deliveredMl ?? 0,
+ _ => throw new DomainException("The delivery status must be delivered or missed.", "status"),
+ };
+ if (status == DeliveryStatus.Delivered && ml is < 1 or > 20_000)
+ {
+ throw new DomainException("A delivered quantity must be between 1 and 20,000 ml.", "deliveredMl");
+ }
+ if (status == DeliveryStatus.Missed && ml != 0)
+ {
+ throw new DomainException("A missed delivery must have 0 ml.", "deliveredMl");
+ }
+
+ Status = status;
+ DeliveredQuantity = Quantity.FromMillilitres(ml);
+ UpdatedAt = now;
+ }
+}
diff --git a/backend/src/PureFreshMilk.Domain/Deliveries/DeliveryId.cs b/backend/src/PureFreshMilk.Domain/Deliveries/DeliveryId.cs
new file mode 100644
index 0000000..d72dcf2
--- /dev/null
+++ b/backend/src/PureFreshMilk.Domain/Deliveries/DeliveryId.cs
@@ -0,0 +1,11 @@
+using PureFreshMilk.Domain.Common;
+
+namespace PureFreshMilk.Domain.Deliveries;
+
+public readonly record struct DeliveryId
+{
+ private DeliveryId(Guid value) => Value = value;
+ public Guid Value { get; }
+ public static DeliveryId New(DateTimeOffset now) => new(Identifier.Create(now));
+ public static DeliveryId From(Guid value) => new(Identifier.Require(value, "A delivery id"));
+}
diff --git a/backend/src/PureFreshMilk.Domain/Deliveries/DeliveryStatus.cs b/backend/src/PureFreshMilk.Domain/Deliveries/DeliveryStatus.cs
new file mode 100644
index 0000000..44bf001
--- /dev/null
+++ b/backend/src/PureFreshMilk.Domain/Deliveries/DeliveryStatus.cs
@@ -0,0 +1,7 @@
+namespace PureFreshMilk.Domain.Deliveries;
+
+public enum DeliveryStatus
+{
+ Delivered,
+ Missed,
+}
diff --git a/backend/src/PureFreshMilk.Infrastructure/InfrastructureServiceCollectionExtensions.cs b/backend/src/PureFreshMilk.Infrastructure/InfrastructureServiceCollectionExtensions.cs
index 712290f..dbe943c 100644
--- a/backend/src/PureFreshMilk.Infrastructure/InfrastructureServiceCollectionExtensions.cs
+++ b/backend/src/PureFreshMilk.Infrastructure/InfrastructureServiceCollectionExtensions.cs
@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
+using PureFreshMilk.Application.Deliveries;
using PureFreshMilk.Application.Households;
using PureFreshMilk.Application.Persistence;
using PureFreshMilk.Application.Rates;
@@ -38,6 +39,7 @@ public static IServiceCollection AddInfrastructure(this IServiceCollection servi
services.AddScoped();
services.AddScoped();
services.AddScoped();
+ services.AddScoped();
// Ready means PostgreSQL answers and every migration has been applied. Without the second part the
// API would start and then fail every request with "relation does not exist".
diff --git a/backend/src/PureFreshMilk.Infrastructure/Persistence/Configurations/DeliveryConfiguration.cs b/backend/src/PureFreshMilk.Infrastructure/Persistence/Configurations/DeliveryConfiguration.cs
new file mode 100644
index 0000000..1257428
--- /dev/null
+++ b/backend/src/PureFreshMilk.Infrastructure/Persistence/Configurations/DeliveryConfiguration.cs
@@ -0,0 +1,41 @@
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+using PureFreshMilk.Domain.Deliveries;
+using PureFreshMilk.Domain.Recipients;
+
+namespace PureFreshMilk.Infrastructure.Persistence.Configurations;
+
+internal sealed class DeliveryConfiguration : IEntityTypeConfiguration
+{
+ public const string RecipientDateIndexName = "ux_deliveries_recipient_id_delivery_date";
+
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("deliveries", table =>
+ {
+ table.HasCheckConstraint("ck_deliveries_status", "status IN ('delivered', 'missed')");
+ table.HasCheckConstraint("ck_deliveries_quantity",
+ "(status = 'delivered' AND delivered_ml BETWEEN 1 AND 20000) OR (status = 'missed' AND delivered_ml = 0)");
+ });
+ builder.HasKey(delivery => delivery.Id).HasName("pk_deliveries");
+ builder.Property(delivery => delivery.Id).HasColumnName("id").ValueGeneratedNever();
+ builder.Property(delivery => delivery.HouseholdId).HasColumnName("household_id");
+ builder.Property(delivery => delivery.RecipientId).HasColumnName("recipient_id");
+ builder.Property(delivery => delivery.DeliveryDate).HasColumnName("delivery_date");
+ builder.Property(delivery => delivery.Status).HasColumnName("status").HasMaxLength(16)
+ .HasConversion(status => status == DeliveryStatus.Delivered ? "delivered" : "missed",
+ value => value == "delivered" ? DeliveryStatus.Delivered : DeliveryStatus.Missed);
+ builder.Property(delivery => delivery.DeliveredQuantity).HasColumnName("delivered_ml");
+ builder.Property(delivery => delivery.CreatedAt).HasColumnName("created_at");
+ builder.Property(delivery => delivery.UpdatedAt).HasColumnName("updated_at");
+ builder.HasOne().WithMany()
+ .HasForeignKey(delivery => new { delivery.HouseholdId, delivery.RecipientId })
+ .HasPrincipalKey(recipient => new { recipient.HouseholdId, recipient.Id })
+ .HasConstraintName("fk_deliveries_recipients_household_id_recipient_id")
+ .OnDelete(DeleteBehavior.Restrict);
+ builder.HasIndex(delivery => new { delivery.RecipientId, delivery.DeliveryDate })
+ .IsUnique().HasDatabaseName(RecipientDateIndexName);
+ builder.HasIndex(delivery => new { delivery.HouseholdId, delivery.DeliveryDate })
+ .HasDatabaseName("ix_deliveries_household_id_delivery_date");
+ }
+}
diff --git a/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/20261123124513_AddDeliveries.Designer.cs b/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/20261123124513_AddDeliveries.Designer.cs
new file mode 100644
index 0000000..9ada562
--- /dev/null
+++ b/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/20261123124513_AddDeliveries.Designer.cs
@@ -0,0 +1,255 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
+using PureFreshMilk.Infrastructure.Persistence;
+
+#nullable disable
+
+namespace PureFreshMilk.Infrastructure.Persistence.Migrations
+{
+ [DbContext(typeof(PureFreshMilkDbContext))]
+ [Migration("20261123124513_AddDeliveries")]
+ partial class AddDeliveries
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.14")
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("PureFreshMilk.Domain.Deliveries.Delivery", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("uuid")
+ .HasColumnName("id");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("DeliveredQuantity")
+ .HasColumnType("integer")
+ .HasColumnName("delivered_ml");
+
+ b.Property("DeliveryDate")
+ .HasColumnType("date")
+ .HasColumnName("delivery_date");
+
+ b.Property("HouseholdId")
+ .HasColumnType("uuid")
+ .HasColumnName("household_id");
+
+ b.Property("RecipientId")
+ .HasColumnType("uuid")
+ .HasColumnName("recipient_id");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(16)
+ .HasColumnType("character varying(16)")
+ .HasColumnName("status");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.HasKey("Id")
+ .HasName("pk_deliveries");
+
+ b.HasIndex("HouseholdId", "DeliveryDate")
+ .HasDatabaseName("ix_deliveries_household_id_delivery_date");
+
+ b.HasIndex("HouseholdId", "RecipientId");
+
+ b.HasIndex("RecipientId", "DeliveryDate")
+ .IsUnique()
+ .HasDatabaseName("ux_deliveries_recipient_id_delivery_date");
+
+ b.ToTable("deliveries", null, t =>
+ {
+ t.HasCheckConstraint("ck_deliveries_quantity", "(status = 'delivered' AND delivered_ml BETWEEN 1 AND 20000) OR (status = 'missed' AND delivered_ml = 0)");
+
+ t.HasCheckConstraint("ck_deliveries_status", "status IN ('delivered', 'missed')");
+ });
+ });
+
+ modelBuilder.Entity("PureFreshMilk.Domain.Households.Household", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("uuid")
+ .HasColumnName("id");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(80)
+ .HasColumnType("character varying(80)")
+ .HasColumnName("name");
+
+ b.Property("TimeZoneId")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("character varying(64)")
+ .HasColumnName("time_zone_id");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.HasKey("Id")
+ .HasName("pk_households");
+
+ b.ToTable("households", null, t =>
+ {
+ t.HasCheckConstraint("ck_households_name_length", "length(btrim(name)) BETWEEN 1 AND 80");
+ });
+ });
+
+ modelBuilder.Entity("PureFreshMilk.Domain.Rates.MilkRate", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("uuid")
+ .HasColumnName("id");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("EffectiveFrom")
+ .HasColumnType("date")
+ .HasColumnName("effective_from");
+
+ b.Property("HouseholdId")
+ .HasColumnType("uuid")
+ .HasColumnName("household_id");
+
+ b.Property("Price")
+ .HasColumnType("bigint")
+ .HasColumnName("price_per_litre_paise");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.HasKey("Id")
+ .HasName("pk_milk_rates");
+
+ b.HasIndex("HouseholdId", "EffectiveFrom")
+ .IsUnique()
+ .HasDatabaseName("ux_milk_rates_household_id_effective_from");
+
+ b.ToTable("milk_rates", null, t =>
+ {
+ t.HasCheckConstraint("ck_milk_rates_price", "price_per_litre_paise BETWEEN 1 AND 1000000");
+ });
+ });
+
+ modelBuilder.Entity("PureFreshMilk.Domain.Recipients.Recipient", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("uuid")
+ .HasColumnName("id");
+
+ b.Property("ArchivedFrom")
+ .HasColumnType("date")
+ .HasColumnName("archived_from");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("ExpectedQuantity")
+ .HasColumnType("integer")
+ .HasColumnName("expected_ml");
+
+ b.Property("HouseholdId")
+ .HasColumnType("uuid")
+ .HasColumnName("household_id");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(80)
+ .HasColumnType("character varying(80)")
+ .HasColumnName("name");
+
+ b.Property("NameKey")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasMaxLength(80)
+ .HasColumnType("character varying(80)")
+ .HasColumnName("name_key")
+ .HasComputedColumnSql("lower(name)", true);
+
+ b.Property("StartsOn")
+ .HasColumnType("date")
+ .HasColumnName("starts_on");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.HasKey("Id")
+ .HasName("pk_recipients");
+
+ b.HasAlternateKey("HouseholdId", "Id")
+ .HasName("uq_recipients_household_id_id");
+
+ b.HasIndex("HouseholdId", "NameKey")
+ .IsUnique()
+ .HasDatabaseName("ux_recipients_household_id_name_key_active")
+ .HasFilter("archived_from IS NULL");
+
+ b.ToTable("recipients", null, t =>
+ {
+ t.HasCheckConstraint("ck_recipients_archived_after_start", "archived_from IS NULL OR archived_from > starts_on");
+
+ t.HasCheckConstraint("ck_recipients_expected_ml", "expected_ml BETWEEN 1 AND 20000");
+
+ t.HasCheckConstraint("ck_recipients_name_length", "length(btrim(name)) BETWEEN 1 AND 80");
+ });
+ });
+
+ modelBuilder.Entity("PureFreshMilk.Domain.Deliveries.Delivery", b =>
+ {
+ b.HasOne("PureFreshMilk.Domain.Recipients.Recipient", null)
+ .WithMany()
+ .HasForeignKey("HouseholdId", "RecipientId")
+ .HasPrincipalKey("HouseholdId", "Id")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_deliveries_recipients_household_id_recipient_id");
+ });
+
+ modelBuilder.Entity("PureFreshMilk.Domain.Rates.MilkRate", b =>
+ {
+ b.HasOne("PureFreshMilk.Domain.Households.Household", null)
+ .WithMany()
+ .HasForeignKey("HouseholdId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_milk_rates_households_household_id");
+ });
+
+ modelBuilder.Entity("PureFreshMilk.Domain.Recipients.Recipient", b =>
+ {
+ b.HasOne("PureFreshMilk.Domain.Households.Household", null)
+ .WithMany()
+ .HasForeignKey("HouseholdId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_recipients_households_household_id");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/20261123124513_AddDeliveries.cs b/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/20261123124513_AddDeliveries.cs
new file mode 100644
index 0000000..4eb0186
--- /dev/null
+++ b/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/20261123124513_AddDeliveries.cs
@@ -0,0 +1,64 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace PureFreshMilk.Infrastructure.Persistence.Migrations
+{
+ ///
+ public partial class AddDeliveries : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "deliveries",
+ columns: table => new
+ {
+ id = table.Column(type: "uuid", nullable: false),
+ household_id = table.Column(type: "uuid", nullable: false),
+ recipient_id = table.Column(type: "uuid", nullable: false),
+ delivery_date = table.Column(type: "date", nullable: false),
+ status = table.Column(type: "character varying(16)", maxLength: 16, nullable: false),
+ delivered_ml = table.Column(type: "integer", nullable: false),
+ created_at = table.Column(type: "timestamp with time zone", nullable: false),
+ updated_at = table.Column(type: "timestamp with time zone", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("pk_deliveries", x => x.id);
+ table.CheckConstraint("ck_deliveries_quantity", "(status = 'delivered' AND delivered_ml BETWEEN 1 AND 20000) OR (status = 'missed' AND delivered_ml = 0)");
+ table.CheckConstraint("ck_deliveries_status", "status IN ('delivered', 'missed')");
+ table.ForeignKey(
+ name: "fk_deliveries_recipients_household_id_recipient_id",
+ columns: x => new { x.household_id, x.recipient_id },
+ principalTable: "recipients",
+ principalColumns: new[] { "household_id", "id" },
+ onDelete: ReferentialAction.Restrict);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "ix_deliveries_household_id_delivery_date",
+ table: "deliveries",
+ columns: new[] { "household_id", "delivery_date" });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_deliveries_household_id_recipient_id",
+ table: "deliveries",
+ columns: new[] { "household_id", "recipient_id" });
+
+ migrationBuilder.CreateIndex(
+ name: "ux_deliveries_recipient_id_delivery_date",
+ table: "deliveries",
+ columns: new[] { "recipient_id", "delivery_date" },
+ unique: true);
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "deliveries");
+ }
+ }
+}
diff --git a/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/PureFreshMilkDbContextModelSnapshot.cs b/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/PureFreshMilkDbContextModelSnapshot.cs
index d1dbff9..554c0d1 100644
--- a/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/PureFreshMilkDbContextModelSnapshot.cs
+++ b/backend/src/PureFreshMilk.Infrastructure/Persistence/Migrations/PureFreshMilkDbContextModelSnapshot.cs
@@ -1,4 +1,4 @@
-//
+//
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
@@ -22,6 +22,62 @@ protected override void BuildModel(ModelBuilder modelBuilder)
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+ modelBuilder.Entity("PureFreshMilk.Domain.Deliveries.Delivery", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("uuid")
+ .HasColumnName("id");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("DeliveredQuantity")
+ .HasColumnType("integer")
+ .HasColumnName("delivered_ml");
+
+ b.Property("DeliveryDate")
+ .HasColumnType("date")
+ .HasColumnName("delivery_date");
+
+ b.Property("HouseholdId")
+ .HasColumnType("uuid")
+ .HasColumnName("household_id");
+
+ b.Property("RecipientId")
+ .HasColumnType("uuid")
+ .HasColumnName("recipient_id");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(16)
+ .HasColumnType("character varying(16)")
+ .HasColumnName("status");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.HasKey("Id")
+ .HasName("pk_deliveries");
+
+ b.HasIndex("HouseholdId", "DeliveryDate")
+ .HasDatabaseName("ix_deliveries_household_id_delivery_date");
+
+ b.HasIndex("HouseholdId", "RecipientId");
+
+ b.HasIndex("RecipientId", "DeliveryDate")
+ .IsUnique()
+ .HasDatabaseName("ux_deliveries_recipient_id_delivery_date");
+
+ b.ToTable("deliveries", null, t =>
+ {
+ t.HasCheckConstraint("ck_deliveries_quantity", "(status = 'delivered' AND delivered_ml BETWEEN 1 AND 20000) OR (status = 'missed' AND delivered_ml = 0)");
+
+ t.HasCheckConstraint("ck_deliveries_status", "status IN ('delivered', 'missed')");
+ });
+ });
+
modelBuilder.Entity("PureFreshMilk.Domain.Households.Household", b =>
{
b.Property("Id")
@@ -160,6 +216,17 @@ protected override void BuildModel(ModelBuilder modelBuilder)
});
});
+ modelBuilder.Entity("PureFreshMilk.Domain.Deliveries.Delivery", b =>
+ {
+ b.HasOne("PureFreshMilk.Domain.Recipients.Recipient", null)
+ .WithMany()
+ .HasForeignKey("HouseholdId", "RecipientId")
+ .HasPrincipalKey("HouseholdId", "Id")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired()
+ .HasConstraintName("fk_deliveries_recipients_household_id_recipient_id");
+ });
+
modelBuilder.Entity("PureFreshMilk.Domain.Rates.MilkRate", b =>
{
b.HasOne("PureFreshMilk.Domain.Households.Household", null)
diff --git a/backend/src/PureFreshMilk.Infrastructure/Persistence/PureFreshMilkDbContext.cs b/backend/src/PureFreshMilk.Infrastructure/Persistence/PureFreshMilkDbContext.cs
index 5d020f2..3969cf2 100644
--- a/backend/src/PureFreshMilk.Infrastructure/Persistence/PureFreshMilkDbContext.cs
+++ b/backend/src/PureFreshMilk.Infrastructure/Persistence/PureFreshMilkDbContext.cs
@@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using PureFreshMilk.Domain.Common;
+using PureFreshMilk.Domain.Deliveries;
using PureFreshMilk.Domain.Households;
using PureFreshMilk.Domain.Rates;
using PureFreshMilk.Domain.Recipients;
@@ -21,11 +22,14 @@ internal sealed class PureFreshMilkDbContext(DbContextOptions MilkRates => Set();
+ public DbSet Deliveries => Set();
+
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
configurationBuilder.Properties().HaveConversion();
configurationBuilder.Properties().HaveConversion();
configurationBuilder.Properties().HaveConversion();
+ configurationBuilder.Properties().HaveConversion();
configurationBuilder.Properties().HaveConversion();
configurationBuilder.Properties().HaveConversion();
}
diff --git a/backend/src/PureFreshMilk.Infrastructure/Persistence/Repositories/DeliveryRepository.cs b/backend/src/PureFreshMilk.Infrastructure/Persistence/Repositories/DeliveryRepository.cs
new file mode 100644
index 0000000..26a1213
--- /dev/null
+++ b/backend/src/PureFreshMilk.Infrastructure/Persistence/Repositories/DeliveryRepository.cs
@@ -0,0 +1,33 @@
+using Microsoft.EntityFrameworkCore;
+using PureFreshMilk.Application.Deliveries;
+using PureFreshMilk.Domain.Deliveries;
+using PureFreshMilk.Domain.Households;
+using PureFreshMilk.Domain.Recipients;
+
+namespace PureFreshMilk.Infrastructure.Persistence.Repositories;
+
+internal sealed class DeliveryRepository(PureFreshMilkDbContext context) : IDeliveryRepository
+{
+ public Task FindAsync(HouseholdId householdId, RecipientId recipientId, DateOnly date,
+ CancellationToken cancellationToken) => context.Deliveries.SingleOrDefaultAsync(delivery =>
+ delivery.HouseholdId == householdId && delivery.RecipientId == recipientId && delivery.DeliveryDate == date,
+ cancellationToken);
+
+ public async Task> ListAsync(HouseholdId householdId, DateOnly from, DateOnly to,
+ CancellationToken cancellationToken) => await context.Deliveries.AsNoTracking().Where(delivery =>
+ delivery.HouseholdId == householdId && delivery.DeliveryDate >= from && delivery.DeliveryDate <= to)
+ .ToListAsync(cancellationToken);
+
+ public Task FirstDateAsync(HouseholdId householdId, RecipientId recipientId,
+ CancellationToken cancellationToken) => context.Deliveries.Where(delivery =>
+ delivery.HouseholdId == householdId && delivery.RecipientId == recipientId)
+ .MinAsync(delivery => (DateOnly?)delivery.DeliveryDate, cancellationToken);
+
+ public Task LastDateAsync(HouseholdId householdId, RecipientId recipientId,
+ CancellationToken cancellationToken) => context.Deliveries.Where(delivery =>
+ delivery.HouseholdId == householdId && delivery.RecipientId == recipientId)
+ .MaxAsync(delivery => (DateOnly?)delivery.DeliveryDate, cancellationToken);
+
+ public void Add(Delivery delivery) => context.Deliveries.Add(delivery);
+ public void Remove(Delivery delivery) => context.Deliveries.Remove(delivery);
+}
diff --git a/backend/src/PureFreshMilk.Infrastructure/Persistence/UnitOfWork.cs b/backend/src/PureFreshMilk.Infrastructure/Persistence/UnitOfWork.cs
index 0400243..e29bc18 100644
--- a/backend/src/PureFreshMilk.Infrastructure/Persistence/UnitOfWork.cs
+++ b/backend/src/PureFreshMilk.Infrastructure/Persistence/UnitOfWork.cs
@@ -29,6 +29,8 @@ public async Task SaveChangesAsync(CancellationToken cancellationToken)
ErrorCodes.RecipientNameTaken, "Another recipient who is not archived already has that name."),
MilkRateConfiguration.EffectiveFromIndexName => new ConflictException(
ErrorCodes.RateDateTaken, "A price already starts on that date."),
+ DeliveryConfiguration.RecipientDateIndexName => new ConflictException(
+ ErrorCodes.DeliveryDateTaken, "A delivery was recorded for this recipient and date at the same time. Reload and retry."),
_ => null,
}
: null;
diff --git a/backend/src/PureFreshMilk.Infrastructure/Persistence/ValueConverters.cs b/backend/src/PureFreshMilk.Infrastructure/Persistence/ValueConverters.cs
index 5acc9b5..5ace6ae 100644
--- a/backend/src/PureFreshMilk.Infrastructure/Persistence/ValueConverters.cs
+++ b/backend/src/PureFreshMilk.Infrastructure/Persistence/ValueConverters.cs
@@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using PureFreshMilk.Domain.Common;
+using PureFreshMilk.Domain.Deliveries;
using PureFreshMilk.Domain.Households;
using PureFreshMilk.Domain.Rates;
using PureFreshMilk.Domain.Recipients;
@@ -18,6 +19,9 @@ internal sealed class RecipientIdConverter()
internal sealed class MilkRateIdConverter()
: ValueConverter(id => id.Value, value => MilkRateId.From(value));
+internal sealed class DeliveryIdConverter()
+ : ValueConverter(id => id.Value, value => DeliveryId.From(value));
+
internal sealed class QuantityConverter()
: ValueConverter(quantity => quantity.Millilitres, value => Quantity.FromMillilitres(value));
diff --git a/backend/tests/PureFreshMilk.Api.Tests/Features/Deliveries/DeliveryEndpointTests.cs b/backend/tests/PureFreshMilk.Api.Tests/Features/Deliveries/DeliveryEndpointTests.cs
new file mode 100644
index 0000000..4a99fee
--- /dev/null
+++ b/backend/tests/PureFreshMilk.Api.Tests/Features/Deliveries/DeliveryEndpointTests.cs
@@ -0,0 +1,74 @@
+using System.Net;
+using System.Net.Http.Json;
+
+namespace PureFreshMilk.Api.Tests.Features.Deliveries;
+
+public sealed class DeliveryEndpointTests(PureFreshMilkApiFactory factory) : IClassFixture
+{
+ private static CancellationToken Ct => TestContext.Current.CancellationToken;
+
+ [Fact]
+ public async Task A_delivery_can_be_recorded_replaced_and_cleared_through_http()
+ {
+ factory.Database.Clear();
+ using var client = factory.CreateClient();
+ await client.SetUpHouseholdAsync();
+ var recipient = await client.AddRecipientAsync("Recipient A", 750);
+ var id = recipient.GetProperty("id").GetGuid();
+ var path = $"/api/v1/recipients/{id}/deliveries/today";
+
+ var empty = await (await client.GetAsync("/api/v1/day-sheets/today", Ct)).ReadAsync();
+ Assert.Equal("notRecorded", empty.GetProperty("rows")[0].GetProperty("status").GetString());
+
+ var created = await client.PutAsJsonAsync(path, new { status = "delivered" }, Ct);
+ Assert.Equal(HttpStatusCode.Created, created.StatusCode);
+ Assert.Equal(750, (await created.ReadAsync()).GetProperty("deliveredMl").GetInt32());
+
+ var replaced = await client.PutAsJsonAsync(path, new { status = "missed" }, Ct);
+ Assert.Equal(HttpStatusCode.OK, replaced.StatusCode);
+ Assert.Equal(0, (await replaced.ReadAsync()).GetProperty("deliveredMl").GetInt32());
+
+ var invalid = await client.PutAsJsonAsync(path, new { status = "missed", deliveredMl = 500 }, Ct);
+ var problem = await invalid.ReadProblemAsync(HttpStatusCode.BadRequest);
+ Assert.NotEmpty(problem.ErrorsFor("deliveredMl"));
+
+ Assert.Equal(HttpStatusCode.NoContent, (await client.DeleteAsync(path, Ct)).StatusCode);
+ Assert.Equal(HttpStatusCode.NoContent, (await client.DeleteAsync(path, Ct)).StatusCode);
+ Assert.Equal("notRecorded", (await (await client.GetAsync("/api/v1/day-sheets/today", Ct)).ReadAsync())
+ .GetProperty("rows")[0].GetProperty("status").GetString());
+ }
+
+ [Fact]
+ public async Task Mark_remaining_and_history_return_server_totals()
+ {
+ factory.Database.Clear();
+ using var client = factory.CreateClient();
+ await client.SetUpHouseholdAsync();
+ await client.AddRecipientAsync("Recipient A", 750, "2026-10-29");
+ await client.AddRecipientAsync("Recipient B", 500, "2026-10-29");
+
+ var filled = await (await client.PostAsync("/api/v1/day-sheets/today/deliver-remaining", null, Ct)).ReadAsync();
+ Assert.Equal(1250, filled.GetProperty("totals").GetProperty("deliveredMl").GetInt32());
+ Assert.Equal(2, filled.GetProperty("totals").GetProperty("delivered").GetInt32());
+
+ var history = await (await client.GetAsync("/api/v1/day-summaries?from=2026-10-29&to=2026-10-30", Ct)).ReadAsync();
+ var items = history.GetProperty("items");
+ Assert.Equal(2, items.GetArrayLength());
+ Assert.Equal("2026-10-30", items[0].GetProperty("date").GetString());
+ Assert.Equal(1250, items[0].GetProperty("totals").GetProperty("deliveredMl").GetInt32());
+ Assert.Equal(2, items[1].GetProperty("totals").GetProperty("notRecorded").GetInt32());
+ }
+
+ [Fact]
+ public async Task Future_day_is_a_400_with_a_stable_code()
+ {
+ factory.Database.Clear();
+ using var client = factory.CreateClient();
+ await client.SetUpHouseholdAsync();
+
+ var problem = await (await client.GetAsync("/api/v1/day-sheets/2026-10-31", Ct))
+ .ReadProblemAsync(HttpStatusCode.BadRequest);
+ Assert.Equal("future-date", problem.GetProperty("code").GetString());
+ Assert.NotEmpty(problem.ErrorsFor("date"));
+ }
+}
diff --git a/backend/tests/PureFreshMilk.Application.Tests/Deliveries/DeliveryHandlerTests.cs b/backend/tests/PureFreshMilk.Application.Tests/Deliveries/DeliveryHandlerTests.cs
new file mode 100644
index 0000000..29be425
--- /dev/null
+++ b/backend/tests/PureFreshMilk.Application.Tests/Deliveries/DeliveryHandlerTests.cs
@@ -0,0 +1,61 @@
+using PureFreshMilk.Application.Common;
+using PureFreshMilk.Application.Deliveries;
+using PureFreshMilk.Application.Recipients;
+using PureFreshMilk.Domain.Common;
+
+namespace PureFreshMilk.Application.Tests.Deliveries;
+
+public sealed class DeliveryHandlerTests
+{
+ private static CancellationToken Ct => TestContext.Current.CancellationToken;
+
+ [Fact]
+ [Trait("Invariant", "L-7,L-8,L-13,L-14,R-10")]
+ public async Task Day_sheet_tracks_record_replace_clear_and_remaining_without_changing_existing_quantities()
+ {
+ var app = await TestHousehold.SetUpAsync();
+ var first = await app.AddRecipientAsync("Recipient A", 750);
+ await app.AddRecipientAsync("Recipient B", 500);
+ var empty = await app.GetDaySheet.HandleAsync("today", Ct);
+ Assert.Equal(2, empty.Totals.NotRecorded);
+ Assert.Equal(1250, empty.Totals.ExpectedMl);
+
+ var recorded = await app.RecordDelivery.HandleAsync(new(first.Id, "today", "delivered", null), Ct);
+ Assert.True(recorded.Created);
+ Assert.Equal(750, recorded.Delivery.DeliveredQuantity.Millilitres);
+ var replaced = await app.RecordDelivery.HandleAsync(new(first.Id, "today", "missed", null), Ct);
+ Assert.False(replaced.Created);
+ Assert.Single(app.Database.Deliveries);
+ Assert.Equal(0, replaced.Delivery.DeliveredQuantity.Millilitres);
+
+ var filled = await app.DeliverRemaining.HandleAsync("today", Ct);
+ Assert.Equal(1, filled.Totals.Delivered);
+ Assert.Equal(1, filled.Totals.Missed);
+ Assert.Equal(500, filled.Totals.DeliveredMl);
+ Assert.Equal(2, app.Database.Deliveries.Count);
+
+ await app.UpdateRecipient.HandleAsync(new UpdateRecipientCommand(first.Id, "Recipient A", 1000, first.StartsOn), Ct);
+ Assert.Equal(0, app.Database.Deliveries.Single(delivery => delivery.RecipientId.Value == first.Id).DeliveredQuantity.Millilitres);
+ await app.ClearDelivery.HandleAsync(first.Id, "today", Ct);
+ await app.ClearDelivery.HandleAsync(first.Id, "today", Ct);
+ Assert.Equal(1, (await app.GetDaySheet.HandleAsync("today", Ct)).Totals.NotRecorded);
+ }
+
+ [Fact]
+ [Trait("Invariant", "L-5,L-6,L-15,R-6,R-7")]
+ public async Task Date_and_recipient_boundaries_are_enforced()
+ {
+ var app = await TestHousehold.SetUpAsync();
+ var first = await app.AddRecipientAsync("Recipient A", 750, new DateOnly(2026, 10, 1));
+ await Assert.ThrowsAsync(() => app.GetDaySheet.HandleAsync("2026-10-31", Ct));
+ await Assert.ThrowsAsync(() => app.RecordDelivery.HandleAsync(
+ new(first.Id, "2026-09-30", "delivered", null), Ct));
+ await app.RecordDelivery.HandleAsync(new(first.Id, "2026-10-15", "delivered", null), Ct);
+ await Assert.ThrowsAsync(() => app.UpdateRecipient.HandleAsync(
+ new(first.Id, "Recipient A", 750, new DateOnly(2026, 10, 16)), Ct));
+ await Assert.ThrowsAsync(() => app.ArchiveRecipient.HandleAsync(
+ new(first.Id, new DateOnly(2026, 10, 15)), Ct));
+ await Assert.ThrowsAsync(() => app.ListDaySummaries.HandleAsync(
+ new DateOnly(2025, 1, 1), new DateOnly(2026, 10, 30), Ct));
+ }
+}
diff --git a/backend/tests/PureFreshMilk.Application.Tests/TestHousehold.cs b/backend/tests/PureFreshMilk.Application.Tests/TestHousehold.cs
index a3a807a..ea5ee8a 100644
--- a/backend/tests/PureFreshMilk.Application.Tests/TestHousehold.cs
+++ b/backend/tests/PureFreshMilk.Application.Tests/TestHousehold.cs
@@ -1,3 +1,4 @@
+using PureFreshMilk.Application.Deliveries;
using PureFreshMilk.Application.Households;
using PureFreshMilk.Application.Rates;
using PureFreshMilk.Application.Recipients;
@@ -22,6 +23,7 @@ public TestHousehold()
var households = new InMemoryHouseholdRepository(Database);
var recipients = new InMemoryRecipientRepository(Database);
var rates = new InMemoryMilkRateRepository(Database);
+ var deliveries = new InMemoryDeliveryRepository(Database);
GetHousehold = new GetHouseholdHandler(households, Clock);
SetUpHousehold = new SetUpHouseholdHandler(households, households, Database, Clock);
@@ -29,8 +31,8 @@ public TestHousehold()
ListRecipients = new ListRecipientsHandler(households, recipients, Clock);
GetRecipient = new GetRecipientHandler(households, recipients);
AddRecipient = new AddRecipientHandler(households, recipients, Database, Clock);
- UpdateRecipient = new UpdateRecipientHandler(households, recipients, Database, Clock);
- ArchiveRecipient = new ArchiveRecipientHandler(households, recipients, Database, Clock);
+ UpdateRecipient = new UpdateRecipientHandler(households, recipients, deliveries, Database, Clock);
+ ArchiveRecipient = new ArchiveRecipientHandler(households, recipients, deliveries, Database, Clock);
UnarchiveRecipient = new UnarchiveRecipientHandler(households, recipients, Database, Clock);
ListRates = new ListMilkRatesHandler(households, rates);
@@ -38,6 +40,12 @@ public TestHousehold()
AddRate = new AddMilkRateHandler(households, rates, Database, Clock);
UpdateRate = new UpdateMilkRateHandler(households, rates, Database, Clock);
DeleteRate = new DeleteMilkRateHandler(households, rates, Database);
+
+ GetDaySheet = new GetDaySheetHandler(households, recipients, deliveries, Clock);
+ RecordDelivery = new RecordDeliveryHandler(households, recipients, deliveries, Database, Clock);
+ ClearDelivery = new ClearDeliveryHandler(households, recipients, deliveries, Database, Clock);
+ DeliverRemaining = new DeliverRemainingHandler(households, recipients, deliveries, Database, GetDaySheet, Clock);
+ ListDaySummaries = new ListDaySummariesHandler(households, recipients, deliveries, Clock);
}
public InMemoryDatabase Database { get; }
@@ -70,6 +78,12 @@ public TestHousehold()
public DeleteMilkRateHandler DeleteRate { get; }
+ public GetDaySheetHandler GetDaySheet { get; }
+ public RecordDeliveryHandler RecordDelivery { get; }
+ public ClearDeliveryHandler ClearDelivery { get; }
+ public DeliverRemainingHandler DeliverRemaining { get; }
+ public ListDaySummariesHandler ListDaySummaries { get; }
+
private static CancellationToken Ct => TestContext.Current.CancellationToken;
/// A household that has been set up, as the first screen of the app does.
diff --git a/backend/tests/PureFreshMilk.Domain.Tests/Deliveries/DeliveryTests.cs b/backend/tests/PureFreshMilk.Domain.Tests/Deliveries/DeliveryTests.cs
new file mode 100644
index 0000000..b5dbcff
--- /dev/null
+++ b/backend/tests/PureFreshMilk.Domain.Tests/Deliveries/DeliveryTests.cs
@@ -0,0 +1,42 @@
+using PureFreshMilk.Domain.Common;
+using PureFreshMilk.Domain.Deliveries;
+using PureFreshMilk.Domain.Households;
+using PureFreshMilk.Domain.Recipients;
+
+namespace PureFreshMilk.Domain.Tests.Deliveries;
+
+public sealed class DeliveryTests
+{
+ private static readonly DateTimeOffset Now = new(2026, 10, 30, 6, 0, 0, TimeSpan.Zero);
+ private static readonly DateOnly Date = new(2026, 10, 30);
+
+ private static Recipient Person() => Recipient.Add(HouseholdId.New(Now), "Recipient A",
+ Quantity.FromMillilitres(750), new DateOnly(2026, 10, 1), Now);
+
+ [Fact]
+ [Trait("Invariant", "L-1,L-2,L-3,L-4,L-7")]
+ public void Recording_and_replacing_enforce_status_and_quantity()
+ {
+ var person = Person();
+ var delivery = Delivery.Record(person, Date, DeliveryStatus.Delivered, null, Now);
+ Assert.Equal(750, delivery.DeliveredQuantity.Millilitres);
+
+ delivery.Replace(DeliveryStatus.Missed, null, person.ExpectedQuantity, Now.AddMinutes(1));
+ Assert.Equal(0, delivery.DeliveredQuantity.Millilitres);
+ delivery.Replace(DeliveryStatus.Delivered, null, person.ExpectedQuantity, Now.AddMinutes(2));
+ Assert.Equal(750, delivery.DeliveredQuantity.Millilitres);
+
+ Assert.Throws(() => delivery.Replace(DeliveryStatus.Delivered, 0, person.ExpectedQuantity, Now));
+ Assert.Throws(() => delivery.Replace(DeliveryStatus.Delivered, 20_001, person.ExpectedQuantity, Now));
+ Assert.Throws(() => delivery.Replace(DeliveryStatus.Missed, 500, person.ExpectedQuantity, Now));
+ Assert.Equal(750, delivery.DeliveredQuantity.Millilitres);
+ }
+
+ [Fact]
+ [Trait("Invariant", "L-6")]
+ public void Inactive_recipient_cannot_receive_a_delivery()
+ {
+ Assert.Throws(() => Delivery.Record(Person(), new DateOnly(2026, 9, 30),
+ DeliveryStatus.Delivered, null, Now));
+ }
+}
diff --git a/backend/tests/PureFreshMilk.Infrastructure.Tests/DeliveryConstraintTests.cs b/backend/tests/PureFreshMilk.Infrastructure.Tests/DeliveryConstraintTests.cs
new file mode 100644
index 0000000..9f0c5c8
--- /dev/null
+++ b/backend/tests/PureFreshMilk.Infrastructure.Tests/DeliveryConstraintTests.cs
@@ -0,0 +1,103 @@
+using Microsoft.EntityFrameworkCore;
+using Npgsql;
+using PureFreshMilk.Domain.Deliveries;
+using PureFreshMilk.Domain.Households;
+using PureFreshMilk.Domain.Recipients;
+using PureFreshMilk.Infrastructure.Persistence;
+
+namespace PureFreshMilk.Infrastructure.Tests;
+
+[Trait("Category", "Database")]
+public sealed class DeliveryConstraintTests(PostgresDatabaseFixture database) : IClassFixture
+{
+ private static CancellationToken Ct => TestContext.Current.CancellationToken;
+
+ private async Task<(Household Household, Recipient Recipient)> SeedAsync()
+ {
+ await using var context = database.CreateContext();
+ await context.Database.ExecuteSqlRawAsync("truncate table deliveries, milk_rates, recipients, households", Ct);
+ var household = Seed.NewHousehold();
+ var recipient = Seed.NewRecipient(household);
+ context.Households.Add(household);
+ context.Recipients.Add(recipient);
+ await context.SaveChangesAsync(Ct);
+ return (household, recipient);
+ }
+
+ [Fact]
+ [Trait("Invariant", "L-7")]
+ public async Task Unique_index_keeps_one_delivery_per_recipient_and_date()
+ {
+ var (household, recipient) = await SeedAsync();
+ await using (var context = database.CreateContext())
+ {
+ context.Deliveries.Add(Delivery.Record(recipient, Seed.Start, DeliveryStatus.Delivered, null, Seed.Now));
+ await context.SaveChangesAsync(Ct);
+ }
+
+ await using var duplicate = database.CreateContext();
+ duplicate.Deliveries.Add(Delivery.Record(recipient, Seed.Start, DeliveryStatus.Missed, null, Seed.Now));
+ var exception = await Assert.ThrowsAsync(
+ () => new UnitOfWork(duplicate).SaveChangesAsync(Ct));
+ Assert.Equal("delivery-date-taken", exception.Code);
+ Assert.Equal(1, await duplicate.Deliveries.AsNoTracking().CountAsync(delivery => delivery.HouseholdId == household.Id, Ct));
+ }
+
+ [Fact]
+ [Trait("Invariant", "L-10")]
+ public async Task Simultaneous_inserts_leave_one_row_and_report_the_loser()
+ {
+ var (household, recipient) = await SeedAsync();
+
+ async Task WriteAsync(DeliveryStatus status)
+ {
+ await using var context = database.CreateContext();
+ context.Deliveries.Add(Delivery.Record(recipient, Seed.Start, status, null, Seed.Now));
+ try
+ {
+ await new UnitOfWork(context).SaveChangesAsync(Ct);
+ return null;
+ }
+ catch (PureFreshMilk.Application.Common.ConflictException exception)
+ {
+ return exception;
+ }
+ }
+
+ var results = await Task.WhenAll(WriteAsync(DeliveryStatus.Delivered), WriteAsync(DeliveryStatus.Missed));
+ Assert.Single(results, result => result is null);
+ Assert.Single(results, result => result is PureFreshMilk.Application.Common.ConflictException);
+ await using var reading = database.CreateContext();
+ Assert.Equal(1, await reading.Deliveries.CountAsync(delivery => delivery.HouseholdId == household.Id, Ct));
+ }
+
+ [Theory]
+ [Trait("Invariant", "L-12")]
+ [InlineData("delivered", 0, "ck_deliveries_quantity")]
+ [InlineData("missed", 500, "ck_deliveries_quantity")]
+ [InlineData("unknown", 0, "ck_deliveries_quantity")]
+ public async Task Database_rejects_invalid_status_and_quantity(string status, int ml, string constraint)
+ {
+ var (household, recipient) = await SeedAsync();
+ await using var context = database.CreateContext();
+ var exception = await Assert.ThrowsAsync(() => context.Database.ExecuteSqlAsync(
+ $"insert into deliveries (id, household_id, recipient_id, delivery_date, status, delivered_ml, created_at, updated_at) values ({Guid.CreateVersion7()}, {household.Id.Value}, {recipient.Id.Value}, {Seed.Start}, {status}, {ml}, {Seed.Now}, {Seed.Now})", Ct));
+ Assert.Equal(PostgresErrorCodes.CheckViolation, exception.SqlState);
+ Assert.Equal(constraint, exception.ConstraintName);
+ }
+
+ [Fact]
+ [Trait("Invariant", "L-9")]
+ public async Task Composite_foreign_key_rejects_another_households_recipient()
+ {
+ var (_, recipient) = await SeedAsync();
+ await using var context = database.CreateContext();
+ var other = Seed.NewHousehold("Another household");
+ context.Households.Add(other);
+ await context.SaveChangesAsync(Ct);
+ var exception = await Assert.ThrowsAsync(() => context.Database.ExecuteSqlAsync(
+ $"insert into deliveries (id, household_id, recipient_id, delivery_date, status, delivered_ml, created_at, updated_at) values ({Guid.CreateVersion7()}, {other.Id.Value}, {recipient.Id.Value}, {Seed.Start}, {"delivered"}, {500}, {Seed.Now}, {Seed.Now})", Ct));
+ Assert.Equal(PostgresErrorCodes.ForeignKeyViolation, exception.SqlState);
+ Assert.Equal("fk_deliveries_recipients_household_id_recipient_id", exception.ConstraintName);
+ }
+}
diff --git a/backend/tests/PureFreshMilk.Infrastructure.Tests/HandlerFlowTests.cs b/backend/tests/PureFreshMilk.Infrastructure.Tests/HandlerFlowTests.cs
index c337a84..8b154bb 100644
--- a/backend/tests/PureFreshMilk.Infrastructure.Tests/HandlerFlowTests.cs
+++ b/backend/tests/PureFreshMilk.Infrastructure.Tests/HandlerFlowTests.cs
@@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using PureFreshMilk.Application.Common;
+using PureFreshMilk.Application.Deliveries;
using PureFreshMilk.Application.Households;
using PureFreshMilk.Application.Rates;
using PureFreshMilk.Application.Recipients;
@@ -29,6 +30,7 @@ private sealed class Request(PureFreshMilkDbContext context, TimeProvider clock)
private readonly HouseholdRepository households = new(context);
private readonly RecipientRepository recipients = new(context);
private readonly MilkRateRepository rates = new(context);
+ private readonly DeliveryRepository deliveries = new(context);
private readonly SingleHouseholdProvider current = new(context);
private readonly UnitOfWork unitOfWork = new(context);
@@ -40,9 +42,9 @@ private sealed class Request(PureFreshMilkDbContext context, TimeProvider clock)
public ListRecipientsHandler ListRecipients => new(current, recipients, clock);
- public UpdateRecipientHandler UpdateRecipient => new(current, recipients, unitOfWork, clock);
+ public UpdateRecipientHandler UpdateRecipient => new(current, recipients, deliveries, unitOfWork, clock);
- public ArchiveRecipientHandler ArchiveRecipient => new(current, recipients, unitOfWork, clock);
+ public ArchiveRecipientHandler ArchiveRecipient => new(current, recipients, deliveries, unitOfWork, clock);
public UnarchiveRecipientHandler UnarchiveRecipient => new(current, recipients, unitOfWork, clock);
@@ -64,7 +66,7 @@ private sealed class Request(PureFreshMilkDbContext context, TimeProvider clock)
private async Task StartEmptyAsync()
{
await using var context = database.CreateContext();
- await context.Database.ExecuteSqlRawAsync("truncate table milk_rates, recipients, households", Ct);
+ await context.Database.ExecuteSqlRawAsync("truncate table deliveries, milk_rates, recipients, households", Ct);
}
private async Task SetUpHouseholdAsync()
diff --git a/backend/tests/PureFreshMilk.Infrastructure.Tests/MigrationTests.cs b/backend/tests/PureFreshMilk.Infrastructure.Tests/MigrationTests.cs
index fe35669..39da99c 100644
--- a/backend/tests/PureFreshMilk.Infrastructure.Tests/MigrationTests.cs
+++ b/backend/tests/PureFreshMilk.Infrastructure.Tests/MigrationTests.cs
@@ -16,6 +16,7 @@ public async Task Migrations_apply_to_an_empty_database_and_the_model_has_no_fur
var applied = await context.Database.GetAppliedMigrationsAsync(Ct);
Assert.Contains(applied, name => name.EndsWith("_AddHouseholdsRecipientsAndMilkRates", StringComparison.Ordinal));
+ Assert.Contains(applied, name => name.EndsWith("_AddDeliveries", StringComparison.Ordinal));
Assert.Empty(await context.Database.GetPendingMigrationsAsync(Ct));
Assert.False(context.Database.HasPendingModelChanges(), "The model differs from the last migration: add a migration.");
}
@@ -30,13 +31,21 @@ public async Task The_tables_have_the_columns_and_types_that_the_design_lists()
"""
select table_name || '.' || column_name || ' ' || data_type || ' ' || is_nullable as "Value"
from information_schema.columns
- where table_schema = 'public' and table_name in ('households', 'recipients', 'milk_rates')
+ where table_schema = 'public' and table_name in ('households', 'recipients', 'milk_rates', 'deliveries')
order by 1
""")
.ToListAsync(Ct);
Assert.Equal(
[
+ "deliveries.created_at timestamp with time zone NO",
+ "deliveries.delivered_ml integer NO",
+ "deliveries.delivery_date date NO",
+ "deliveries.household_id uuid NO",
+ "deliveries.id uuid NO",
+ "deliveries.recipient_id uuid NO",
+ "deliveries.status character varying NO",
+ "deliveries.updated_at timestamp with time zone NO",
"households.created_at timestamp with time zone NO",
"households.id uuid NO",
"households.name character varying NO",
@@ -70,7 +79,7 @@ public async Task The_constraints_and_indexes_of_the_design_exist()
.SqlQueryRaw(
"""
select conname as "Value" from pg_constraint
- where conrelid in ('households'::regclass, 'recipients'::regclass, 'milk_rates'::regclass)
+ where conrelid in ('households'::regclass, 'recipients'::regclass, 'milk_rates'::regclass, 'deliveries'::regclass)
and contype in ('p', 'u', 'f', 'c') -- PostgreSQL 18 also lists NOT NULL ('n') here
order by conname
""")
@@ -78,13 +87,17 @@ order by conname
Assert.Equal(
[
+ "ck_deliveries_quantity",
+ "ck_deliveries_status",
"ck_households_name_length",
"ck_milk_rates_price",
"ck_recipients_archived_after_start",
"ck_recipients_expected_ml",
"ck_recipients_name_length",
+ "fk_deliveries_recipients_household_id_recipient_id",
"fk_milk_rates_households_household_id",
"fk_recipients_households_household_id",
+ "pk_deliveries",
"pk_households",
"pk_milk_rates",
"pk_recipients",
@@ -109,7 +122,7 @@ order by conname
.ToListAsync(Ct);
Assert.Equal(
- ["fk_milk_rates_households_household_id r", "fk_recipients_households_household_id r"],
+ ["fk_deliveries_recipients_household_id_recipient_id r", "fk_milk_rates_households_household_id r", "fk_recipients_households_household_id r"],
rules);
}
diff --git a/backend/tests/PureFreshMilk.TestSupport/InMemoryDatabase.cs b/backend/tests/PureFreshMilk.TestSupport/InMemoryDatabase.cs
index 28d0a07..88bdfd3 100644
--- a/backend/tests/PureFreshMilk.TestSupport/InMemoryDatabase.cs
+++ b/backend/tests/PureFreshMilk.TestSupport/InMemoryDatabase.cs
@@ -1,4 +1,5 @@
using PureFreshMilk.Application.Persistence;
+using PureFreshMilk.Domain.Deliveries;
using PureFreshMilk.Domain.Households;
using PureFreshMilk.Domain.Rates;
using PureFreshMilk.Domain.Recipients;
@@ -20,6 +21,7 @@ public sealed class InMemoryDatabase : IUnitOfWork
public List Recipients { get; } = [];
public List MilkRates { get; } = [];
+ public List Deliveries { get; } = [];
/// How many times has been called.
public int SaveCount { get; private set; }
@@ -45,6 +47,7 @@ public void Clear()
Households.Clear();
Recipients.Clear();
MilkRates.Clear();
+ Deliveries.Clear();
pendingChanges.Clear();
SaveCount = 0;
}
diff --git a/backend/tests/PureFreshMilk.TestSupport/InMemoryDeliveryRepository.cs b/backend/tests/PureFreshMilk.TestSupport/InMemoryDeliveryRepository.cs
new file mode 100644
index 0000000..c576062
--- /dev/null
+++ b/backend/tests/PureFreshMilk.TestSupport/InMemoryDeliveryRepository.cs
@@ -0,0 +1,30 @@
+using PureFreshMilk.Application.Deliveries;
+using PureFreshMilk.Domain.Deliveries;
+using PureFreshMilk.Domain.Households;
+using PureFreshMilk.Domain.Recipients;
+
+namespace PureFreshMilk.TestSupport;
+
+public sealed class InMemoryDeliveryRepository(InMemoryDatabase database) : IDeliveryRepository
+{
+ public Task FindAsync(HouseholdId householdId, RecipientId recipientId, DateOnly date,
+ CancellationToken cancellationToken) => Task.FromResult(database.Deliveries.SingleOrDefault(delivery =>
+ delivery.HouseholdId == householdId && delivery.RecipientId == recipientId && delivery.DeliveryDate == date));
+
+ public Task> ListAsync(HouseholdId householdId, DateOnly from, DateOnly to,
+ CancellationToken cancellationToken) => Task.FromResult>(database.Deliveries.Where(delivery =>
+ delivery.HouseholdId == householdId && delivery.DeliveryDate >= from && delivery.DeliveryDate <= to).ToArray());
+
+ public Task FirstDateAsync(HouseholdId householdId, RecipientId recipientId,
+ CancellationToken cancellationToken) => Task.FromResult(database.Deliveries.Where(delivery =>
+ delivery.HouseholdId == householdId && delivery.RecipientId == recipientId)
+ .Select(delivery => (DateOnly?)delivery.DeliveryDate).Min());
+
+ public Task LastDateAsync(HouseholdId householdId, RecipientId recipientId,
+ CancellationToken cancellationToken) => Task.FromResult(database.Deliveries.Where(delivery =>
+ delivery.HouseholdId == householdId && delivery.RecipientId == recipientId)
+ .Select(delivery => (DateOnly?)delivery.DeliveryDate).Max());
+
+ public void Add(Delivery delivery) => database.StageChange(() => database.Deliveries.Add(delivery));
+ public void Remove(Delivery delivery) => database.StageChange(() => database.Deliveries.Remove(delivery));
+}
diff --git a/backend/tests/PureFreshMilk.TestSupport/InMemoryPersistenceExtensions.cs b/backend/tests/PureFreshMilk.TestSupport/InMemoryPersistenceExtensions.cs
index 31ad179..bbc0d27 100644
--- a/backend/tests/PureFreshMilk.TestSupport/InMemoryPersistenceExtensions.cs
+++ b/backend/tests/PureFreshMilk.TestSupport/InMemoryPersistenceExtensions.cs
@@ -1,5 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
+using PureFreshMilk.Application.Deliveries;
using PureFreshMilk.Application.Households;
using PureFreshMilk.Application.Persistence;
using PureFreshMilk.Application.Rates;
@@ -22,6 +23,7 @@ public static InMemoryDatabase UseInMemoryPersistence(this IServiceCollection se
services.RemoveAll();
services.RemoveAll();
services.RemoveAll();
+ services.RemoveAll();
services.RemoveAll();
services.AddSingleton(database);
@@ -30,6 +32,7 @@ public static InMemoryDatabase UseInMemoryPersistence(this IServiceCollection se
services.AddSingleton(households);
services.AddSingleton(new InMemoryRecipientRepository(database));
services.AddSingleton(new InMemoryMilkRateRepository(database));
+ services.AddSingleton(new InMemoryDeliveryRepository(database));
return database;
}
From 2e7d51240433154c07ed0d783c831a69dba1fe19 Mon Sep 17 00:00:00 2001
From: Satyam Yadav <114805086+Coding-Professional@users.noreply.github.com>
Date: Mon, 23 Nov 2026 18:44:50 +0530
Subject: [PATCH 3/3] feat(web): connect Today and History to saved deliveries
---
README.md | 9 +-
apps/web/src/app/(auth)/login/page.tsx | 2 +-
apps/web/src/app/(auth)/signup/page.tsx | 2 +-
apps/web/src/app/app/history/[date]/page.tsx | 14 +
apps/web/src/app/app/history/page.tsx | 20 +-
apps/web/src/app/app/settings/page.tsx | 4 +-
apps/web/src/app/app/today/page.tsx | 11 +-
.../web/src/components/layout/site-footer.tsx | 2 +-
.../src/features/history/history-screen.tsx | 112 ++++++++
.../features/today/connected-day-screen.tsx | 251 ++++++++++++++++++
apps/web/src/features/today/delivery-card.tsx | 22 +-
apps/web/src/features/today/today-state.ts | 7 +-
apps/web/src/features/today/today-summary.tsx | 12 +-
apps/web/src/services/delivery-service.ts | 51 ++++
apps/web/src/types/api.ts | 30 +++
apps/web/tests/e2e/recipients.spec.ts | 4 +-
.../features/connected-day-screen.test.tsx | 63 +++++
.../tests/unit/features/today-state.test.ts | 2 +-
.../unit/services/delivery-service.test.ts | 51 ++++
docs/architecture/domain-model.md | 1 +
docs/architecture/overview.md | 21 +-
docs/development.md | 31 ++-
.../slice-1-recipients-and-deliveries.md | 2 +-
scripts/migrate-db.ps1 | 29 ++
scripts/migrate-db.sh | 30 +++
25 files changed, 719 insertions(+), 64 deletions(-)
create mode 100644 apps/web/src/app/app/history/[date]/page.tsx
create mode 100644 apps/web/src/features/history/history-screen.tsx
create mode 100644 apps/web/src/features/today/connected-day-screen.tsx
create mode 100644 apps/web/src/services/delivery-service.ts
create mode 100644 apps/web/tests/unit/features/connected-day-screen.test.tsx
create mode 100644 apps/web/tests/unit/services/delivery-service.test.ts
create mode 100644 scripts/migrate-db.ps1
create mode 100644 scripts/migrate-db.sh
diff --git a/README.md b/README.md
index 1e9252d..6c01326 100644
--- a/README.md
+++ b/README.md
@@ -4,9 +4,10 @@ PureFreshMilk keeps an exact record of a household's daily milk deliveries: who
and which mornings the milk didn't come. Monthly totals, charges, payments and outstanding
balances come next.
-> **Project status: foundation.** The repository structure, architecture and tooling are in place.
-> The **Today** screen is a working visual prototype on **synthetic demo data**. Nothing is saved
-> yet, and billing, accounts and persistence are not implemented.
+> **Project status: daily recording works locally.** With the API and PostgreSQL running, you can
+> set up a household, manage recipients and milk prices, record deliveries, and review past days.
+> Without an API address, Today and Recipients show clearly labelled synthetic demo data.
+> Billing and accounts are not implemented yet.
> See [what is not implemented yet](docs/architecture/overview.md#what-is-not-implemented-yet).
## Tech stack
@@ -54,7 +55,9 @@ npm run dev # http://localhost:3000
```bash
cp .env.example .env # set POSTGRES_PASSWORD
docker compose up -d --wait # PostgreSQL on localhost:5432
+bash scripts/migrate-db.sh # apply both migrations (or: pwsh scripts/migrate-db.ps1)
bash scripts/run-api.sh # API on http://localhost:5080 (or: pwsh scripts/run-api.ps1)
+# in a second terminal:
cd apps/web && cp .env.example .env.local && npm run dev
```
diff --git a/apps/web/src/app/(auth)/login/page.tsx b/apps/web/src/app/(auth)/login/page.tsx
index 87b899d..eed1243 100644
--- a/apps/web/src/app/(auth)/login/page.tsx
+++ b/apps/web/src/app/(auth)/login/page.tsx
@@ -27,7 +27,7 @@ export default function LoginPage() {
href="/app/today"
className="font-semibold text-accent underline-offset-4 hover:underline"
>
- try the Today screen with demo data
+ open the Today screen
>
diff --git a/apps/web/src/app/(auth)/signup/page.tsx b/apps/web/src/app/(auth)/signup/page.tsx
index 58f22c7..04bd3e8 100644
--- a/apps/web/src/app/(auth)/signup/page.tsx
+++ b/apps/web/src/app/(auth)/signup/page.tsx
@@ -27,7 +27,7 @@ export default function SignupPage() {
href="/app/today"
className="font-semibold text-accent underline-offset-4 hover:underline"
>
- try the Today screen with demo data
+ open the Today screen
>
diff --git a/apps/web/src/app/app/history/[date]/page.tsx b/apps/web/src/app/app/history/[date]/page.tsx
new file mode 100644
index 0000000..2f5d211
--- /dev/null
+++ b/apps/web/src/app/app/history/[date]/page.tsx
@@ -0,0 +1,14 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { ConnectedDayScreen } from "@/features/today/connected-day-screen";
+import { isIsoDate } from "@/lib/dates";
+
+export const metadata: Metadata = { title: "Day record" };
+// The date is a request-time route parameter; this page renders when navigated to.
+export const instant = false;
+
+export default async function DayRecordPage({ params }: { params: Promise<{ date: string }> }) {
+ const { date } = await params;
+ if (!isIsoDate(date)) notFound();
+ return ;
+}
diff --git a/apps/web/src/app/app/history/page.tsx b/apps/web/src/app/app/history/page.tsx
index 4be8deb..ac6e825 100644
--- a/apps/web/src/app/app/history/page.tsx
+++ b/apps/web/src/app/app/history/page.tsx
@@ -1,24 +1,8 @@
import type { Metadata } from "next";
-import { History } from "lucide-react";
-import { PageHeader } from "@/components/layout/page-header";
-import { PlaceholderPanel } from "@/components/ui/placeholder-panel";
+import { HistoryScreen } from "@/features/history/history-screen";
export const metadata: Metadata = { title: "History" };
export default function HistoryPage() {
- return (
- <>
-
-
- >
- );
+ return ;
}
diff --git a/apps/web/src/app/app/settings/page.tsx b/apps/web/src/app/app/settings/page.tsx
index 05842a3..a42eb34 100644
--- a/apps/web/src/app/app/settings/page.tsx
+++ b/apps/web/src/app/app/settings/page.tsx
@@ -15,9 +15,9 @@ export default function SettingsPage() {
diff --git a/apps/web/src/app/app/today/page.tsx b/apps/web/src/app/app/today/page.tsx
index 4cb8a6b..123021d 100644
--- a/apps/web/src/app/app/today/page.tsx
+++ b/apps/web/src/app/app/today/page.tsx
@@ -1,11 +1,16 @@
import type { Metadata } from "next";
import { TodayScreen } from "@/features/today/today-screen";
+import { ConnectedDayScreen } from "@/features/today/connected-day-screen";
import { DEMO_RECIPIENTS } from "@/lib/demo-household";
+import { getApiBaseUrl } from "@/services/api-client";
export const metadata: Metadata = { title: "Today" };
-// Demo data for now. When persistence lands, this page will load the household's
-// recipients and today's entries from the API instead.
+// Without an API address, the explicitly labelled demo remains available.
export default function TodayPage() {
- return ;
+ return getApiBaseUrl() ? (
+
+ ) : (
+
+ );
}
diff --git a/apps/web/src/components/layout/site-footer.tsx b/apps/web/src/components/layout/site-footer.tsx
index 7071c7d..5551b77 100644
--- a/apps/web/src/components/layout/site-footer.tsx
+++ b/apps/web/src/components/layout/site-footer.tsx
@@ -2,7 +2,7 @@ import Link from "next/link";
import { BrandMark } from "./brand";
const links = [
- { href: "/app/today", label: "Today (demo)" },
+ { href: "/app/today", label: "Today" },
{ href: "/login", label: "Log in" },
{ href: "/signup", label: "Sign up" },
];
diff --git a/apps/web/src/features/history/history-screen.tsx b/apps/web/src/features/history/history-screen.tsx
new file mode 100644
index 0000000..ea313d9
--- /dev/null
+++ b/apps/web/src/features/history/history-screen.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { useCallback } from "react";
+import Link from "next/link";
+import { LoaderCircle } from "lucide-react";
+import { PageHeader } from "@/components/layout/page-header";
+import { DemoBadge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Notice } from "@/components/ui/notice";
+import { describeApiError } from "@/features/shared/api-error-message";
+import { useResource } from "@/features/shared/use-resource";
+import { formatIsoDate } from "@/lib/dates";
+import { formatQuantity } from "@/lib/quantity";
+import { getApiBaseUrl } from "@/services/api-client";
+import { hasProblemCode } from "@/services/api-client";
+import { listDaySummaries } from "@/services/delivery-service";
+import { getHousehold } from "@/services/household-service";
+
+export function HistoryScreen() {
+ return getApiBaseUrl() ? : ;
+}
+
+function DemoHistory() {
+ return (
+ <>
+ } />
+
+ The Today demo resets on reload. Connect the API to record days and see them here.
+
+ >
+ );
+}
+
+function ConnectedHistory() {
+ const load = useCallback(async (signal: AbortSignal) => {
+ const household = await getHousehold({ signal });
+ const end = new Date(`${household.today}T00:00:00Z`);
+ end.setUTCDate(end.getUTCDate() - 29);
+ const from = end.toISOString().slice(0, 10);
+ return { summaries: await listDaySummaries(from, household.today, { signal }) };
+ }, []);
+ const { state, retry } = useResource(load);
+
+ if (state.kind === "loading")
+ return (
+ <>
+
+
+
+ Loading history…
+
+ >
+ );
+ if (state.kind === "failed")
+ return (
+ <>
+
+ {hasProblemCode(state.error, "household-not-set-up") ? (
+
+ Start on the{" "}
+
+ Recipients page
+
+ , then your delivery history will appear here.
+
+ ) : (
+
+ Try again
+
+ }
+ >
+ {describeApiError(state.error)}
+
+ )}
+ >
+ );
+
+ return (
+ <>
+
+
+
+ {state.data.summaries.map(({ date, totals }) => (
+ -
+
+ {formatIsoDate(date)}
+
+ {totals.expectedMl === 0
+ ? "No deliveries expected"
+ : totals.delivered + totals.missed === 0
+ ? "Not recorded"
+ : `${formatQuantity(totals.deliveredMl)} delivered · ${totals.delivered} delivered · ${totals.missed} missed`}
+ {totals.notRecorded > 0 ? ` · ${totals.notRecorded} to mark` : ""}
+
+
+
+ ))}
+
+
+ >
+ );
+}
diff --git a/apps/web/src/features/today/connected-day-screen.tsx b/apps/web/src/features/today/connected-day-screen.tsx
new file mode 100644
index 0000000..be22d90
--- /dev/null
+++ b/apps/web/src/features/today/connected-day-screen.tsx
@@ -0,0 +1,251 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import Link from "next/link";
+import { LoaderCircle } from "lucide-react";
+import { PageHeader } from "@/components/layout/page-header";
+import { Button } from "@/components/ui/button";
+import { Notice } from "@/components/ui/notice";
+import { describeApiError } from "@/features/shared/api-error-message";
+import { useResource } from "@/features/shared/use-resource";
+import { formatIsoDate } from "@/lib/dates";
+import { recipientMarker } from "@/lib/recipient-marker";
+import { hasProblemCode } from "@/services/api-client";
+import {
+ clearDelivery,
+ deliverRemaining,
+ getDaySheet,
+ recordDelivery,
+} from "@/services/delivery-service";
+import type { ApiDayRow, ApiDaySheet } from "@/types/api";
+import { DeliveryCard } from "./delivery-card";
+import { SUMMARY_HEADING_ID, TodaySummary } from "./today-summary";
+import type { DaySummary, TodayRow } from "./today-state";
+
+/** Real day sheet. The API owns the saved totals; local changes are shown while a request is pending. */
+export function ConnectedDayScreen({ date }: { date: string }) {
+ const load = useCallback((signal: AbortSignal) => getDaySheet(date, { signal }), [date]);
+ const { state, refresh, retry } = useResource(load);
+ const [optimistic, setOptimistic] = useState<{ base: ApiDaySheet; sheet: ApiDaySheet } | null>(
+ null,
+ );
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+
+ const title = date === "today" ? "Today" : "Day record";
+ if (state.kind === "loading")
+ return (
+ <>
+
+
+
+ Loading deliveries…
+
+ >
+ );
+ if (state.kind === "failed")
+ return (
+ <>
+
+ {hasProblemCode(state.error, "household-not-set-up") ? (
+
+ Start on the{" "}
+
+ Recipients page
+
+ , then come back to record deliveries.
+
+ ) : (
+
+ Try again
+
+ }
+ >
+ {describeApiError(state.error)}
+
+ )}
+ >
+ );
+
+ const baseSheet = state.data;
+ const sheet = optimistic?.base === baseSheet ? optimistic.sheet : baseSheet;
+ const rows: TodayRow[] = sheet.rows.map((row) => ({
+ recipient: { id: row.recipientId, name: row.name, expectedMl: row.expectedMl },
+ marker: recipientMarker(row.name),
+ entry: {
+ recipientId: row.recipientId,
+ status: row.status === "notRecorded" ? "pending" : row.status,
+ deliveredMl: row.deliveredMl,
+ },
+ differenceMl: row.status === "delivered" ? row.deliveredMl - row.expectedMl : 0,
+ }));
+ const summary: DaySummary = {
+ expectedMl: sheet.totals.expectedMl,
+ deliveredMl: sheet.totals.deliveredMl,
+ counts: {
+ delivered: sheet.totals.delivered,
+ missed: sheet.totals.missed,
+ pending: sheet.totals.notRecorded,
+ },
+ };
+
+ async function change(
+ recipient: ApiDayRow,
+ status: "delivered" | "missed" | "notRecorded",
+ ml?: number,
+ ) {
+ if (busy) return;
+ const previous = sheet;
+ setBusy(true);
+ setError(null);
+ setOptimistic({
+ base: baseSheet,
+ sheet: changeRow(
+ previous,
+ recipient.recipientId,
+ status,
+ ml ?? (status === "delivered" ? recipient.expectedMl : 0),
+ ),
+ });
+ try {
+ if (status === "notRecorded") await clearDelivery(recipient.recipientId, previous.date);
+ else
+ await recordDelivery(
+ recipient.recipientId,
+ previous.date,
+ status,
+ status === "delivered" ? ml : undefined,
+ );
+ refresh();
+ } catch (cause) {
+ setOptimistic({ base: baseSheet, sheet: previous });
+ setError(describeApiError(cause));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function markRemaining() {
+ if (busy) return;
+ const previous = sheet;
+ setBusy(true);
+ setError(null);
+ let next = previous;
+ for (const row of previous.rows.filter((item) => item.status === "notRecorded"))
+ next = changeRow(next, row.recipientId, "delivered", row.expectedMl);
+ setOptimistic({ base: baseSheet, sheet: next });
+ try {
+ setOptimistic({ base: baseSheet, sheet: await deliverRemaining(previous.date) });
+ refresh();
+ } catch (cause) {
+ setOptimistic({ base: baseSheet, sheet: previous });
+ setError(describeApiError(cause));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <>
+
+ Back to History
+
+ ) : undefined
+ }
+ />
+ {error ? (
+
+ Reload day
+
+ }
+ >
+ {error}
+
+ ) : null}
+ {rows.length === 0 ? (
+
+ Add recipients on the{" "}
+
+ Recipients page
+ {" "}
+ to start recording deliveries.
+
+ ) : (
+
+
+
+
+ Deliveries
+
+
+ {rows.map((row) => {
+ const source = sheet.rows.find((item) => item.recipientId === row.recipient.id)!;
+ return (
+
+ change(source, row.entry.status === "delivered" ? "notRecorded" : "delivered")
+ }
+ onMiss={() =>
+ change(source, row.entry.status === "missed" ? "notRecorded" : "missed")
+ }
+ onClear={() => change(source, "notRecorded")}
+ onAdjust={(deltaMl) =>
+ change(source, "delivered", row.entry.deliveredMl + deltaMl)
+ }
+ />
+ );
+ })}
+
+
+
+ )}
+ >
+ );
+}
+
+function changeRow(
+ sheet: ApiDaySheet,
+ id: string,
+ status: ApiDayRow["status"],
+ ml: number,
+): ApiDaySheet {
+ const rows = sheet.rows.map((row) =>
+ row.recipientId === id ? { ...row, status, deliveredMl: ml } : row,
+ );
+ return {
+ ...sheet,
+ rows,
+ totals: {
+ expectedMl: rows.reduce((sum, row) => sum + row.expectedMl, 0),
+ deliveredMl: rows.reduce((sum, row) => sum + row.deliveredMl, 0),
+ delivered: rows.filter((row) => row.status === "delivered").length,
+ missed: rows.filter((row) => row.status === "missed").length,
+ notRecorded: rows.filter((row) => row.status === "notRecorded").length,
+ },
+ };
+}
diff --git a/apps/web/src/features/today/delivery-card.tsx b/apps/web/src/features/today/delivery-card.tsx
index 5d87fbc..259325a 100644
--- a/apps/web/src/features/today/delivery-card.tsx
+++ b/apps/web/src/features/today/delivery-card.tsx
@@ -14,10 +14,18 @@ interface DeliveryCardProps {
onMiss: () => void;
onClear: () => void;
onAdjust: (deltaMl: number) => void;
+ disabled?: boolean;
}
/** One recipient's delivery for today: delivered or missed, and how much arrived. */
-export function DeliveryCard({ row, onDeliver, onMiss, onClear, onAdjust }: DeliveryCardProps) {
+export function DeliveryCard({
+ row,
+ onDeliver,
+ onMiss,
+ onClear,
+ onAdjust,
+ disabled = false,
+}: DeliveryCardProps) {
const { recipient, marker, entry } = row;
const headingId = useId();
@@ -46,6 +54,7 @@ export function DeliveryCard({ row, onDeliver, onMiss, onClear, onAdjust }: Deli
tone="delivered"
recipientName={recipient.name}
pressed={entry.status === "delivered"}
+ disabled={disabled}
onClick={entry.status === "delivered" ? onClear : onDeliver}
/>
@@ -64,6 +74,7 @@ export function DeliveryCard({ row, onDeliver, onMiss, onClear, onAdjust }: Deli
deliveredMl={entry.deliveredMl}
differenceMl={row.differenceMl}
onAdjust={onAdjust}
+ disabled={disabled}
/>
) : null}
@@ -83,6 +94,7 @@ function StatusToggle({
recipientName,
pressed,
onClick,
+ disabled,
}: {
label: string;
icon: LucideIcon;
@@ -90,6 +102,7 @@ function StatusToggle({
recipientName: string;
pressed: boolean;
onClick: () => void;
+ disabled: boolean;
}) {
return (