lambda-erp 1.4.2__py3-none-any.whl → 1.4.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
api/chat.py CHANGED
@@ -2865,6 +2865,8 @@ Returns use the SAME document type with negative quantities and `is_return=1`. C
2865
2865
  - **Delivery Note Return:** Convert a submitted Delivery Note. Stock comes back into the warehouse, reverses COGS entries.
2866
2866
  - **Purchase Receipt Return:** Convert a submitted Purchase Receipt. Stock goes back out, reverses stock-in-hand entries.
2867
2867
 
2868
+ - **Price correction / goodwill credit (no goods come back):** convert the invoice to a return as above, then on the draft set `amount_only=1` and set each line's `rate` to the amount credited per unit (qty stays negative: the units the credit is for). An amount-only credit or debit note never moves stock (also when the original had update_stock=1) and leaves billed and returnable quantities alone, so the goods can still be returned later. Sales Invoice and Purchase Invoice only. Do NOT use a plain return for a price correction.
2869
+
2868
2870
  To create a return: use convert_document with the SAME doctype as both source and target.
2869
2871
  Example: convert_document(doctype="sales-invoice", name="SINV-0001", target_doctype="Sales Invoice")
2870
2872
 
@@ -72,6 +72,8 @@ class PurchaseInvoice(Document):
72
72
  self.posting_date = nowdate()
73
73
 
74
74
  apply_external_source_defaults(self)
75
+ from lambda_erp.workflow import apply_amount_only
76
+ apply_amount_only(self)
75
77
  self._set_supplier_name()
76
78
  self._set_missing_accounts()
77
79
  set_default_currency(self, "Supplier", "supplier")
@@ -144,6 +146,20 @@ class PurchaseInvoice(Document):
144
146
  if not item.get("cost_center"):
145
147
  item["cost_center"] = default_cc
146
148
 
149
+ if flt(self.get("amount_only")):
150
+ # A price correction moves no goods, so it must not touch the
151
+ # stock accounts (Stock In Hand would drift from the stock ledger;
152
+ # SRBNB would keep a balance no receipt clears). The difference is
153
+ # a purchase price variance: stock adjustment, else expense.
154
+ variance = db.get_value("Company", self.company, "stock_adjustment_account") or default_expense
155
+ for item in self.get("items"):
156
+ account = item.get("expense_account")
157
+ if account and variance and (
158
+ account == stock_received_account
159
+ or db.get_value("Account", account, "account_type") == "Stock"
160
+ ):
161
+ item["expense_account"] = variance
162
+
147
163
  def _validate_stock_warehouses(self):
148
164
  """When update_stock=1, every stock-item line needs a warehouse so
149
165
  the SLE has somewhere to put the received goods."""
@@ -89,6 +89,8 @@ class SalesInvoice(Document):
89
89
  self.posting_date = nowdate()
90
90
 
91
91
  apply_external_source_defaults(self)
92
+ from lambda_erp.workflow import apply_amount_only
93
+ apply_amount_only(self)
92
94
  self._set_customer_name()
93
95
  self._set_missing_accounts()
94
96
  set_default_currency(self, "Customer", "customer")
lambda_erp/database.py CHANGED
@@ -862,6 +862,7 @@ class Database:
862
862
  is_return INTEGER DEFAULT 0,
863
863
  return_against TEXT,
864
864
  update_stock INTEGER DEFAULT 0,
865
+ amount_only INTEGER DEFAULT 0,
865
866
  is_pos INTEGER DEFAULT 0,
866
867
  paid_amount REAL DEFAULT 0,
867
868
  against_income_account TEXT,
@@ -937,6 +938,7 @@ class Database:
937
938
  is_return INTEGER DEFAULT 0,
938
939
  return_against TEXT,
939
940
  update_stock INTEGER DEFAULT 0,
941
+ amount_only INTEGER DEFAULT 0,
940
942
  against_expense_account TEXT,
941
943
  purchase_order TEXT,
942
944
  status TEXT DEFAULT 'Draft',
@@ -3200,6 +3202,13 @@ def _m049_pricing_rule_currency(db: "Database") -> None:
3200
3202
  [currencies[0]])
3201
3203
 
3202
3204
 
3205
+ def _m050_amount_only_returns(db: "Database") -> None:
3206
+ """A credit / debit note that corrects money only (price correction): no
3207
+ quantity returned, no stock moved. See workflow.apply_amount_only."""
3208
+ for table in ("Sales Invoice", "Purchase Invoice"):
3209
+ db.ensure_column(table, "amount_only", "INTEGER DEFAULT 0")
3210
+
3211
+
3203
3212
  def _m042_record_notes(db: "Database") -> None:
3204
3213
  """Internal team notes on any document or master (see api.record_notes)."""
3205
3214
  db.conn.execute(
@@ -3269,6 +3278,7 @@ Database.MIGRATIONS = [
3269
3278
  (47, "sales_order_status_left_to_do", _m047_sales_order_status_left_to_do),
3270
3279
  (48, "item_valuation_moving_average", _m048_item_valuation_moving_average),
3271
3280
  (49, "pricing_rule_currency", _m049_pricing_rule_currency),
3281
+ (50, "amount_only_returns", _m050_amount_only_returns),
3272
3282
  ]
3273
3283
 
3274
3284
 
lambda_erp/validation.py CHANGED
@@ -134,6 +134,8 @@ def document_requirements(cls):
134
134
  from lambda_erp.workflow import RETURN_TYPES
135
135
  if cls.DOCTYPE in RETURN_TYPES:
136
136
  rules.append('Returns require a submitted non-return original with matching company and party, negative quantities, original order-line references and quantities within the remaining returnable amount across all rows and previous returns. Use the return converter.')
137
+ if cls.DOCTYPE in {'Sales Invoice', 'Purchase Invoice'}:
138
+ rules.append('amount_only=1 on a return makes it a price correction: money only, no stock movement (update_stock is forced to 0), billed and returnable quantities of the original unchanged. Lines name original rows with negative qty (at most the invoiced qty) and the credited amount per unit as rate. Not allowed on non-returns.')
137
139
  if cls.DOCTYPE in TRANSACTION_TYPES:
138
140
  rules.append('Supplied warehouse, account and cost-center links must belong to company. Explicit rate=0 means free and is preserved; only absent/blank prices use defaults. Prices must be finite and non-negative.')
139
141
  required += ['company', 'items']
lambda_erp/workflow.py CHANGED
@@ -41,6 +41,27 @@ def _return_key(row, rule):
41
41
  return (identity, row.get(rule[2]) if rule else None)
42
42
 
43
43
 
44
+ def apply_amount_only(doc):
45
+ """A return invoice that corrects money only (a price correction, a
46
+ goodwill credit). No goods come back: it never moves stock and leaves the
47
+ billed and returnable quantities of its original alone. Its lines still
48
+ name the original rows with a negative qty (the units the credit is for)
49
+ so tax and totals work like on any other return."""
50
+ if not flt(doc.get('amount_only')):
51
+ return False
52
+ if not flt(doc.get('is_return')):
53
+ raise ValidationError('Amount only is for returns (credit / debit notes): set is_return and return_against')
54
+ doc._data['update_stock'] = 0
55
+ return True
56
+
57
+
58
+ def _goods_returns(doctype, alias='p'):
59
+ """SQL filter: leave amount-only returns out of quantity sums."""
60
+ if 'amount_only' not in get_db()._get_table_columns(doctype):
61
+ return ''
62
+ return f' AND COALESCE({alias}.amount_only, 0) = 0'
63
+
64
+
44
65
  def validate_return(doc):
45
66
  if not doc.get('return_against'):
46
67
  raise ValidationError(f'Return Against is required for a return {doc.DOCTYPE}')
@@ -58,17 +79,19 @@ def validate_return(doc):
58
79
  raise ValidationError('Return currency must match the original document')
59
80
  if not doc.get('currency'):
60
81
  doc.currency = original.currency
61
- if doc.DOCTYPE.endswith('Invoice') and bool(flt(doc.get('update_stock'))) != bool(flt(original.update_stock)):
62
- raise ValidationError('Return update_stock must match the original invoice')
82
+ amount_only = bool(flt(doc.get('amount_only')))
83
+ if not amount_only and doc.DOCTYPE.endswith('Invoice') and bool(flt(doc.get('update_stock'))) != bool(flt(original.update_stock)):
84
+ raise ValidationError('Return update_stock must match the original invoice; for a price correction without goods set amount_only')
63
85
  rule = ORDER_REFERENCES.get(doc.DOCTYPE)
64
86
  table = doc.CHILD_TABLES['items'][0]
65
87
  original_rows = db.get_all(table, filters={'parent': doc.return_against}, fields=['*'])
66
88
  quantities = defaultdict(float)
67
89
  for row in original_rows:
68
90
  quantities[_return_key(row, rule)] += flt(row.get('qty'))
69
- previous = db.sql(
91
+ previous = [] if amount_only else db.sql(
70
92
  f'SELECT i.* FROM "{table}" i JOIN "{doc.DOCTYPE}" p ON p.name = i.parent '
71
- 'WHERE p.return_against = ? AND p.is_return = 1 AND p.docstatus = 1 AND p.name != ?',
93
+ 'WHERE p.return_against = ? AND p.is_return = 1 AND p.docstatus = 1 AND p.name != ?'
94
+ + _goods_returns(doc.DOCTYPE),
72
95
  [doc.return_against, doc.name])
73
96
  returned = defaultdict(float)
74
97
  for row in previous:
@@ -82,6 +105,12 @@ def validate_return(doc):
82
105
  raise ValidationError('Return item and order line must match an original document row; use the return converter')
83
106
  requested[key] += abs(flt(row.get('qty')))
84
107
  for key, qty in requested.items():
108
+ if amount_only:
109
+ # Money only: bounded by what was invoiced (and by the value cap
110
+ # on the invoice), not by what is still returnable.
111
+ if qty > quantities[key] + EPSILON:
112
+ raise ValidationError(f'Amount-only qty ({qty}) for {key[0]} exceeds the invoiced qty ({quantities[key]})')
113
+ continue
85
114
  remaining = max(0, quantities[key] - returned[key])
86
115
  if qty > remaining + EPSILON:
87
116
  raise ValidationError(f'Return qty ({qty}) for {key[0]} exceeds remaining returnable qty ({remaining}; already returned {returned[key]})')
@@ -92,7 +121,8 @@ def _sum_line(doctype, line_field, line, *, exclude=None, stock_only=False):
92
121
  return flt(db.sql(
93
122
  f'SELECT COALESCE(SUM(i.qty), 0) AS qty FROM "{doctype} Item" i '
94
123
  f'JOIN "{doctype}" p ON p.name = i.parent WHERE i."{line_field}" = ? '
95
- 'AND p.docstatus = 1 AND p.name != ?' + (' AND p.update_stock = 1' if stock_only else ''),
124
+ 'AND p.docstatus = 1 AND p.name != ?' + (' AND p.update_stock = 1' if stock_only else '')
125
+ + _goods_returns(doctype),
96
126
  [line, exclude or ''])[0]['qty'])
97
127
 
98
128
 
@@ -101,11 +131,22 @@ def returnable_rows(original):
101
131
  db = get_db()
102
132
  rule = ORDER_REFERENCES.get(original.DOCTYPE)
103
133
  table = original.CHILD_TABLES['items'][0]
104
- previous = db.sql(f'SELECT i.* FROM "{table}" i JOIN "{original.DOCTYPE}" p ON p.name = i.parent '
134
+ flag = ', p.amount_only AS amount_only' if 'amount_only' in db._get_table_columns(original.DOCTYPE) else ''
135
+ previous = db.sql(f'SELECT i.*{flag} FROM "{table}" i JOIN "{original.DOCTYPE}" p ON p.name = i.parent '
105
136
  'WHERE p.return_against = ? AND p.is_return = 1 AND p.docstatus = 1', [original.name])
106
137
  used = defaultdict(float)
138
+ credited = defaultdict(float) # value already credited per line identity
139
+ corrected = set()
107
140
  for row in previous:
108
- used[_return_key(row, rule)] += abs(flt(row.qty))
141
+ key = _return_key(row, rule)
142
+ credited[key] += abs(flt(row.qty)) * flt(row.get('rate'))
143
+ if flt(row.get('amount_only')):
144
+ corrected.add(key)
145
+ else:
146
+ used[key] += abs(flt(row.qty))
147
+ invoiced = defaultdict(float)
148
+ for row in original.get('items'):
149
+ invoiced[_return_key(row, rule)] += flt(row.get('qty')) * flt(row.get('rate'))
109
150
  result = []
110
151
  for row in original.get('items'):
111
152
  key = _return_key(row, rule)
@@ -116,6 +157,15 @@ def returnable_rows(original):
116
157
  result.append({**row, 'qty':remaining})
117
158
  if not result:
118
159
  raise ValidationError('No remaining returnable quantity on this document')
160
+ # After a price correction the goods come back at what was left to pay
161
+ # for them, not at the original price (which would exceed the value cap).
162
+ for key in corrected:
163
+ rows = [row for row in result if _return_key(row, rule) == key]
164
+ at_original = sum(flt(row['qty']) * flt(row.get('rate')) for row in rows)
165
+ left = max(0, invoiced[key] - credited[key])
166
+ if at_original > left + EPSILON:
167
+ for row in rows:
168
+ row['rate'] = flt(row.get('rate')) * left / at_original
119
169
  return result
120
170
 
121
171
 
@@ -123,6 +173,8 @@ def validate_order_quantities(doc, *, cancelling=False):
123
173
  rule = ORDER_REFERENCES.get(doc.DOCTYPE)
124
174
  if not rule:
125
175
  return
176
+ if flt(doc.get('amount_only')):
177
+ return # money only: order quantities are untouched
126
178
  order_type, _, line_field, _ = rule
127
179
  quantities = defaultdict(float)
128
180
  for row in doc.get('items'):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: lambda-erp
3
- Version: 1.4.2
3
+ Version: 1.4.4
4
4
  Summary: Core ERP logic - accounting, sales, purchasing, inventory
5
5
  Author: TORUS INVESTMENTS AG
6
6
  License-Expression: Apache-2.0
@@ -2,7 +2,7 @@ api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
2
  api/attachments.py,sha256=SOIBZz1_aj7HUXOpkDLYnwXhQoud62fLohS4_G9WhHA,21266
3
3
  api/auth.py,sha256=xQZ9bq_2yAK0iPhx5p00nA5rt88WcxkAE25OniN4qKM,45203
4
4
  api/bootstrap.py,sha256=SZc6zVXkS4l4OHDfwAOsuI0SfP-bLL5EeADJm-RZBb0,21529
5
- api/chat.py,sha256=oLaDsQTP_JmWCBunhsDBaME3H0kYxGMJ1_5cYu_Pb8g,255058
5
+ api/chat.py,sha256=MaH8AKMqjxtMa2rZzJE4S9jaf4hJxTlpidcZqA1cNuI,255594
6
6
  api/chat_links.py,sha256=eHuGxuMvWh42-UC3i97GVxV04NemXGMQDUhfoKiLO-A,2344
7
7
  api/demo_limits.py,sha256=b5PSNWgPIRuIVsAcJZyGLCivUv4RorEzJlZXf5LNwh0,14191
8
8
  api/deps.py,sha256=HaFNz0q0NlX49kNMs1xMe0rrO6Slqpt8-TlPOATirT4,140
@@ -53,7 +53,7 @@ api/templates/proposal.html,sha256=NKZ6jPZP-WOkkOXfYPIs65AHC72xm8t2lUXd_z_-i4I,5
53
53
  api/templates/record.html,sha256=aPCWz4uB1ZBEf8KTFHeChMAbWgObEvx3VuhV1aC4x7A,34
54
54
  api/templates/reservation.html,sha256=_FCwWgq-rB75MG-pMsk6AeIkXCU97MzsshQZn9Hc4Zc,7248
55
55
  lambda_erp/__init__.py,sha256=ahOPqWyRzyy70oKnhA95TZnOWOCSaOZIjGSQ-qLojro,1088
56
- lambda_erp/database.py,sha256=rLGH3ZbJSg-nm9aNyDFUqeLqu_WVpUEbiVvfSybat1I,143755
56
+ lambda_erp/database.py,sha256=bymBiyzRXuuy3h4tfL89NWkD1VhmxSNhj5bhCTbiTeo,144241
57
57
  lambda_erp/exceptions.py,sha256=ml-iuIefPDTNKqsOJCbdipstaAEKK5re9djIG-UFDxw,516
58
58
  lambda_erp/hooks.py,sha256=koA8a_kNGVIknIhDWjqaq_LI0OYS9Tjt3JT08O5XJcc,1369
59
59
  lambda_erp/master_integrity.py,sha256=xGonkRsJZn92CrBcj8oFBnNnzIncIR1C3fuTOM3UrOw,1191
@@ -61,8 +61,8 @@ lambda_erp/model.py,sha256=S4XKCXcih8P31ESOhPW_nquaBZcEWz96Ml76NdNk4D8,25146
61
61
  lambda_erp/simulation.py,sha256=iwuTpNvZ35woeE-utveNgWSyDhlE2MK3Id_TTuNTNxg,27554
62
62
  lambda_erp/timestamps.py,sha256=iEOvJCOPoQ0YjbLv5CV2fEH7e002h2caWuYD2ko5Q9I,3067
63
63
  lambda_erp/utils.py,sha256=VKXhpsiWIAKc_Kf1aCDnwmnrmMIsK5egHuB2zrddfVo,4404
64
- lambda_erp/validation.py,sha256=45SKxyhggbush7mR3l-CtvInyLmaMnISFmFavVry77I,9844
65
- lambda_erp/workflow.py,sha256=LMkjWXSrTywl9fo1knIUOsmrTmgkmTJsrfQqPYTqYxA,12732
64
+ lambda_erp/validation.py,sha256=f5BR2xq1m6dgAxNBErDhNON0rHd2AVJjr843X7WQrew,10245
65
+ lambda_erp/workflow.py,sha256=Uwi3cY-Dh5Gae6a_VdI5vbJJ6FUdPclWWNA2a8kYeXE,15393
66
66
  lambda_erp/accounting/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
67
67
  lambda_erp/accounting/bank_account.py,sha256=3zwf2thIlB_JAFuaaK2EjhFtfZv-R2JJ3oklplM9Ab0,2862
68
68
  lambda_erp/accounting/bank_reconciliation.py,sha256=8YoVFV44AkEYEKix1NXhzO_r4RtfvS6CqfRedx6bpTA,38804
@@ -75,9 +75,9 @@ lambda_erp/accounting/general_ledger.py,sha256=ySlaYYUS-hIqOVRZaBl_3t8VFp4E9Ua66
75
75
  lambda_erp/accounting/journal_entry.py,sha256=pA6gD5penIO__0L4PMM30J6i3O7Bj6WmEwOqgf6uLZ0,12918
76
76
  lambda_erp/accounting/payment_entry.py,sha256=_-7q-aiq1Ky7PmtIAi6n8ou608zudHCJCGOSQDjaE4s,26504
77
77
  lambda_erp/accounting/pos_invoice.py,sha256=RKuu3Dt8gAACIMbV0GFeY2YQoWj1DYlveHN7bkvJclg,13676
78
- lambda_erp/accounting/purchase_invoice.py,sha256=zYH9P26bqOQEVXV64Ieq9nQ9UpFO2Edfe6ytdYGJKbY,19802
78
+ lambda_erp/accounting/purchase_invoice.py,sha256=I9-_gMdWebaWrrTCHn_lBvHoGhwxki6ZQ9tvDiBwGt4,20701
79
79
  lambda_erp/accounting/revaluation.py,sha256=40OF8ngnMp6eCYa3R0262B3WvAaxnyeEWTtrgzFOtfE,8862
80
- lambda_erp/accounting/sales_invoice.py,sha256=AXgprmdqFKYy5g7YWOpCe7aEi6ir_zoicfxlHXZP3_g,19615
80
+ lambda_erp/accounting/sales_invoice.py,sha256=T-GhpgWTDu68paj1EiY1SZ8-O2LKYFPexXupDriy34E,19705
81
81
  lambda_erp/accounting/settlement.py,sha256=ej43n59qORcKJZTLOmnqg6QsiiMKxSqLPh7cVIZxeqw,3033
82
82
  lambda_erp/accounting/subscription.py,sha256=Xzk2465D-pp8-fKp73pF96L600KBP_qXjEJg54ncSIM,8585
83
83
  lambda_erp/accounting/setup/__init__.py,sha256=-ROSd6ZHTPScYkwbnGIXVBXl-8UH361WwcpWVvXmSHw,2395
@@ -113,7 +113,7 @@ lambda_erp/stock/delivery_note.py,sha256=YITKHPz2od9FItWWOOy-EgHPbZEhuFz-Yr6EgdX
113
113
  lambda_erp/stock/purchase_receipt.py,sha256=8JZjzdH1FHHlgbflSnVfQStjzF2LKGa4O5Us6oRfr9w,11815
114
114
  lambda_erp/stock/stock_entry.py,sha256=zfIob3CBGArnvcuOa3-529Ya873fCEFnVVRiPMjRUdU,12083
115
115
  lambda_erp/stock/stock_ledger.py,sha256=Rl97Q8lFAXd7TnB-eqH8XPWwqBT_p_q8vnDGnZkF3SE,15572
116
- lambda_erp-1.4.2.dist-info/METADATA,sha256=mDT_vPJuRbSAgL1H2URK2cHwDwex6314wdpF0jh0iE4,32538
117
- lambda_erp-1.4.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
118
- lambda_erp-1.4.2.dist-info/licenses/LICENSE,sha256=8H08P22jiM0mJ97SgnpYchU0NeaPunGxZc3IqEaLgtc,11394
119
- lambda_erp-1.4.2.dist-info/RECORD,,
116
+ lambda_erp-1.4.4.dist-info/METADATA,sha256=_Ht8jj7shj_zBZHhnobL9FRWfSAI1XDX57JlqBJCYCo,32538
117
+ lambda_erp-1.4.4.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
118
+ lambda_erp-1.4.4.dist-info/licenses/LICENSE,sha256=8H08P22jiM0mJ97SgnpYchU0NeaPunGxZc3IqEaLgtc,11394
119
+ lambda_erp-1.4.4.dist-info/RECORD,,