From eee2c201fa21146f60cc5c72690f1d6b1f6eca66 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 5 Oct 2024 19:15:21 +0100 Subject: [PATCH] Store when barcode was last scanned --- Groceries.Data/AppDbContext.cs | 3 +++ Groceries.Data/Items/ItemBarcode.cs | 1 + .../20241005180119_item_barcodes_last_scanned_at.sql | 7 +++++++ Groceries/Transactions/TransactionsController.cs | 11 ++++++++++- 4 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 Groceries.Data/Migrations/20241005180119_item_barcodes_last_scanned_at.sql diff --git a/Groceries.Data/AppDbContext.cs b/Groceries.Data/AppDbContext.cs index c952f8b..fe3249f 100644 --- a/Groceries.Data/AppDbContext.cs +++ b/Groceries.Data/AppDbContext.cs @@ -33,6 +33,9 @@ public class AppDbContext : DbContext entity.Property(e => e.Format) .HasDefaultValueSql(); + + entity.Property(e => e.LastScannedAt) + .HasDefaultValueSql(); }); modelBuilder.Entity(entity => diff --git a/Groceries.Data/Items/ItemBarcode.cs b/Groceries.Data/Items/ItemBarcode.cs index a3479f1..47b1b22 100644 --- a/Groceries.Data/Items/ItemBarcode.cs +++ b/Groceries.Data/Items/ItemBarcode.cs @@ -12,4 +12,5 @@ public class ItemBarcode public Guid ItemId { get; init; } public long BarcodeData { get; init; } public string Format { get; init; } + public DateTime LastScannedAt { get; set; } } diff --git a/Groceries.Data/Migrations/20241005180119_item_barcodes_last_scanned_at.sql b/Groceries.Data/Migrations/20241005180119_item_barcodes_last_scanned_at.sql new file mode 100644 index 0000000..92c8a84 --- /dev/null +++ b/Groceries.Data/Migrations/20241005180119_item_barcodes_last_scanned_at.sql @@ -0,0 +1,7 @@ +ALTER TABLE item_barcodes +ADD COLUMN IF NOT EXISTS last_scanned_at timestamptz NOT NULL DEFAULT current_timestamp; + +UPDATE item_barcodes +SET last_scanned_at = created_at +FROM item_purchases +WHERE item_barcodes.item_id = item_purchases.item_id AND is_last_purchase = true; diff --git a/Groceries/Transactions/TransactionsController.cs b/Groceries/Transactions/TransactionsController.cs index a8c75ac..7db9e5f 100644 --- a/Groceries/Transactions/TransactionsController.cs +++ b/Groceries/Transactions/TransactionsController.cs @@ -76,7 +76,16 @@ public class TransactionsController : Controller .FirstOrDefaultAsync(); item ??= new Item(id: default); - item.Barcodes.Add(new ItemBarcode(item.Id, barcodeData.Value, barcodeFormat)); + + var barcode = new ItemBarcode(item.Id, barcodeData.Value, barcodeFormat); + item.Barcodes.Add(barcode); + + if (item.Id != default) + { + barcode.LastScannedAt = DateTime.UtcNow; + dbContext.Update(barcode); + await dbContext.SaveChangesAsync(); + } // TODO: Fix `MinValue` hack - view models? transactionItem = new TransactionItem(item.Id, decimal.MinValue, int.MinValue) { Item = item };