Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion crates/pos-core/src/catalog/products.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ pub struct Product {
pub allow_negative_stock: bool,
pub is_weighed: bool,
pub available_at_till: bool,
/// Priced when it is sold (a department key, a top-up, an open-price service), never from a
/// catalogue price: the till asks for the price before the line enters the cart.
pub open_price: bool,
pub plu: Option<u32>,
pub image: Option<String>,
pub archived: bool,
Expand Down Expand Up @@ -243,7 +246,8 @@ impl From<&Product> for ProductInput {
const SELECT: &str = "SELECT p.id, p.reference, p.name_ar, p.name_fr, p.name_en, p.category_id,
p.unit_id, u.code, u.decimals, p.tax_rate_id, t.rate_bp, p.kind, p.parent_id, p.sell_price,
p.cost_price, p.min_stock, p.track_stock, p.allow_negative_stock, p.is_weighed,
p.available_at_till, p.plu, p.image, p.archived_at IS NOT NULL, p.updated_at
p.available_at_till, p.plu, p.image, p.archived_at IS NOT NULL, p.updated_at,
EXISTS (SELECT 1 FROM open_price_products o WHERE o.product_id = p.id)
FROM products p JOIN units u ON u.id = p.unit_id JOIN tax_rates t ON t.id = p.tax_rate_id";

fn map(row: &Row<'_>) -> rusqlite::Result<Product> {
Expand Down Expand Up @@ -272,6 +276,7 @@ fn map(row: &Row<'_>) -> rusqlite::Result<Product> {
image: row.get(21)?,
archived: row.get(22)?,
updated_at: row.get(23)?,
open_price: row.get(24)?,
barcodes: Vec::new(),
prices: Vec::new(),
components: Vec::new(),
Expand Down
7 changes: 6 additions & 1 deletion crates/pos-core/src/catalog/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ pub struct ProductHit {
pub image: Option<String>,
pub archived: bool,
pub available_at_till: bool,
/// Priced when it is sold (a department key, a top-up, an open-price service): the till asks
/// for its price before the line enters the cart.
pub open_price: bool,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
Expand Down Expand Up @@ -59,7 +62,8 @@ const HIT_COLUMNS: &str =
(SELECT b.barcode FROM product_barcodes b WHERE b.product_id = p.id ORDER BY b.rowid LIMIT 1),
COALESCE((SELECT SUM(l.qty) FROM stock_levels l JOIN stock_locations s ON s.id = l.location_id
WHERE l.product_id = p.id AND s.kind = 'storage'), 0),
p.image, p.archived_at IS NOT NULL, p.available_at_till";
p.image, p.archived_at IS NOT NULL, p.available_at_till,
EXISTS (SELECT 1 FROM open_price_products o WHERE o.product_id = p.id)";

fn map_hit(row: &Row<'_>) -> rusqlite::Result<ProductHit> {
Ok(ProductHit {
Expand All @@ -77,6 +81,7 @@ fn map_hit(row: &Row<'_>) -> rusqlite::Result<ProductHit> {
image: row.get(11)?,
archived: row.get(12)?,
available_at_till: row.get(13)?,
open_price: row.get(14)?,
})
}

Expand Down
2 changes: 2 additions & 0 deletions crates/pos-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ pub const KNOWN_CODES: &[&str] = &[
"free_line_not_allowed",
"discount_not_allowed",
"discount_above_limit",
// a product priced when it is sold (a department key, a top-up) needs its price first
"open_price_required",
// M1 held tickets
"held_cart_not_found",
// M1 returns
Expand Down
2 changes: 1 addition & 1 deletion crates/pos-core/src/sales/cart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ fn price_line(
let unit_price = if open_price {
line.unit_price
.filter(|p| p.is_positive())
.ok_or_else(|| AppError::validation("unitPrice", "required"))?
.ok_or_else(|| AppError::validation("unitPrice", "open_price_required"))?
} else {
line.unit_price.unwrap_or(catalogue)
};
Expand Down
218 changes: 181 additions & 37 deletions crates/pos-core/src/sales/held.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
//! (SAL-040/041, AUD-001: line voids and cancelled carts). Holding touches neither stock nor
//! cash; a recalled cart is priced again with today's prices.

use super::cart::{self, Cart, RepricedCart};
use super::cart::{self, Cart, CartLine, RepricedCart};
use crate::audit;
use crate::catalog::clean_opt;
use crate::catalog::{clean_opt, products};
use crate::error::AppError;
use crate::ids::new_id;
use crate::money::{Money, Qty};
Expand Down Expand Up @@ -209,18 +209,22 @@ pub fn discard(tx: &Transaction<'_>, ctx: &TillContext, id: &str) -> Result<(),
Ok(())
}

/// Line `index` of `cart`, or `value_invalid` when the cart has no such line.
fn line_at(cart: &Cart, index: u32) -> Result<&CartLine, AppError> {
usize::try_from(index)
.ok()
.and_then(|i| cart.lines.get(i))
.ok_or_else(|| AppError::validation("index", "value_invalid"))
}

/// Line `index` of `cart` valued alone, at the quantity it has in `cart`.
fn value_line(
tx: &Transaction<'_>,
ctx: &TillContext,
cart: &Cart,
index: u32,
) -> Result<cart::PricedLine, AppError> {
let line = usize::try_from(index)
.ok()
.and_then(|i| cart.lines.get(i))
.cloned()
.ok_or_else(|| AppError::validation("index", "value_invalid"))?;
let line = line_at(cart, index)?.clone();
let alone = Cart {
lines: vec![line],
..cart.clone()
Expand All @@ -232,59 +236,140 @@ fn value_line(
.ok_or_else(|| AppError::validation("index", "value_invalid"))
}

/// Journals a line void or a cancelled cart (the command checks `sales.void_line`) with the
/// backend's figures: the voided line is valued alone (another line's refusal cannot block the
/// void), the cancelled cart as a whole, both as they stand ([`cart::value_cart`]).
/// Whether `err` only means a line cannot be priced: an open-price product rung without its price,
/// a free line without a tax rate, a product archived meanwhile. A void or a cancellation is
/// journaled anyway, with what the cart still says; a database, I/O or internal failure is not
/// swallowed.
fn unpriceable(err: &AppError) -> bool {
matches!(
err,
AppError::Validation { .. } | AppError::NotFound { .. } | AppError::Conflict { .. }
)
}

/// What the journal keeps of a line the backend cannot price: its product, its name (the open
/// item's, else the catalogue's in the ticket's language) and the amount its typed price gives
/// (nothing when it has none).
fn described_line(
conn: &Connection,
cart: &Cart,
line: &CartLine,
) -> (Option<String>, String, Money) {
let description = line
.description
.clone()
.or_else(|| {
line.product_id
.as_deref()
.and_then(|id| products::get(conn, id).ok())
.map(|product| product.name_in(cart.lang).to_owned())
})
.or_else(|| line.product_id.clone())
.unwrap_or_default();
let amount = line
.unit_price
.and_then(|price| price.mul_qty(line.qty))
.unwrap_or(Money::ZERO);
(line.product_id.clone(), description, amount)
}

/// The cart's total as far as it can be priced: a line the backend refuses is left out.
fn valueable_total(
tx: &Transaction<'_>,
ctx: &TillContext,
cart: &Cart,
) -> Result<Money, AppError> {
let mut amounts = Vec::with_capacity(cart.lines.len());
for index in 0..cart.lines.len() {
let index = u32::try_from(index).unwrap_or(u32::MAX);
match value_line(tx, ctx, cart, index) {
Ok(line) => amounts.push(line.amounts.total_ttc),
Err(err) if unpriceable(&err) => {}
Err(err) => return Err(err),
}
}
Ok(Money::checked_sum(amounts).unwrap_or(Money::ZERO))
}

/// Journals a line void, a lowered quantity or a cancelled cart (the command checks
/// `sales.void_line`) with the backend's figures: the voided line is valued alone (another line's
/// refusal cannot block the void), the cancelled cart as a whole, both as they stand
/// ([`cart::value_cart`]). A line that can no longer be priced — an open-price product rung
/// without its price — is still journaled, with its name, its quantity and the amount its typed
/// price gives: a cart that cannot be sold must stay voidable and cancellable (SAL-040/041,
/// AUD-001), as [`discard`] already does for a held ticket.
pub fn record_cart_event(
tx: &Transaction<'_>,
ctx: &TillContext,
input: CartEventInput,
) -> Result<(), AppError> {
let event = match input {
CartEventInput::LineVoided { cart, index } => {
let line = value_line(tx, ctx, &cart, index)?;
let line = line_at(&cart, index)?;
let (product_id, description, amount) = match value_line(tx, ctx, &cart, index) {
Ok(priced) => (
priced.product_id,
priced.description,
priced.amounts.total_ttc,
),
Err(err) if unpriceable(&err) => described_line(tx, &cart, line),
Err(err) => return Err(err),
};
CartEvent::LineVoided {
product_id: line.product_id,
description: line.description,
product_id,
description,
qty: line.qty,
amount: line.amounts.total_ttc,
amount,
}
}
CartEventInput::CartCancelled { cart } => {
let valued = cart::value_cart(tx, ctx, &cart)?;
let total = match cart::value_cart(tx, ctx, &cart) {
Ok(valued) => valued.totals.total_ttc,
Err(err) if unpriceable(&err) => valueable_total(tx, ctx, &cart)?,
Err(err) => return Err(err),
};
CartEvent::CartCancelled {
lines: u32::try_from(valued.lines.len()).unwrap_or(u32::MAX),
total: valued.totals.total_ttc,
lines: u32::try_from(cart.lines.len()).unwrap_or(u32::MAX),
total,
}
}
CartEventInput::QtyReduced { cart, index, qty } => {
let before = value_line(tx, ctx, &cart, index)?;
let line = line_at(&cart, index)?;
if !qty.is_positive() {
return Err(AppError::validation("qty", "qty_invalid"));
}
if qty >= before.qty {
if qty >= line.qty {
return Err(AppError::validation("qty", "value_invalid"));
}
let mut lowered = cart.clone();
if let Some(line) = usize::try_from(index)
.ok()
.and_then(|i| lowered.lines.get_mut(i))
{
line.qty = qty;
}
let after = value_line(tx, ctx, &lowered, index)?;
let removed = Qty(before.qty.0 - qty.0);
let amount = before
.amounts
.total_ttc
.checked_sub(after.amounts.total_ttc)
.ok_or_else(|| AppError::validation("qty", "value_invalid"))?;
let amount = match value_line(tx, ctx, &cart, index) {
Ok(before) => {
let mut lowered = cart.clone();
if let Some(line) = usize::try_from(index)
.ok()
.and_then(|i| lowered.lines.get_mut(i))
{
line.qty = qty;
}
match value_line(tx, ctx, &lowered, index) {
Ok(after) => before
.amounts
.total_ttc
.checked_sub(after.amounts.total_ttc)
.ok_or_else(|| AppError::validation("qty", "value_invalid"))?,
Err(err) if unpriceable(&err) => Money::ZERO,
Err(err) => return Err(err),
}
}
Err(err) if unpriceable(&err) => Money::ZERO,
Err(err) => return Err(err),
};
let (product_id, description, _) = described_line(tx, &cart, line);
CartEvent::QtyReduced {
product_id: before.product_id,
description: before.description,
qty_before: before.qty,
product_id,
description,
qty_before: line.qty,
qty_after: qty,
removed_qty: removed,
removed_qty: Qty(line.qty.0 - qty.0),
amount,
}
}
Expand Down Expand Up @@ -439,6 +524,65 @@ mod tests {
);
}

/// An open-price product rung from the grid without its price cannot be valued, but a cart the
/// till can no longer price must stay voidable, cancellable and reducible (SAL-040/041,
/// AUD-001): the journal keeps its name, its quantity and no amount.
#[test]
fn an_unpriced_open_price_line_does_not_block_a_void_or_a_cancellation() {
let shop = shop();
let milk = shop.product("Lait", Money(10_000), &shop.tva19);
let divers = shop.department_key("Divers");
let cart = Cart::new(
Lang::Fr,
vec![
CartLine::product(&milk.id, Qty(1_000)),
CartLine::product(&divers, Qty(2_000)),
],
);
let ctx = shop.till();
let (voided, lowered, cancelled) = (cart.clone(), cart.clone(), cart);
shop.db
.write(move |tx| {
// the line has no price yet: the cart as a whole cannot be priced
assert!(cart::value_cart(tx, &ctx, &voided).is_err());
record_cart_event(
tx,
&ctx,
CartEventInput::LineVoided {
cart: voided,
index: 1,
},
)?;
record_cart_event(
tx,
&ctx,
CartEventInput::QtyReduced {
cart: lowered,
index: 1,
qty: Qty(1_000),
},
)?;
record_cart_event(tx, &ctx, CartEventInput::CartCancelled { cart: cancelled })
})
.unwrap();
assert_eq!(
event_of(&shop, "sale.line_voided"),
json!({ "kind": "line_voided", "productId": divers, "description": "Divers", "qty": 2_000, "amount": 0 })
);
assert_eq!(
event_of(&shop, "sale.qty_reduced"),
json!({
"kind": "qty_reduced", "productId": divers, "description": "Divers",
"qtyBefore": 2_000, "qtyAfter": 1_000, "removedQty": 1_000, "amount": 0
})
);
// the priced line still counts; the unpriced one is left out of the total
assert_eq!(
event_of(&shop, "sale.cancelled"),
json!({ "kind": "cart_cancelled", "lines": 2, "total": 10_000 })
);
}

/// Ten units rung and cut to one is a partial void: journaled with what left the cart.
#[test]
fn a_lowered_quantity_is_journaled_as_a_partial_void() {
Expand Down
15 changes: 15 additions & 0 deletions src/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,11 @@ export const commands = {
allowNegativeStock: boolean,
isWeighed: boolean,
availableAtTill: boolean,
/**
* Priced when it is sold (a department key, a top-up, an open-price service), never from a
* catalogue price: the till asks for the price before the line enters the cart.
*/
openPrice: boolean,
plu: number | null,
image: string | null,
archived: boolean,
Expand Down Expand Up @@ -6092,6 +6097,11 @@ export type Product = {
allowNegativeStock: boolean,
isWeighed: boolean,
availableAtTill: boolean,
/**
* Priced when it is sold (a department key, a top-up, an open-price service), never from a
* catalogue price: the till asks for the price before the line enters the cart.
*/
openPrice: boolean,
plu: number | null,
image: string | null,
archived: boolean,
Expand Down Expand Up @@ -6150,6 +6160,11 @@ export type ProductHit = {
image: string | null,
archived: boolean,
availableAtTill: boolean,
/**
* Priced when it is sold (a department key, a top-up, an open-price service): the till asks
* for its price before the line enters the cart.
*/
openPrice: boolean,
};

export type ProductInput = {
Expand Down
Loading