This repository has been archived by the owner on Dec 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpurchase.py
2095 lines (1872 loc) · 76.2 KB
/
purchase.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import datetime
from collections import defaultdict
from decimal import Decimal
from itertools import chain, groupby
from sql import Literal, Null
from sql.aggregate import Count
from sql.functions import CharLength
from sql.operators import Concat
from trytond import backend
from trytond.i18n import gettext
from trytond.ir.attachment import AttachmentCopyMixin
from trytond.ir.note import NoteCopyMixin
from trytond.model import (
Index, Model, ModelSQL, ModelView, Unique, Workflow, fields,
sequence_ordered)
from trytond.model.exceptions import AccessError
from trytond.modules.account.tax import TaxableMixin
from trytond.modules.account_product.exceptions import AccountError
from trytond.modules.company import CompanyReport
from trytond.modules.company.model import (
employee_field, reset_employee, set_employee)
from trytond.modules.currency.fields import Monetary
from trytond.modules.product import price_digits, round_price
from trytond.pool import Pool
from trytond.pyson import Bool, Eval, If, PYSONEncoder
from trytond.tools import firstline
from trytond.transaction import Transaction
from trytond.wizard import (
Button, StateAction, StateTransition, StateView, Wizard)
from .exceptions import PartyLocationError, PurchaseQuotationError
def get_shipments_returns(model_name):
"Computes the returns or shipments"
def method(self, name):
Model = Pool().get(model_name)
shipments = set()
for line in self.lines:
for move in line.moves:
if isinstance(move.shipment, Model):
shipments.add(move.shipment.id)
return list(shipments)
return method
def search_shipments_returns(model_name):
"Search on shipments or returns"
def method(self, name, clause):
_, operator, operand, *extra = clause
nested = clause[0][len(name):]
if not nested:
if isinstance(clause[2], str):
nested = '.rec_name'
else:
nested = '.id'
return [('lines.moves.shipment' + nested,
operator, operand, model_name, *extra)]
return classmethod(method)
class Purchase(
Workflow, ModelSQL, ModelView, TaxableMixin,
AttachmentCopyMixin, NoteCopyMixin):
'Purchase'
__name__ = 'purchase.purchase'
_rec_name = 'number'
_states = {
'readonly': Eval('state') != 'draft',
}
company = fields.Many2One(
'company.company', "Company", required=True,
states={
'readonly': (
(Eval('state') != 'draft')
| Eval('lines', [0])
| Eval('party', True)
| Eval('invoice_party', True)),
})
number = fields.Char("Number", readonly=True)
reference = fields.Char("Reference")
description = fields.Char('Description', size=None, states=_states)
purchase_date = fields.Date('Purchase Date',
states={
'readonly': ~Eval('state').in_(['draft', 'quotation']),
'required': ~Eval('state').in_(
['draft', 'quotation', 'cancelled']),
})
payment_term = fields.Many2One('account.invoice.payment_term',
'Payment Term', states={
'readonly': ~Eval('state').in_(['draft', 'quotation']),
})
party = fields.Many2One('party.party', 'Party', required=True,
states={
'readonly': ((Eval('state') != 'draft')
| (Eval('lines', [0]) & Eval('party'))),
},
context={
'company': Eval('company', -1),
},
depends={'company'})
party_lang = fields.Function(fields.Char('Party Language'),
'on_change_with_party_lang')
contact = fields.Many2One(
'party.contact_mechanism', "Contact",
context={
'company': Eval('company', -1),
},
search_context={
'related_party': Eval('party'),
},
depends={'company'})
invoice_party = fields.Many2One('party.party', "Invoice Party",
states={
'readonly': ((Eval('state') != 'draft')
| Eval('lines', [0])),
},
context={
'company': Eval('company', -1),
},
search_context={
'related_party': Eval('party'),
},
depends={'company'})
invoice_address = fields.Many2One('party.address', 'Invoice Address',
domain=[
('party', '=', If(Bool(Eval('invoice_party')),
Eval('invoice_party'), Eval('party'))),
],
states={
'readonly': Eval('state') != 'draft',
'required': ~Eval('state').in_(
['draft', 'quotation', 'cancelled']),
})
warehouse = fields.Many2One('stock.location', 'Warehouse',
domain=[('type', '=', 'warehouse')], states=_states)
currency = fields.Many2One('currency.currency', 'Currency', required=True,
states={
'readonly': ((Eval('state') != 'draft')
| (Eval('lines', [0]) & Eval('currency'))),
})
lines = fields.One2Many('purchase.line', 'purchase', 'Lines',
states=_states)
comment = fields.Text('Comment')
untaxed_amount = fields.Function(Monetary(
"Untaxed", currency='currency', digits='currency'),
'get_amount')
untaxed_amount_cache = Monetary(
"Untaxed Cache", currency='currency', digits='currency')
tax_amount = fields.Function(Monetary(
"Tax", currency='currency', digits='currency'),
'get_amount')
tax_amount_cache = Monetary(
"Tax Cache", currency='currency', digits='currency')
total_amount = fields.Function(Monetary(
"Total", currency='currency', digits='currency'),
'get_amount')
total_amount_cache = Monetary(
"Total Cache", currency='currency', digits='currency')
invoice_method = fields.Selection([
('manual', 'Manual'),
('order', 'Based On Order'),
('shipment', 'Based On Shipment'),
], 'Invoice Method', required=True, states=_states)
invoice_state = fields.Selection([
('none', 'None'),
('waiting', 'Waiting'),
('paid', 'Paid'),
('exception', 'Exception'),
], 'Invoice State', readonly=True, required=True, sort=False)
invoices = fields.Function(fields.Many2Many(
'account.invoice', None, None, "Invoices"),
'get_invoices', searcher='search_invoices')
invoices_ignored = fields.Many2Many(
'purchase.purchase-ignored-account.invoice',
'purchase', 'invoice', 'Ignored Invoices', readonly=True)
invoices_recreated = fields.Many2Many(
'purchase.purchase-recreated-account.invoice',
'purchase', 'invoice', 'Recreated Invoices', readonly=True)
origin = fields.Reference(
"Origin", selection='get_origin',
states={
'readonly': Eval('state') != 'draft',
})
delivery_date = fields.Date(
"Delivery Date",
states={
'readonly': Eval('state').in_([
'processing', 'done', 'cancelled']),
},
help="The default delivery date for each line.")
shipment_state = fields.Selection([
('none', 'None'),
('waiting', 'Waiting'),
('received', 'Received'),
('exception', 'Exception'),
], 'Shipment State', readonly=True, required=True, sort=False)
shipments = fields.Function(fields.Many2Many(
'stock.shipment.in', None, None, "Shipments"),
'get_shipments', searcher='search_shipments')
shipment_returns = fields.Function(fields.Many2Many(
'stock.shipment.in.return', None, None, "Shipment Returns"),
'get_shipment_returns', searcher='search_shipment_returns')
moves = fields.Function(
fields.Many2Many('stock.move', None, None, "Moves"),
'get_moves', searcher='search_moves')
quoted_by = employee_field(
"Quoted By",
states=['quotation', 'confirmed', 'processing', 'done', 'cancelled'])
confirmed_by = employee_field(
"Confirmed By",
states=['confirmed', 'processing', 'done', 'cancelled'])
state = fields.Selection([
('draft', "Draft"),
('quotation', "Quotation"),
('confirmed', "Confirmed"),
('processing', "Processing"),
('done', "Done"),
('cancelled', "Cancelled"),
], "State", readonly=True, required=True, sort=False)
del _states
@classmethod
def __setup__(cls):
cls.number.search_unaccented = False
cls.reference.search_unaccented = False
super(Purchase, cls).__setup__()
t = cls.__table__()
cls._sql_indexes.update({
Index(t, (t.reference, Index.Similarity())),
Index(t, (t.party, Index.Equality())),
Index(
t,
(t.state, Index.Equality()),
where=t.state.in_([
'draft', 'quotation', 'confirmed', 'processing'])),
Index(
t,
(t.invoice_state, Index.Equality()),
where=t.state.in_(['none', 'waiting', 'exception'])),
Index(
t,
(t.shipment_state, Index.Equality()),
where=t.state.in_(['none', 'waiting', 'exception'])),
})
cls._order = [
('purchase_date', 'DESC NULLS FIRST'),
('id', 'DESC'),
]
cls._transitions |= set((
('draft', 'quotation'),
('quotation', 'confirmed'),
('confirmed', 'processing'),
('confirmed', 'draft'),
('processing', 'processing'),
('processing', 'done'),
('done', 'processing'),
('draft', 'cancelled'),
('quotation', 'cancelled'),
('quotation', 'draft'),
('cancelled', 'draft'),
))
cls._buttons.update({
'cancel': {
'invisible': ~Eval('state').in_(['draft', 'quotation']),
'depends': ['state'],
},
'draft': {
'invisible': ~Eval('state').in_(
['cancelled', 'quotation', 'confirmed']),
'icon': If(Eval('state') == 'cancelled', 'tryton-undo',
'tryton-back'),
'depends': ['state'],
},
'quote': {
'pre_validate': [
If(~Eval('purchase_date'),
('purchase_date', '!=', None),
()),
If(~Eval('invoice_address'),
('invoice_address', '!=', None),
()),
],
'invisible': Eval('state') != 'draft',
'readonly': ~Eval('lines', Eval('untaxed_amount', 0)),
'depends': ['state'],
},
'confirm': {
'invisible': Eval('state') != 'quotation',
'depends': ['state'],
},
'process': {
'invisible': ~Eval('state').in_(
['confirmed', 'processing']),
'icon': If(Eval('state') == 'confirmed',
'tryton-forward', 'tryton-refresh'),
'depends': ['state'],
},
'handle_invoice_exception': {
'invisible': ((Eval('invoice_state') != 'exception')
| (Eval('state') == 'cancelled')),
'depends': ['state', 'invoice_state'],
},
'handle_shipment_exception': {
'invisible': ((Eval('shipment_state') != 'exception')
| (Eval('state') == 'cancelled')),
'depends': ['state', 'shipment_state'],
},
'modify_header': {
'invisible': ((Eval('state') != 'draft')
| ~Eval('lines', [-1])),
'depends': ['state'],
},
})
# The states where amounts are cached
cls._states_cached = ['confirmed', 'done', 'cancelled']
@classmethod
def __register__(cls, module_name):
pool = Pool()
PurchaseLine = pool.get('purchase.line')
Move = pool.get('stock.move')
InvoiceLine = pool.get('account.invoice.line')
cursor = Transaction().connection.cursor()
sql_table = cls.__table__()
table = cls.__table_handler__(module_name)
# Migration from 3.8:
if table.column_exist('supplier_reference'):
table.column_rename('reference', 'number')
table.column_rename('supplier_reference', 'reference')
super(Purchase, cls).__register__(module_name)
table = cls.__table_handler__(module_name)
# Migration from 3.2
# state confirmed splitted into confirmed and processing
if (backend.TableHandler.table_exist(PurchaseLine._table)
and backend.TableHandler.table_exist(Move._table)
and backend.TableHandler.table_exist(InvoiceLine._table)):
purchase_line = PurchaseLine.__table__()
move = Move.__table__()
invoice_line = InvoiceLine.__table__()
# Wrap subquery inside an other inner subquery because MySQL syntax
# doesn't allow update a table and select from the same table in a
# subquery.
sub_query = sql_table.join(purchase_line,
condition=purchase_line.purchase == sql_table.id
).join(invoice_line, 'LEFT',
condition=(invoice_line.origin
== Concat(
PurchaseLine.__name__ + ',', purchase_line.id))
).join(move, 'LEFT',
condition=(move.origin == Concat(
PurchaseLine.__name__ + ',', purchase_line.id))
).select(sql_table.id,
where=((sql_table.state == 'confirmed')
& ((invoice_line.id != Null)
| (move.id != Null))))
cursor.execute(*sql_table.update(
columns=[sql_table.state],
values=['processing'],
where=sql_table.id.in_(sub_query.select(sub_query.id))))
# Migration from 5.6: rename state cancel to cancelled
cursor.execute(*sql_table.update(
[sql_table.state], ['cancelled'],
where=sql_table.state == 'cancel'))
@classmethod
def order_number(cls, tables):
table, _ = tables[None]
return [CharLength(table.number), table.number]
@classmethod
def default_warehouse(cls):
Location = Pool().get('stock.location')
return Location.get_default_warehouse()
@staticmethod
def default_company():
return Transaction().context.get('company')
@fields.depends('company')
def on_change_company(self):
self.invoice_method = self.default_invoice_method(
company=self.company.id if self.company else None)
@staticmethod
def default_state():
return 'draft'
@classmethod
def default_currency(cls, **pattern):
pool = Pool()
Company = pool.get('company.company')
company = pattern.get('company')
if not company:
company = cls.default_company()
if company:
return Company(company).currency.id
@classmethod
def default_invoice_method(cls, **pattern):
Configuration = Pool().get('purchase.configuration')
configuration = Configuration(1)
return configuration.get_multivalue(
'purchase_invoice_method', **pattern)
@staticmethod
def default_invoice_state():
return 'none'
@staticmethod
def default_shipment_state():
return 'none'
@fields.depends(
'company', 'party', 'invoice_party', 'payment_term', 'lines')
def on_change_party(self):
cursor = Transaction().connection.cursor()
table = self.__table__()
if not self.invoice_party:
self.invoice_address = None
self.invoice_method = self.default_invoice_method(
company=self.company.id if self.company else None)
if not self.lines:
self.currency = self.default_currency(
company=self.company.id if self.company else None)
if self.party:
if not self.invoice_party:
self.invoice_address = self.party.address_get(type='invoice')
if not self.lines:
invoice_party = (
self.invoice_party.id if self.invoice_party else None)
subquery = table.select(
table.currency,
table.payment_term,
table.invoice_method,
where=(table.party == self.party.id)
& (table.invoice_party == invoice_party),
order_by=table.id,
limit=10)
cursor.execute(*subquery.select(
subquery.currency,
subquery.payment_term,
subquery.invoice_method,
group_by=[
subquery.currency,
subquery.payment_term,
subquery.invoice_method,
],
order_by=Count(Literal(1)).desc))
row = cursor.fetchone()
if row:
self.currency, self.payment_term, self.invoice_method = row
if self.party.supplier_currency:
self.currency = self.party.supplier_currency
if self.party.supplier_payment_term:
self.payment_term = self.party.supplier_payment_term
else:
self.payment_term = None
@fields.depends('party', 'invoice_party')
def on_change_invoice_party(self):
if self.invoice_party:
self.invoice_address = self.invoice_party.address_get(
type='invoice')
elif self.party:
self.invoice_address = self.party.address_get(type='invoice')
@fields.depends('party')
def on_change_with_party_lang(self, name=None):
Config = Pool().get('ir.configuration')
if self.party:
if self.party.lang:
return self.party.lang.code
return Config.get_language()
@fields.depends('party', 'company')
def _get_tax_context(self):
context = {}
if self.party and self.party.lang:
context['language'] = self.party.lang.code
if self.company:
context['company'] = self.company.id
return context
@fields.depends('lines', 'currency', methods=['get_tax_amount'])
def on_change_lines(self):
self.untaxed_amount = Decimal('0.0')
self.tax_amount = Decimal('0.0')
self.total_amount = Decimal('0.0')
if self.lines:
for line in self.lines:
self.untaxed_amount += getattr(line, 'amount', None) or 0
self.tax_amount = self.get_tax_amount()
if self.currency:
self.untaxed_amount = self.currency.round(self.untaxed_amount)
self.tax_amount = self.currency.round(self.tax_amount)
self.total_amount = self.untaxed_amount + self.tax_amount
if self.currency:
self.total_amount = self.currency.round(self.total_amount)
@property
def taxable_lines(self):
taxable_lines = []
# In case we're called from an on_change we have to use some sensible
# defaults
for line in self.lines:
if getattr(line, 'type', None) != 'line':
continue
taxable_lines.append((
getattr(line, 'taxes', None) or [],
getattr(line, 'unit_price', None) or Decimal(0),
getattr(line, 'quantity', None) or 0,
None,
))
return taxable_lines
@fields.depends(methods=['_get_taxes'])
def get_tax_amount(self):
taxes = iter(self._get_taxes().values())
return sum((tax['amount'] for tax in taxes), Decimal(0))
@classmethod
def get_amount(cls, purchases, names):
untaxed_amount = {}
tax_amount = {}
total_amount = {}
if {'tax_amount', 'total_amount'} & set(names):
compute_taxes = True
else:
compute_taxes = False
# Sort cached first and re-instanciate to optimize cache management
purchases = sorted(purchases,
key=lambda p: p.state in cls._states_cached, reverse=True)
purchases = cls.browse(purchases)
for purchase in purchases:
if (purchase.state in cls._states_cached
and purchase.untaxed_amount_cache is not None
and purchase.tax_amount_cache is not None
and purchase.total_amount_cache is not None):
untaxed_amount[purchase.id] = purchase.untaxed_amount_cache
if compute_taxes:
tax_amount[purchase.id] = purchase.tax_amount_cache
total_amount[purchase.id] = purchase.total_amount_cache
else:
untaxed_amount[purchase.id] = sum(
(line.amount for line in purchase.lines
if line.type == 'line'), Decimal(0))
if compute_taxes:
tax_amount[purchase.id] = purchase.get_tax_amount()
total_amount[purchase.id] = (
untaxed_amount[purchase.id] + tax_amount[purchase.id])
result = {
'untaxed_amount': untaxed_amount,
'tax_amount': tax_amount,
'total_amount': total_amount,
}
for key in list(result.keys()):
if key not in names:
del result[key]
return result
def get_invoices(self, name):
invoices = set()
for line in self.lines:
for invoice_line in line.invoice_lines:
if invoice_line.invoice:
invoices.add(invoice_line.invoice.id)
return list(invoices)
@classmethod
def search_invoices(cls, name, clause):
return [('lines.invoice_lines.invoice' + clause[0].lstrip(name),)
+ tuple(clause[1:])]
def get_invoice_state(self):
'''
Return the invoice state for the purchase.
'''
skip_ids = set(x.id for x in self.invoices_ignored)
skip_ids.update(x.id for x in self.invoices_recreated)
invoices = [i for i in self.invoices if i.id not in skip_ids]
if invoices:
if any(i.state == 'cancelled' for i in invoices):
return 'exception'
elif all(i.state == 'paid' for i in invoices):
return 'paid'
else:
return 'waiting'
return 'none'
get_shipments = get_shipments_returns('stock.shipment.in')
get_shipment_returns = get_shipments_returns('stock.shipment.in.return')
search_shipments = search_shipments_returns('stock.shipment.in')
search_shipment_returns = search_shipments_returns(
'stock.shipment.in.return')
def get_shipment_state(self):
'''
Return the shipment state for the purchase.
'''
if self.moves:
if any(l.move_exception for l in self.lines):
return 'exception'
elif all(l.move_done for l in self.lines):
return 'received'
else:
return 'waiting'
return 'none'
def get_moves(self, name):
return [m.id for l in self.lines for m in l.moves]
@classmethod
def search_moves(cls, name, clause):
return [('lines.' + clause[0],) + tuple(clause[1:])]
@classmethod
def _get_origin(cls):
"Return list of Model names for origin Reference"
return ['purchase.purchase']
@classmethod
def get_origin(cls):
Model = Pool().get('ir.model')
get_name = Model.get_name
models = cls._get_origin()
return [(None, '')] + [(m, get_name(m)) for m in models]
@property
def report_address(self):
if self.invoice_address:
return self.invoice_address.full_address
else:
return ''
@property
def delivery_full_address(self):
if self.warehouse and self.warehouse.address:
return self.warehouse.address.full_address
return ''
@property
def full_number(self):
return self.number
def get_rec_name(self, name):
items = []
if self.number:
items.append(self.full_number)
if self.reference:
items.append('[%s]' % self.reference)
if not items:
items.append('(%s)' % self.id)
return ' '.join(items)
@classmethod
def search_rec_name(cls, name, clause):
_, operator, value = clause
if operator.startswith('!') or operator.startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
domain = [bool_op,
('number', operator, value),
('reference', operator, value),
]
return domain
@classmethod
def view_attributes(cls):
attributes = super().view_attributes() + [
('/form//field[@name="comment"]', 'spell', Eval('party_lang')),
('/tree', 'visual', If(Eval('state') == 'cancelled', 'muted', '')),
('/tree/field[@name="invoice_state"]', 'visual',
If(Eval('invoice_state') == 'exception', 'danger', '')),
('/tree/field[@name="shipment_state"]', 'visual',
If(Eval('shipment_state') == 'exception', 'danger', '')),
]
if Transaction().context.get('modify_header'):
attributes.extend([
('//group[@id="states"]', 'states', {'invisible': True}),
('//group[@id="amount"]', 'states', {'invisible': True}),
('//group[@id="links"]', 'states', {'invisible': True}),
('//group[@id="buttons"]', 'states', {'invisible': True}),
])
return attributes
@classmethod
def get_resources_to_copy(cls, name):
return {
'stock.shipment.in.return',
'account.invoice',
}
@classmethod
def copy(cls, purchases, default=None):
if default is None:
default = {}
else:
default = default.copy()
default.setdefault('number', None)
default.setdefault('invoice_state', 'none')
default.setdefault('invoices_ignored', None)
default.setdefault('shipment_state', 'none')
default.setdefault('purchase_date', None)
default.setdefault('quoted_by')
default.setdefault('confirmed_by')
return super(Purchase, cls).copy(purchases, default=default)
def check_for_quotation(self):
for line in self.lines:
if (not line.to_location
and line.product
and line.product.type in line.get_move_product_types()):
raise PurchaseQuotationError(
gettext('purchase.msg_warehouse_required_for_quotation',
purchase=self.rec_name))
@classmethod
def set_number(cls, purchases):
'''
Fill the number field with the purchase sequence
'''
pool = Pool()
Config = pool.get('purchase.configuration')
config = Config(1)
for purchase in purchases:
if purchase.number:
continue
purchase.number = config.get_multivalue(
'purchase_sequence', company=purchase.company.id).get()
cls.save(purchases)
@classmethod
def set_purchase_date(cls, purchases):
Date = Pool().get('ir.date')
for company, purchases in groupby(purchases, key=lambda p: p.company):
with Transaction().set_context(company=company.id):
today = Date.today()
cls.write([p for p in purchases if not p.purchase_date], {
'purchase_date': today,
})
@classmethod
def store_cache(cls, purchases):
for purchase in purchases:
purchase.untaxed_amount_cache = purchase.untaxed_amount
purchase.tax_amount_cache = purchase.tax_amount
purchase.total_amount_cache = purchase.total_amount
cls.save(purchases)
def _get_invoice_purchase(self):
'Return invoice'
pool = Pool()
Journal = pool.get('account.journal')
Invoice = pool.get('account.invoice')
journals = Journal.search([
('type', '=', 'expense'),
], limit=1)
if journals:
journal, = journals
else:
journal = None
party = self.invoice_party or self.party
return Invoice(
company=self.company,
type='in',
journal=journal,
party=party,
invoice_address=self.invoice_address,
currency=self.currency,
account=party.account_payable_used,
payment_term=self.payment_term,
)
def create_invoice(self):
'Create an invoice for the purchase and return it'
if self.invoice_method == 'manual':
return
invoice_lines = []
for line in self.lines:
invoice_lines.append(line.get_invoice_line())
invoice_lines = list(chain(*invoice_lines))
if not invoice_lines:
return
invoice = self._get_invoice_purchase()
if getattr(invoice, 'lines', None):
invoice_lines = list(invoice.lines) + invoice_lines
invoice.lines = invoice_lines
return invoice
def create_move(self, move_type):
'''
Create move for each purchase lines
'''
pool = Pool()
Move = pool.get('stock.move')
moves = []
for line in self.lines:
move = line.get_move(move_type)
if move:
moves.append(move)
Move.save(moves)
return moves
@property
def return_from_location(self):
if self.warehouse:
return (self.warehouse.supplier_return_location
or self.warehouse.storage_location)
def _get_return_shipment(self):
ShipmentInReturn = Pool().get('stock.shipment.in.return')
return ShipmentInReturn(
company=self.company,
from_location=self.return_from_location,
to_location=self.party.supplier_location,
supplier=self.party,
delivery_address=self.party.address_get(type='delivery'),
)
def create_return_shipment(self, return_moves):
'''
Create return shipment and return the shipment id
'''
return_shipment = self._get_return_shipment()
return_shipment.moves = return_moves
return return_shipment
def is_done(self):
return ((self.invoice_state == 'paid'
or self.invoice_state == 'none')
and (self.shipment_state == 'received'
or self.shipment_state == 'none'
or all(l.product.type == 'service'
for l in self.lines if l.product)))
@classmethod
def delete(cls, purchases):
# Cancel before delete
cls.cancel(purchases)
for purchase in purchases:
if purchase.state != 'cancelled':
raise AccessError(
gettext('purchase.msg_purchase_delete_cancel',
purchase=purchase.rec_name))
super(Purchase, cls).delete(purchases)
@classmethod
@ModelView.button
@Workflow.transition('cancelled')
def cancel(cls, purchases):
cls.store_cache(purchases)
@classmethod
@ModelView.button
@Workflow.transition('draft')
@reset_employee('quoted_by', 'confirmed_by')
def draft(cls, purchases):
pass
@classmethod
@ModelView.button
@Workflow.transition('quotation')
@set_employee('quoted_by')
def quote(cls, purchases):
for purchase in purchases:
purchase.check_for_quotation()
cls.set_number(purchases)
@classmethod
@ModelView.button
@Workflow.transition('confirmed')
@set_employee('confirmed_by')
def confirm(cls, purchases):
pool = Pool()
Configuration = pool.get('purchase.configuration')
transaction = Transaction()
context = transaction.context
cls.set_purchase_date(purchases)
cls.store_cache(purchases)
config = Configuration(1)
with transaction.set_context(
queue_scheduled_at=config.purchase_process_after,
queue_batch=context.get('queue_batch', True)):
cls.__queue__.process(purchases)
@classmethod
@Workflow.transition('processing')
def proceed(cls, purchases):
pass
@classmethod
@Workflow.transition('done')
def do(cls, purchases):
pass
@classmethod
@ModelView.button_action('purchase.wizard_invoice_handle_exception')
def handle_invoice_exception(cls, purchases):
pass
@classmethod
@ModelView.button_action('purchase.wizard_shipment_handle_exception')
def handle_shipment_exception(cls, purchases):
pass
@classmethod
@ModelView.button
def process(cls, purchases):
states = {'confirmed', 'processing', 'done'}
purchases = [p for p in purchases if p.state in states]
cls.lock(purchases)
cls._process_invoice(purchases)
cls._process_shipment(purchases)
cls._process_invoice_shipment_states(purchases)
cls._process_state(purchases)
@classmethod
def _process_invoice(cls, purchases):
invoices = {}
for purchase in purchases:
invoice = purchase.create_invoice()
if invoice:
invoices[purchase] = invoice
cls._save_invoice(invoices)
@classmethod
def _save_invoice(cls, invoices):
pool = Pool()
Invoice = pool.get('account.invoice')
Invoice.save(invoices.values())
Invoice.update_taxes(invoices.values())
for purchase, invoice in invoices.items():
purchase.copy_resources_to(invoice)
@classmethod
def _process_shipment(cls, purchases):
pool = Pool()
Move = pool.get('stock.move')
ShipmentInReturn = pool.get('stock.shipment.in.return')
moves, shipments_return = [], {}
for purchase in purchases:
moves.extend(purchase.create_move('in'))
return_moves = purchase.create_move('return')
if return_moves:
shipments_return[purchase] = purchase.create_return_shipment(
return_moves)
Move.save(moves)
ShipmentInReturn.save(shipments_return.values())
ShipmentInReturn.wait(shipments_return.values())
for purchase, shipment in shipments_return.items():
purchase.copy_resources_to(shipment)
@classmethod
def _process_invoice_shipment_states(cls, purchases):
pool = Pool()
Line = pool.get('purchase.line')
lines = []
invoice_states, shipment_states = defaultdict(list), defaultdict(list)
for purchase in purchases:
invoice_state = purchase.get_invoice_state()
if purchase.invoice_state != invoice_state:
invoice_states[invoice_state].append(purchase)
shipment_state = purchase.get_shipment_state()
if purchase.shipment_state != shipment_state:
shipment_states[shipment_state].append(purchase)
for line in purchase.lines:
line.set_actual_quantity()
lines.append(line)