backbone_inventory/infrastructure/persistence/
purchase_receipt_item_repository.rs1use anyhow::Result;
12use rust_decimal::Decimal;
13use sqlx::{PgPool, Row};
14use uuid::Uuid;
15
16use backbone_orm::org_scope;
17
18use crate::domain::entity::PurchaseReceiptItem;
19
20pub const TABLE_NAME: &str = "inventory.purchase_receipt_items";
22
23pub struct PurchaseReceiptItemRepository(
28 backbone_orm::GenericCrudRepository<PurchaseReceiptItem, backbone_orm::SoftDelete>,
29);
30
31impl std::ops::Deref for PurchaseReceiptItemRepository {
32 type Target = backbone_orm::GenericCrudRepository<PurchaseReceiptItem, backbone_orm::SoftDelete>;
33 fn deref(&self) -> &Self::Target { &self.0 }
34}
35
36impl PurchaseReceiptItemRepository {
37 pub fn new(pool: PgPool) -> Self {
39 Self(backbone_orm::GenericCrudRepository::new(pool, TABLE_NAME))
40 }
41}
42
43pub struct NewReceiptItemRow {
45 pub id: Uuid,
46 pub receipt_id: Uuid,
47 pub item_id: Uuid,
48 pub quantity: Decimal,
49 pub rate: Decimal,
50 pub amount: Decimal,
51 pub is_landed_costs_line: bool,
54}
55
56pub struct ReceiptItemRow {
58 pub item_id: Uuid,
59 pub quantity: Decimal,
60 pub rate: Decimal,
61 pub is_landed_costs_line: bool,
63}
64
65impl PurchaseReceiptItemRepository {
67 pub async fn insert_item(
70 &self,
71 conn: &mut sqlx::PgConnection,
72 l: &NewReceiptItemRow,
73 ) -> Result<(), sqlx::Error> {
74 sqlx::query(
75 r#"INSERT INTO inventory.purchase_receipt_items
76 (id, receipt_id, item_id, quantity, rate, amount, is_landed_costs_line)
77 VALUES ($1,$2,$3,$4,$5,$6,$7)"#,
78 )
79 .bind(l.id).bind(l.receipt_id).bind(l.item_id).bind(l.quantity).bind(l.rate).bind(l.amount)
80 .bind(l.is_landed_costs_line)
81 .execute(conn)
82 .await?;
83 Ok(())
84 }
85
86 pub async fn fetch_items(
91 &self,
92 pool: &PgPool,
93 receipt_id: Uuid,
94 ) -> Result<Vec<ReceiptItemRow>, sqlx::Error> {
95 let rows = org_scope::fetch_all_rows_scoped(
96 pool,
97 sqlx::query(
98 r#"SELECT item_id, quantity, rate, is_landed_costs_line FROM inventory.purchase_receipt_items
99 WHERE receipt_id=$1 AND (metadata->>'deleted_at') IS NULL ORDER BY id"#,
100 )
101 .bind(receipt_id),
102 )
103 .await?;
104 Ok(rows.iter().map(|it| ReceiptItemRow {
105 item_id: it.get("item_id"), quantity: it.get("quantity"), rate: it.get("rate"),
106 is_landed_costs_line: it.get("is_landed_costs_line"),
107 }).collect())
108 }
109}
110
111backbone_core::impl_crud_repository!(PurchaseReceiptItemRepository, PurchaseReceiptItem, soft_delete);