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
10 changes: 5 additions & 5 deletions backend/app/services/sales_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ def get_invoice(self, invoice_id: int) -> SalesInvoice:
def create_invoice(self, data: SalesInvoiceCreate) -> SalesInvoice:
with transaction(self.db):
# --- VALIDATION ---
if data.invoice_type == "credit" and not data.customer_id:
raise ValidationError("Credit invoices require a customer")
if data.invoice_type in ("credit", "mixed") and not data.customer_id:
raise ValidationError("Credit and mixed invoices require a customer")

total_amount = sum(item.total_price for item in data.items)

if data.invoice_type == "credit" and data.customer_id:
if data.invoice_type in ("credit", "mixed") and data.customer_id:
self.validator.validate_credit_limit(data.customer_id, total_amount)

for item_data in data.items:
Expand Down Expand Up @@ -96,10 +96,10 @@ def create_invoice(self, data: SalesInvoiceCreate) -> SalesInvoice:
total_amount=total_amount,
cogs=sum(item.sold_quantity * item.cost_at_sale for item in data.items),
cash_received=data.paid_amount,
is_credit=(data.invoice_type == "credit"),
is_credit=(data.invoice_type in ("credit", "mixed")),
)

if data.invoice_type == "credit" and data.customer_id:
if data.invoice_type in ("credit", "mixed") and data.customer_id and remaining > 0:
customer = self.customer_repo.get_by_id(data.customer_id)
self.customer_repo.update_balance(customer, remaining)

Expand Down
6 changes: 6 additions & 0 deletions database/fix_mixed_invoice_type.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- Fix: Allow 'mixed' invoice type in the check constraint
-- The frontend supports 'mixed' invoices (part cash, part credit) but the DB constraint only allowed 'cash' or 'credit'

ALTER TABLE sales_invoices DROP CONSTRAINT chk_credit_requires_customer;
ALTER TABLE sales_invoices ADD CONSTRAINT chk_credit_requires_customer
CHECK (invoice_type = 'cash' OR (invoice_type IN ('credit', 'mixed') AND customer_id IS NOT NULL));
2 changes: 1 addition & 1 deletion database/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ CREATE TABLE sales_invoices (
warehouse_id INTEGER NOT NULL REFERENCES warehouses(warehouse_id),
warehouse_notes TEXT,
notes TEXT,
CONSTRAINT chk_credit_requires_customer CHECK (invoice_type = 'cash' OR (invoice_type = 'credit' AND customer_id IS NOT NULL))
CONSTRAINT chk_credit_requires_customer CHECK (invoice_type = 'cash' OR (invoice_type IN ('credit', 'mixed') AND customer_id IS NOT NULL))
);

-- 10. Sales Invoice Items
Expand Down