File: purchase.py

package info (click to toggle)
tryton-modules-purchase 7.0.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,716 kB
  • sloc: python: 3,709; xml: 1,737; makefile: 11; sh: 3
file content (2294 lines) | stat: -rw-r--r-- 85,020 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
# 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
import math
from collections import defaultdict
from decimal import Decimal
from itertools import chain, groupby

from sql import Literal
from sql.aggregate import Count
from sql.functions import CharLength

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
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, PurchaseMoveQuantity, PurchaseQuotationError)


def samesign(a, b):
    return math.copysign(a, b) == a


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", ondelete='RESTRICT',
        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={
            'readonly': (
                (Eval('state') != 'draft')
                | ~Eval('company')
                | ~Eval('currency')),
            })
    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'),
            ('pending', "Pending"),
            ('awaiting payment', "Awaiting Payment"),
            ('partially paid', "Partially Paid"),
            ('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'),
            ('partially shipped', 'Partially Shipped'),
            ('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': {
                    'invisible': Eval('state') != 'draft',
                    'readonly': ~Eval('lines', Eval('untaxed_amount', 0)),
                    'depends': ['state'],
                    },
                'confirm': {
                    'pre_validate': [
                        If(~Eval('invoice_address'),
                            ('invoice_address', '!=', None),
                            ()),
                        ],
                    'invisible': Eval('state') != 'quotation',
                    'depends': ['state'],
                    },
                'process': {
                    'invisible': ~Eval('state').in_(
                        ['confirmed', 'processing']),
                    'icon': If(Eval('state') == 'confirmed',
                        'tryton-forward', 'tryton-refresh'),
                    'depends': ['state'],
                    },
                'manual_invoice': {
                    'invisible': (
                        (Eval('invoice_method') != 'manual')
                        | ~Eval('state').in_(['processing', 'done'])),
                    'depends': ['invoice_method', '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):
        cursor = Transaction().connection.cursor()
        sql_table = cls.__table__()

        super(Purchase, cls).__register__(module_name)

        # Migration from 5.6: rename state cancel to cancelled
        cursor.execute(*sql_table.update(
                [sql_table.state], ['cancelled'],
                where=sql_table.state == 'cancel'))

        # Migration from 6.6: rename invoice state waiting to pending
        cursor.execute(*sql_table.update(
                [sql_table.invoice_state], ['pending'],
                where=sql_table.invoice_state == 'waiting'))

    @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 is not None and company >= 0:
            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.desc,
                    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)
        self.tax_amount = Decimal(0)
        self.total_amount = Decimal(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' and line.amount is not None),
                    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][len(name):],
                *clause[1:])]

    @property
    def _invoices_for_state(self):
        return self.invoices

    def get_invoice_state(self):
        '''
        Return the invoice state for the purchase.
        '''
        skips = set(self.invoices_ignored)
        skips.update(self.invoices_recreated)
        invoices = [i for i in self._invoices_for_state if i not in skips]

        def is_cancelled(invoice):
            return invoice.state == 'cancelled' and not invoice.cancel_move

        def is_paid(invoice):
            return (
                invoice.state == 'paid'
                or (invoice.state == 'cancelled' and invoice.cancel_move))
        if invoices:
            if any(is_cancelled(i) for i in invoices):
                return 'exception'
            elif all(is_paid(i) for i in invoices):
                return 'paid'
            elif any(is_paid(i) for i in invoices):
                return 'partially paid'
            elif any(i.state == 'posted' for i in invoices):
                return 'awaiting payment'
            else:
                return 'pending'
        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.moves_exception for l in self.lines):
                return 'exception'
            elif all(l.moves_progress >= 1 for l in self.lines
                    if l.moves_progress is not None):
                return 'received'
            elif any(l.moves_progress for l in self.lines):
                return 'partially shipped'
            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')
        default.setdefault('untaxed_amount_cache')
        default.setdefault('tax_amount_cache')
        default.setdefault('total_amount_cache')
        return super(Purchase, cls).copy(purchases, default=default)

    def check_for_quotation(self):
        for line in self.lines:
            if (line.quantity or 0) >= 0:
                location = line.to_location
            else:
                location = line.from_location
            if ((not location or not line.warehouse)
                    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()
        Invoice = pool.get('account.invoice')
        party = self.invoice_party or self.party
        invoice = Invoice(
            company=self.company,
            type='in',
            party=party,
            invoice_address=self.invoice_address,
            currency=self.currency,
            account=party.account_payable_used,
            payment_term=self.payment_term,
            )
        invoice.set_journal()
        return invoice

    def create_invoice(self):
        'Create an invoice for the purchase and return it'
        context = Transaction().context
        if (self.invoice_method == 'manual'
                and not context.get('_purchase_manual_invoice', False)):
            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.invoice_method != 'manual'))
            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):
        cls.write(purchases, {
                'tax_amount_cache': None,
                'untaxed_amount_cache': None,
                'total_amount_cache': None,
                })

    @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)

    @property
    def process_after(self):
        pool = Pool()
        Configuration = pool.get('purchase.configuration')
        config = Configuration(1)
        return config.purchase_process_after

    @classmethod
    @ModelView.button
    @Workflow.transition('confirmed')
    @set_employee('confirmed_by')
    def confirm(cls, purchases):
        pool = Pool()
        Line = pool.get('purchase.line')
        transaction = Transaction()
        context = transaction.context
        cls.set_purchase_date(purchases)

        cls.write(purchases, {'state': 'confirmed'})
        lines = list(sum((p.lines for p in purchases), ()))
        Line._validate(lines, ['unit_price'])

        cls.store_cache(purchases)
        for process_after, sub_purchases in groupby(
                purchases, lambda p: p.process_after):
            with transaction.set_context(
                    queue_scheduled_at=process_after,
                    queue_batch=context.get('queue_batch', True)):
                cls.__queue__.process(sub_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())
        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)

        for invoice_state, purchases in invoice_states.items():
            cls.write(purchases, {'invoice_state': invoice_state})
            cls.log(purchases, 'transition', f'invoice_state:{invoice_state}')
        for shipment_state, purchases in shipment_states.items():
            cls.write(purchases, {'shipment_state': shipment_state})
            cls.log(
                purchases, 'transition', f'shipment_state:{shipment_state}')
        Line.save(lines)

    @classmethod
    def _process_state(cls, purchases):
        process, done = [], []
        for purchase in purchases:
            if purchase.is_done():
                if purchase.state != 'done':
                    if purchase.state == 'confirmed':
                        process.append(purchase)
                    done.append(purchase)
            elif purchase.state != 'processing':
                process.append(purchase)
        if process:
            cls.proceed(process)
        if done:
            cls.do(done)

    @classmethod
    @ModelView.button
    def manual_invoice(cls, purchases):
        purchases = [p for p in purchases if p.invoice_method == 'manual']
        with Transaction().set_context(_purchase_manual_invoice=True):
            cls.process(purchases)

    @classmethod
    @ModelView.button_action('purchase.wizard_modify_header')
    def modify_header(cls, purchases):
        pass


class PurchaseIgnoredInvoice(ModelSQL):
    'Purchase - Ignored Invoice'
    __name__ = 'purchase.purchase-ignored-account.invoice'
    _table = 'purchase_invoice_ignored_rel'
    purchase = fields.Many2One(
        'purchase.purchase', "Purchase", ondelete='CASCADE', required=True)
    invoice = fields.Many2One(
        'account.invoice', "Invoice", ondelete='RESTRICT', required=True)


class PurchaseRecreatedInvoice(ModelSQL):
    'Purchase - Recreated Invoice'
    __name__ = 'purchase.purchase-recreated-account.invoice'
    _table = 'purchase_invoice_recreated_rel'
    purchase = fields.Many2One(
        'purchase.purchase', "Purchase", ondelete='CASCADE', required=True)
    invoice = fields.Many2One(
        'account.invoice', "Invoice", ondelete='RESTRICT', required=True)


class Line(sequence_ordered(), ModelSQL, ModelView):
    'Purchase Line'
    __name__ = 'purchase.line'
    purchase = fields.Many2One(
        'purchase.purchase', "Purchase", ondelete='CASCADE', required=True,
        states={
            'readonly': ((Eval('purchase_state') != 'draft')
                & Bool(Eval('purchase'))),
            })
    type = fields.Selection([
        ('line', 'Line'),
        ('subtotal', 'Subtotal'),
        ('title', 'Title'),
        ('comment', 'Comment'),
        ], "Type", required=True,
        states={
            'readonly': Eval('purchase_state') != 'draft',
            })
    quantity = fields.Float(
        "Quantity", digits='unit',
        domain=[
            If(Eval('type') != 'line',
                ('quantity', '=', None),
                ()),
            ],
        states={
            'invisible': Eval('type') != 'line',
            'required': Eval('type') == 'line',
            'readonly': Eval('purchase_state') != 'draft',
            })
    actual_quantity = fields.Float(
        "Actual Quantity", digits='unit', readonly=True,
        domain=[
            If(Eval('type') != 'line',
                ('actual_quantity', '=', None),
                ()),
            ],
        states={
            'invisible': ((Eval('type') != 'line') | ~Eval('actual_quantity')),
            })
    unit = fields.Many2One('product.uom', 'Unit',
        ondelete='RESTRICT',
        states={
            'required': Bool(Eval('product')),
            'invisible': Eval('type') != 'line',
            'readonly': Eval('purchase_state') != 'draft',
            },
        domain=[
            If(Bool(Eval('product_uom_category')),
                ('category', '=', Eval('product_uom_category')),
                ('category', '!=', -1)),
            If(Eval('type') != 'line',
                ('id', '=', None),
                ()),
            ])
    product = fields.Many2One('product.product', 'Product',
        ondelete='RESTRICT',
        domain=[
            If(Eval('purchase_state').in_(['draft', 'quotation'])
                & ~(Eval('quantity', 0) < 0),
                ('purchasable', '=', True),
                ()),
            If(Eval('type') != 'line',
                ('id', '=', None),
                ()),
            ],
        states={
            'invisible': Eval('type') != 'line',
            'readonly': Eval('purchase_state') != 'draft',
            'required': Bool(Eval('product_supplier')),
            },
        context={
            'company': Eval('company', None),
            },
        search_context={
            'locations': If(Bool(Eval('warehouse')),
                [Eval('warehouse', -1)], []),
            'stock_date_end': Eval('purchase_date', None),
            'stock_skip_warehouse': True,
            'currency': Eval('currency', -1),
            'supplier': Eval('supplier', -1),
            'purchase_date': Eval('purchase_date', None),
            'uom': Eval('unit'),
            'taxes': Eval('taxes', []),
            'quantity': Eval('quantity'),
            },
        depends={
            'company', 'warehouse', 'purchase_date', 'currency', 'supplier'})
    product_supplier = fields.Many2One(
        'purchase.product_supplier', "Supplier's Product",
        ondelete='RESTRICT',
        domain=[
            If(Eval('type') != 'line',
                ('id', '=', None),
                ()),
            If(Bool(Eval('product')),
                ['OR',
                    [
                        ('template.products', '=', Eval('product')),
                        ('product', '=', None),
                        ],
                    ('product', '=', Eval('product')),
                    ],
                []),
            ('party', '=', Eval('supplier', -1)),
            ],
        states={
            'invisible': Eval('type') != 'line',
            'readonly': Eval('purchase_state') != 'draft',
            })
    product_uom_category = fields.Function(
        fields.Many2One(
            'product.uom.category', "Product UoM Category",
            help="The category of Unit of Measure for the product."),
        'on_change_with_product_uom_category')
    unit_price = Monetary(
        "Unit Price", currency='currency', digits=price_digits,
        domain=[
            If(Eval('type') != 'line',
                ('unit_price', '=', None),
                ()),
            ],
        states={
            'invisible': Eval('type') != 'line',
            'required': (
                (Eval('type') == 'line')
                & Eval('purchase_state').in_(
                    ['confirmed', 'processing', 'done'])),
            'readonly': Eval('purchase_state') != 'draft',
            })
    amount = fields.Function(Monetary(
            "Amount", currency='currency', digits='currency',
            states={
                'invisible': ~Eval('type').in_(['line', 'subtotal']),
                }),
        'get_amount')
    description = fields.Text('Description', size=None,
        states={
            'readonly': Eval('purchase_state') != 'draft',
            })
    summary = fields.Function(fields.Char('Summary'), 'on_change_with_summary')
    note = fields.Text('Note')
    taxes = fields.Many2Many('purchase.line-account.tax',
        'line', 'tax', 'Taxes',
        order=[('tax.sequence', 'ASC'), ('tax.id', 'ASC')],
        domain=[
            ('parent', '=', None),
            ['OR',
                ('group', '=', None),
                ('group.kind', 'in', ['purchase', 'both']),
                ],
            ('company', '=', Eval('company', -1)),
            If(Eval('type') != 'line',
                ('id', '=', None),
                ()),
            ],
        states={
            'invisible': Eval('type') != 'line',
            'readonly': Eval('purchase_state') != 'draft',
            })
    invoice_lines = fields.One2Many(
        'account.invoice.line', 'origin', "Invoice Lines", readonly=True,
        states={
            'invisible': ~Eval('invoice_lines'),
            })
    moves = fields.One2Many(
        'stock.move', 'origin', "Moves", readonly=True,
        states={
            'invisible': ~Eval('moves'),
            })
    moves_ignored = fields.Many2Many('purchase.line-ignored-stock.move',
            'purchase_line', 'move', 'Ignored Moves', readonly=True)
    moves_recreated = fields.Many2Many('purchase.line-recreated-stock.move',
            'purchase_line', 'move', 'Recreated Moves', readonly=True)
    moves_exception = fields.Function(
        fields.Boolean("Moves Exception"), 'get_moves_exception')
    moves_progress = fields.Function(
        fields.Float("Moves Progress", digits=(1, 4)),
        'get_moves_progress')
    warehouse = fields.Function(fields.Many2One(
            'stock.location', "Warehouse"),
        'on_change_with_warehouse')
    from_location = fields.Function(fields.Many2One('stock.location',
            'From Location'), 'get_from_location')
    to_location = fields.Function(fields.Many2One('stock.location',
            'To Location'), 'get_to_location')
    delivery_date = fields.Function(fields.Date('Delivery Date',
            states={
                'invisible': Eval('type') != 'line',
                'readonly': (Eval('purchase_state').in_(
                        ['processing', 'done', 'cancelled'])
                    | ~Eval('delivery_date_edit', False)),
                }),
        'on_change_with_delivery_date', setter='set_delivery_date')
    delivery_date_edit = fields.Boolean(
        "Edit Delivery Date",
        domain=[
            If(Eval('type') != 'line',
                ('delivery_date_edit', '=', False),
                ()),
            ],
        states={
            'invisible': (
                (Eval('type') != 'line')
                | Eval('purchase_state').in_(
                    ['processing', 'done', 'cancelled'])),
            'readonly': Eval('purchase_state').in_(
                ['processing', 'done', 'cancelled']),
            },
        help="Check to edit the delivery date.")
    delivery_date_store = fields.Date(
        "Delivery Date", readonly=True,
        domain=[
            If(Eval('type') != 'line',
                ('delivery_date_store', '=', None),
                ()),
            ],
        states={
            'invisible': Eval('type') != 'line',
            })
    purchase_state = fields.Function(
        fields.Selection('get_purchase_states', 'Purchase State'),
        'on_change_with_purchase_state', searcher='search_purchase_state')
    company = fields.Function(
        fields.Many2One('company.company', "Company"),
        'on_change_with_company')
    supplier = fields.Function(
        fields.Many2One(
            'party.party', "Supplier",
            context={
                'company': Eval('company', -1),
                }),
        'on_change_with_supplier', searcher='search_supplier')
    purchase_date = fields.Function(
        fields.Date("Purchase Date"),
        'on_change_with_purchase_date', searcher='search_purchase_date')
    currency = fields.Function(
        fields.Many2One('currency.currency', 'Currency'),
        'on_change_with_currency')

    @classmethod
    def get_move_product_types(cls):
        pool = Pool()
        Move = pool.get('stock.move')
        return Move.get_product_types()

    @classmethod
    def __setup__(cls):
        super().__setup__()
        cls.__access__.add('purchase')
        cls._order.insert(0, ('purchase.purchase_date', 'DESC NULLS FIRST'))
        cls._order.insert(1, ('purchase.id', 'DESC'))

    @staticmethod
    def default_type():
        return 'line'

    @fields.depends('type', 'taxes')
    def on_change_type(self):
        if self.type != 'line':
            self.product = None
            self.product_supplier = None
            self.unit = None
            self.taxes = None

    @classmethod
    def default_delivery_date_edit(cls):
        return False

    @property
    def _move_remaining_quantity(self):
        "Compute the remaining quantity to receive"
        pool = Pool()
        Uom = pool.get('product.uom')
        if self.type != 'line' or not self.product:
            return
        if self.product.type == 'service':
            return
        skips = set(self.moves_ignored)
        quantity = abs(self.quantity)
        for move in self.moves:
            if move.state == 'done' or move in skips:
                quantity -= Uom.compute_qty(
                    move.unit, move.quantity, self.unit)
        return quantity

    def get_moves_exception(self, name):
        skips = set(self.moves_ignored)
        skips.update(self.moves_recreated)
        return any(
            m.state == 'cancelled' for m in self.moves if m not in skips)

    def get_moves_progress(self, name):
        progress = None
        quantity = self._move_remaining_quantity
        if quantity is not None and self.quantity:
            progress = round(
                (abs(self.quantity) - quantity) / abs(self.quantity), 4)
            progress = max(0., min(1., progress))
        return progress

    def _get_tax_rule_pattern(self):
        '''
        Get tax rule pattern
        '''
        return {}

    @fields.depends(
        'purchase', '_parent_purchase.currency', '_parent_purchase.party',
        '_parent_purchase.purchase_date', 'company',
        'unit', 'product', 'product_supplier', 'taxes')
    def _get_context_purchase_price(self):
        context = {}
        if self.purchase:
            if self.purchase.currency:
                context['currency'] = self.purchase.currency.id
            if self.purchase.party:
                context['supplier'] = self.purchase.party.id
            context['purchase_date'] = self.purchase.purchase_date
        if self.company:
            context['company'] = self.company.id
        if self.unit:
            context['uom'] = self.unit.id
        elif self.product:
            context['uom'] = self.product.purchase_uom.id
        if self.product_supplier:
            context['product_supplier'] = self.product_supplier.id
        context['taxes'] = [t.id for t in self.taxes or []]
        return context

    @fields.depends('purchase', 'company', '_parent_purchase.party',)
    def _get_product_supplier_pattern(self):
        return {
            'party': (
                self.purchase.party.id
                if self.purchase and self.purchase.party else -1),
            'company': (self.company.id if self.company else -1),
            }

    @fields.depends(
        'purchase', 'taxes',
        '_parent_purchase.party', '_parent_purchase.invoice_party',
        methods=['compute_taxes', 'on_change_with_amount'])
    def on_change_purchase(self):
        party = None
        if self.purchase:
            party = self.purchase.invoice_party or self.purchase.party
        self.taxes = self.compute_taxes(party)
        self.amount = self.on_change_with_amount()

    @fields.depends(
        'product', 'unit', 'purchase', 'taxes',
        '_parent_purchase.party', '_parent_purchase.invoice_party',
        'product_supplier', methods=['compute_taxes', 'compute_unit_price',
            '_get_product_supplier_pattern'])
    def on_change_product(self):
        party = None
        if self.purchase:
            party = self.purchase.invoice_party or self.purchase.party

        # Set taxes before unit_price to have taxes in context of purchase
        # price
        self.taxes = self.compute_taxes(party)

        if self.product:
            category = self.product.purchase_uom.category
            if not self.unit or self.unit.category != category:
                self.unit = self.product.purchase_uom

            product_suppliers = list(self.product.product_suppliers_used(
                    **self._get_product_supplier_pattern()))
            if len(product_suppliers) == 1:
                self.product_supplier, = product_suppliers
            elif (self.product_supplier
                    and self.product_supplier not in product_suppliers):
                self.product_supplier = None

            self.unit_price = self.compute_unit_price()

        self.amount = self.on_change_with_amount()

    @fields.depends(
        'type', 'product',
        methods=['on_change_with_company', '_get_tax_rule_pattern'])
    def compute_taxes(self, party):
        pool = Pool()
        AccountConfiguration = pool.get('account.configuration')

        if self.type != 'line':
            return []

        company = self.on_change_with_company()
        taxes = set()
        pattern = self._get_tax_rule_pattern()
        taxes_used = []
        if self.product:
            taxes_used = self.product.supplier_taxes_used
        elif company:
            account_config = AccountConfiguration(1)
            account = account_config.get_multivalue(
                'default_category_account_expense', company=company.id)
            if account:
                taxes_used = account.taxes
        for tax in taxes_used:
            if party and party.supplier_tax_rule:
                tax_ids = party.supplier_tax_rule.apply(tax, pattern)
                if tax_ids:
                    taxes.update(tax_ids)
                continue
            taxes.add(tax.id)
        if party and party.supplier_tax_rule:
            tax_ids = party.supplier_tax_rule.apply(None, pattern)
            if tax_ids:
                taxes.update(tax_ids)
        return list(taxes)

    @fields.depends('product', 'quantity', 'unit_price',
        methods=['_get_context_purchase_price'])
    def compute_unit_price(self):
        pool = Pool()
        Product = pool.get('product.product')

        unit_price = None
        if self.product:
            with Transaction().set_context(self._get_context_purchase_price()):
                unit_price = Product.get_purchase_price(
                    [self.product], abs(self.quantity or 0))[self.product.id]
        if unit_price is None:
            unit_price = self.unit_price
        return unit_price

    @fields.depends('product', 'product_supplier',
        methods=['on_change_product'])
    def on_change_product_supplier(self):
        if self.product_supplier:
            if self.product_supplier.product:
                self.product = self.product_supplier.product
            elif not self.product:
                if len(self.product_supplier.template.products) == 1:
                    self.product, = self.product_supplier.template.products
        self.on_change_product()

    @fields.depends('product')
    def on_change_with_product_uom_category(self, name=None):
        return self.product.default_uom_category if self.product else None

    @fields.depends(methods=['compute_unit_price'])
    def on_change_quantity(self):
        self.unit_price = self.compute_unit_price()

    @fields.depends(methods=['on_change_quantity', 'on_change_with_amount'])
    def on_change_unit(self):
        self.on_change_quantity()
        self.amount = self.on_change_with_amount()

    @fields.depends(methods=['on_change_quantity', 'on_change_with_amount'])
    def on_change_taxes(self):
        self.on_change_quantity()
        self.amount = self.on_change_with_amount()

    @fields.depends('description')
    def on_change_with_summary(self, name=None):
        return firstline(self.description or '')

    @fields.depends(
        'type', 'quantity', 'unit_price',
        'purchase', '_parent_purchase.currency')
    def on_change_with_amount(self):
        if (self.type == 'line'
                and self.quantity is not None
                and self.unit_price is not None):
            currency = self.purchase.currency if self.purchase else None
            amount = Decimal(str(self.quantity)) * self.unit_price
            if currency:
                return currency.round(amount)
            return amount

    def get_amount(self, name):
        if self.type == 'line':
            return self.on_change_with_amount()
        elif self.type == 'subtotal':
            amount = Decimal(0)
            for line2 in self.purchase.lines:
                if line2.type == 'line':
                    amount += line2.purchase.currency.round(
                        Decimal(str(line2.quantity)) * line2.unit_price)
                elif line2.type == 'subtotal':
                    if self == line2:
                        break
                    amount = Decimal(0)
            return amount

    @fields.depends('purchase', '_parent_purchase.warehouse')
    def on_change_with_warehouse(self, name=None):
        return self.purchase.warehouse if self.purchase else None

    def get_from_location(self, name):
        if (self.quantity or 0) >= 0:
            if self.purchase.party.supplier_location:
                return self.purchase.party.supplier_location
        elif self.purchase.return_from_location:
            return self.purchase.return_from_location

    def get_to_location(self, name):
        if (self.quantity or 0) >= 0:
            if self.purchase.warehouse:
                return self.purchase.warehouse.input_location
        elif self.purchase.party.supplier_location:
            return self.purchase.party.supplier_location

    @fields.depends('moves', methods=['planned_delivery_date'])
    def on_change_with_delivery_date(self, name=None):
        moves = [m for m in self.moves if m.state != 'cancelled']
        if moves:
            dates = filter(
                None, (m.effective_date or m.planned_date for m in moves))
            return min(dates, default=None)
        return self.planned_delivery_date

    @classmethod
    def set_delivery_date(cls, lines, name, value):
        cls.write([l for l in lines if l.delivery_date_edit], {
                'delivery_date_store': value,
                })

    @fields.depends('delivery_date_edit', 'delivery_date',
        methods=['planned_delivery_date'])
    def on_change_delivery_date_edit(self):
        if not self.delivery_date_edit:
            self.delivery_date = self.planned_delivery_date

    @property
    @fields.depends(
        'product_supplier', 'quantity', 'purchase',
        '_parent_purchase.purchase_date',
        'delivery_date_edit', 'delivery_date_store',
        '_parent_purchase.delivery_date', '_parent_purchase.party',
        '_parent_purchase.company')
    def planned_delivery_date(self):
        pool = Pool()
        Date = pool.get('ir.date')
        ProductSupplier = pool.get('purchase.product_supplier')
        if self.purchase and self.purchase.company:
            with Transaction().set_context(company=self.purchase.company.id):
                today = Date.today()
        else:
            today = Date.today()
        product_supplier = self.product_supplier
        if not product_supplier and self.purchase and self.purchase.company:
            product_supplier = ProductSupplier(
                party=self.purchase.party,
                company=self.purchase.company)
        delivery_date = None
        if self.delivery_date_edit:
            delivery_date = self.delivery_date_store
        elif self.purchase and self.purchase.delivery_date:
            delivery_date = self.purchase.delivery_date
        elif (product_supplier
                and self.quantity is not None
                and self.quantity > 0
                and self.purchase):
            date = self.purchase.purchase_date if self.purchase else None
            delivery_date = product_supplier.compute_supply_date(date=date)
            if delivery_date == datetime.date.max:
                delivery_date = None
        if delivery_date and delivery_date < today:
            delivery_date = None
        return delivery_date

    @classmethod
    def get_purchase_states(cls):
        pool = Pool()
        Purchase = pool.get('purchase.purchase')
        return Purchase.fields_get(['state'])['state']['selection']

    @fields.depends('purchase', '_parent_purchase.state')
    def on_change_with_purchase_state(self, name=None):
        if self.purchase:
            return self.purchase.state

    @classmethod
    def search_purchase_state(cls, name, clause):
        return [('purchase.state', *clause[1:])]

    @fields.depends('purchase', '_parent_purchase.company')
    def on_change_with_company(self, name=None):
        return self.purchase.company if self.purchase else None

    @fields.depends('purchase', '_parent_purchase.party')
    def on_change_with_supplier(self, name=None):
        return self.purchase.party if self.purchase else None

    @classmethod
    def search_supplier(cls, name, clause):
        return [('purchase.party' + clause[0][len(name):], *clause[1:])]

    @fields.depends('purchase', '_parent_purchase.purchase_date')
    def on_change_with_purchase_date(self, name=None):
        if self.purchase:
            return self.purchase.purchase_date

    @classmethod
    def search_purchase_date(cls, name, clause):
        return [('purchase.purchase_date', *clause[1:])]

    @classmethod
    def order_purchase_date(cls, tables):
        return cls.purchase.convert_order(
            'purchase.purchase_date', tables, cls)

    @fields.depends('purchase', '_parent_purchase.currency')
    def on_change_with_currency(self, name=None):
        return self.purchase.currency if self.purchase else None

    def get_invoice_line(self):
        'Return a list of invoice line for purchase line'
        pool = Pool()
        InvoiceLine = pool.get('account.invoice.line')
        AccountConfiguration = pool.get('account.configuration')
        account_config = AccountConfiguration(1)

        if self.type != 'line':
            return []

        invoice_line = InvoiceLine()
        invoice_line.type = self.type
        invoice_line.currency = self.currency
        invoice_line.company = self.company
        invoice_line.description = self.description
        invoice_line.note = self.note
        invoice_line.origin = self

        quantity = (self._get_invoice_line_quantity()
            - self._get_invoiced_quantity())

        if self.unit:
            quantity = self.unit.round(quantity)
        invoice_line.quantity = quantity

        if not invoice_line.quantity:
            return []

        invoice_line.unit = self.unit
        invoice_line.product = self.product
        invoice_line.unit_price = self.unit_price
        invoice_line.taxes = self.taxes
        if self.company.purchase_taxes_expense:
            invoice_line.taxes_deductible_rate = 0
        elif self.product:
            invoice_line.taxes_deductible_rate = (
                self.product.supplier_taxes_deductible_rate_used)
        invoice_line.invoice_type = 'in'
        if self.product:
            invoice_line.account = self.product.account_expense_used
            if not invoice_line.account:
                raise AccountError(
                    gettext('purchase'
                        '.msg_purchase_product_missing_account_expense',
                        purchase=self.purchase.rec_name,
                        product=self.product.rec_name))
        else:
            invoice_line.account = account_config.get_multivalue(
                'default_category_account_expense', company=self.company.id)
            if not invoice_line.account:
                raise AccountError(
                    gettext('purchase'
                        '.msg_purchase_missing_account_expense',
                        purchase=self.purchase.rec_name))
        invoice_line.stock_moves = self._get_invoice_line_moves(
            invoice_line.quantity)
        return [invoice_line]

    def _get_invoice_line_quantity(self):
        'Return the quantity that should be invoiced'
        pool = Pool()
        Uom = pool.get('product.uom')

        if (self.purchase.invoice_method in {'order', 'manual'}
                or not self.product
                or self.product.type == 'service'):
            return self.quantity
        elif self.purchase.invoice_method == 'shipment':
            quantity = 0.0
            for move in self.moves:
                if move.state != 'done':
                    continue
                qty = Uom.compute_qty(move.unit, move.quantity, self.unit)
                # Test only against from_location
                # as it is what matters for purchase
                src_type = 'supplier'
                if (move.from_location.type == src_type
                        and move.to_location.type != src_type):
                    quantity += qty
                elif (move.to_location.type == src_type
                        and move.from_location.type != src_type):
                    quantity -= qty
            return quantity

    def _get_invoiced_quantity(self):
        'Return the quantity already invoiced'
        pool = Pool()
        Uom = pool.get('product.uom')

        quantity = 0
        skips = {l for i in self.purchase.invoices_recreated for l in i.lines}
        for invoice_line in self.invoice_lines:
            if invoice_line.type != 'line':
                continue
            if invoice_line not in skips:
                if self.unit:
                    quantity += Uom.compute_qty(
                        invoice_line.unit or self.unit, invoice_line.quantity,
                        self.unit)
                else:
                    quantity += invoice_line.quantity
        return quantity

    def _get_invoice_line_moves(self, quantity):
        'Return the stock moves that should be invoiced'
        moves = []
        if self.purchase.invoice_method in {'order', 'manual'}:
            moves.extend(self.moves)
        elif (self.purchase.invoice_method == 'shipment'
                and samesign(self.quantity, quantity)):
            for move in self.moves:
                if move.state == 'done':
                    if move.invoiced_quantity < move.quantity:
                        moves.append(move)
        return moves

    def get_move(self, move_type):
        '''
        Return move values for purchase line
        '''
        pool = Pool()
        Move = pool.get('stock.move')

        if self.type != 'line':
            return
        if not self.product:
            return
        if self.product.type not in Move.get_product_types():
            return

        if (self.quantity >= 0) != (move_type == 'in'):
            return

        quantity = (self._get_move_quantity(move_type)
            - self._get_shipped_quantity(move_type))

        quantity = self.unit.round(quantity)
        if quantity <= 0:
            return

        if not self.purchase.party.supplier_location:
            raise PartyLocationError(
                gettext('purchase.msg_purchase_supplier_location_required',
                    purchase=self.purchase.rec_name,
                    party=self.purchase.party.rec_name))
        move = Move()
        move.quantity = quantity
        move.unit = self.unit
        move.product = self.product
        move.from_location = self.from_location
        move.to_location = self.to_location
        move.state = 'draft'
        move.company = self.purchase.company
        if move.on_change_with_unit_price_required():
            move.unit_price = self.unit_price
            move.currency = self.purchase.currency
        else:
            move.unit_price = None
            move.currency = None
        move.planned_date = self.planned_delivery_date
        move.invoice_lines = self._get_move_invoice_lines(move_type)
        move.origin = self
        move.origin_planned_date = move.planned_date
        return move

    def _get_move_quantity(self, move_type):
        'Return the quantity that should be shipped'
        return abs(self.quantity)

    def _get_shipped_quantity(self, move_type):
        'Return the quantity already shipped'
        pool = Pool()
        Uom = pool.get('product.uom')

        quantity = 0
        skip = set(self.moves_recreated)
        for move in self.moves:
            if move not in skip:
                quantity += Uom.compute_qty(
                    move.unit, move.quantity, self.unit)
        return quantity

    def check_move_quantity(self):
        pool = Pool()
        Lang = pool.get('ir.lang')
        Warning = pool.get('res.user.warning')
        lang = Lang.get()
        move_type = 'in' if self.quantity >= 0 else 'return'
        quantity = (
            self._get_move_quantity(move_type)
            - self._get_shipped_quantity(move_type))
        if self.unit.round(quantity) < 0:
            warning_name = Warning.format(
                'check_move_quantity', [self])
            if Warning.check(warning_name):
                raise PurchaseMoveQuantity(warning_name, gettext(
                        'purchase.msg_purchase_line_move_quantity',
                        line=self.rec_name,
                        extra=lang.format_number_symbol(
                            -quantity, self.unit),
                        quantity=lang.format_number_symbol(
                            self.quantity, self.unit)))

    def _get_move_invoice_lines(self, move_type):
        'Return the invoice lines that should be shipped'
        if self.purchase.invoice_method in {'order', 'manual'}:
            lines = self.invoice_lines
        else:
            lines = filter(lambda l: not l.stock_moves, self.invoice_lines)
            lines = filter(
                lambda l: samesign(self.quantity, l.quantity), lines)
        return list(lines)

    def set_actual_quantity(self):
        pool = Pool()
        Uom = pool.get('product.uom')
        if self.type != 'line':
            return
        moved_quantity = 0
        for move in self.moves:
            if move.state != 'cancelled' and self.unit:
                moved_quantity += Uom.compute_qty(
                    move.unit, move.quantity, self.unit, round=False)
        if self.quantity < 0:
            moved_quantity *= -1
        invoiced_quantity = 0
        for invoice_line in self.invoice_lines:
            if (not invoice_line.invoice
                    or invoice_line.invoice.state != 'cancelled'):
                if self.unit:
                    invoiced_quantity += Uom.compute_qty(
                        invoice_line.unit or self.unit, invoice_line.quantity,
                        self.unit, round=False)
                else:
                    invoiced_quantity += invoice_line.quantity
        actual_quantity = max(moved_quantity, invoiced_quantity, key=abs)
        if self.unit:
            actual_quantity = self.unit.round(actual_quantity)
        if self.actual_quantity != actual_quantity:
            self.actual_quantity = actual_quantity

    def get_rec_name(self, name):
        pool = Pool()
        Lang = pool.get('ir.lang')
        if self.product:
            lang = Lang.get()
            return (lang.format_number_symbol(
                    self.quantity or 0, self.unit, digits=self.unit.digits)
                + ' %s @ %s' % (self.product.rec_name, self.purchase.rec_name))
        else:
            return self.purchase.rec_name

    @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'
        return [bool_op,
            ('purchase.rec_name', *clause[1:]),
            ('product.rec_name', *clause[1:]),
            ]

    @classmethod
    def view_attributes(cls):
        return super().view_attributes() + [
            ('/form//field[@name="note"]|/form//field[@name="description"]',
                'spell', Eval('_parent_purchase', {}).get('party_lang')),
            ('//label[@id="delivery_date"]', 'states', {
                    'invisible': Eval('type') != 'line',
                    }),
            ]

    @classmethod
    def create(cls, vlist):
        pool = Pool()
        Purchase = pool.get('purchase.purchase')
        purchase_ids = filter(None, {v.get('purchase') for v in vlist})
        for purchase in Purchase.browse(list(purchase_ids)):
            if purchase.state != 'draft':
                raise AccessError(
                    gettext('purchase.msg_purchase_line_create_draft',
                        purchase=purchase.rec_name))
        return super().create(vlist)

    @classmethod
    def delete(cls, lines):
        for line in lines:
            if line.purchase_state not in {'cancelled', 'draft'}:
                raise AccessError(
                    gettext('purchase.msg_purchase_line_delete_cancel_draft',
                        line=line.rec_name,
                        purchase=line.purchase.rec_name))
        super().delete(lines)

    @classmethod
    def copy(cls, lines, default=None):
        if default is None:
            default = {}
        else:
            default = default.copy()
        default.setdefault('moves', None)
        default.setdefault('moves_ignored', None)
        default.setdefault('moves_recreated', None)
        default.setdefault('invoice_lines', None)
        default.setdefault('actual_quantity')
        return super().copy(lines, default=default)


class LineTax(ModelSQL):
    'Purchase Line - Tax'
    __name__ = 'purchase.line-account.tax'
    _table = 'purchase_line_account_tax'
    line = fields.Many2One(
        'purchase.line', "Purchase Line", ondelete='CASCADE', required=True,
        domain=[('type', '=', 'line')])
    tax = fields.Many2One(
        'account.tax', "Tax", ondelete='RESTRICT', required=True,
        domain=[('parent', '=', None)])

    @classmethod
    def __setup__(cls):
        super().__setup__()
        t = cls.__table__()
        cls._sql_constraints += [
            ('line_tax_unique', Unique(t, t.line, t.tax),
                'purchase.msg_purchase_line_tax_unique'),
            ]


class LineIgnoredMove(ModelSQL):
    'Purchase Line - Ignored Move'
    __name__ = 'purchase.line-ignored-stock.move'
    _table = 'purchase_line_moves_ignored_rel'
    purchase_line = fields.Many2One(
        'purchase.line', "Purchase Line", ondelete='CASCADE', required=True)
    move = fields.Many2One(
        'stock.move', "Move", ondelete='RESTRICT', required=True)


class LineRecreatedMove(ModelSQL):
    'Purchase Line - Ignored Move'
    __name__ = 'purchase.line-recreated-stock.move'
    _table = 'purchase_line_moves_recreated_rel'
    purchase_line = fields.Many2One(
        'purchase.line', "Purchase Line", ondelete='CASCADE', required=True)
    move = fields.Many2One(
        'stock.move', "Move", ondelete='RESTRICT', required=True)


class PurchaseReport(CompanyReport):
    __name__ = 'purchase.purchase'

    @classmethod
    def execute(cls, ids, data):
        with Transaction().set_context(address_with_party=True):
            return super(PurchaseReport, cls).execute(ids, data)

    @classmethod
    def get_context(cls, records, header, data):
        pool = Pool()
        Date = pool.get('ir.date')
        context = super().get_context(records, header, data)
        company = header.get('company')
        with Transaction().set_context(
                company=company.id if company else None):
            context['today'] = Date.today()
        return context


class OpenSupplier(Wizard):
    'Open Suppliers'
    __name__ = 'purchase.open_supplier'
    start_state = 'open_'
    open_ = StateAction('party.act_party_form')

    def do_open_(self, action):
        pool = Pool()
        ModelData = pool.get('ir.model.data')
        Wizard = pool.get('ir.action.wizard')
        Purchase = pool.get('purchase.purchase')
        cursor = Transaction().connection.cursor()
        purchase = Purchase.__table__()

        cursor.execute(*purchase.select(purchase.party,
                group_by=purchase.party))
        supplier_ids = [line[0] for line in cursor]
        action['pyson_domain'] = PYSONEncoder().encode(
            [('id', 'in', supplier_ids)])
        wizard = Wizard(ModelData.get_id('purchase', 'act_open_supplier'))
        action['name'] = wizard.name
        return action, {}


class HandleShipmentExceptionAsk(ModelView):
    'Handle Shipment Exception'
    __name__ = 'purchase.handle.shipment.exception.ask'
    recreate_moves = fields.Many2Many(
        'stock.move', None, None, 'Recreate Moves',
        domain=[('id', 'in', Eval('domain_moves'))],
        help=('The selected moves will be recreated. '
            'The other ones will be ignored.'))
    domain_moves = fields.Many2Many(
        'stock.move', None, None, 'Domain Moves')


class HandleShipmentException(Wizard):
    'Handle Shipment Exception'
    __name__ = 'purchase.handle.shipment.exception'
    start_state = 'ask'
    ask = StateView('purchase.handle.shipment.exception.ask',
        'purchase.handle_shipment_exception_ask_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('OK', 'handle', 'tryton-ok', default=True),
            ])
    handle = StateTransition()

    def default_ask(self, fields):
        moves = []
        for line in self.record.lines:
            skip = set(line.moves_ignored + line.moves_recreated)
            for move in line.moves:
                if move.state == 'cancelled' and move not in skip:
                    moves.append(move.id)
        return {
            'recreate_moves': moves,
            'domain_moves': moves,
            }

    def transition_handle(self):
        pool = Pool()
        PurchaseLine = pool.get('purchase.line')
        to_recreate = self.ask.recreate_moves
        domain_moves = self.ask.domain_moves

        for line in self.record.lines:
            moves_ignored = []
            moves_recreated = []
            skip = set(line.moves_ignored)
            skip.update(line.moves_recreated)
            for move in line.moves:
                if move not in domain_moves or move in skip:
                    continue
                if move in to_recreate:
                    moves_recreated.append(move.id)
                else:
                    moves_ignored.append(move.id)

            PurchaseLine.write([line], {
                'moves_ignored': [('add', moves_ignored)],
                'moves_recreated': [('add', moves_recreated)],
                })

        self.model.__queue__.process([self.record])
        return 'end'


class HandleInvoiceExceptionAsk(ModelView):
    'Handle Invoice Exception'
    __name__ = 'purchase.handle.invoice.exception.ask'
    recreate_invoices = fields.Many2Many(
        'account.invoice', None, None, 'Recreate Invoices',
        domain=[('id', 'in', Eval('domain_invoices'))],
        help=('The selected invoices will be recreated. '
            'The other ones will be ignored.'))
    domain_invoices = fields.Many2Many(
        'account.invoice', None, None, 'Domain Invoices')


class HandleInvoiceException(Wizard):
    'Handle Invoice Exception'
    __name__ = 'purchase.handle.invoice.exception'
    start_state = 'ask'
    ask = StateView('purchase.handle.invoice.exception.ask',
        'purchase.handle_invoice_exception_ask_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('OK', 'handle', 'tryton-ok', default=True),
            ])
    handle = StateTransition()

    def default_ask(self, fields):
        skip = set(self.record.invoices_ignored)
        skip.update(self.record.invoices_recreated)
        invoices = []
        for invoice in self.record.invoices:
            if invoice.state == 'cancelled' and invoice not in skip:
                invoices.append(invoice.id)
        return {
            'recreate_invoices': invoices,
            'domain_invoices': invoices,
            }

    def transition_handle(self):
        invoices_ignored = []
        invoices_recreated = []
        for invoice in self.ask.domain_invoices:
            if invoice in self.ask.recreate_invoices:
                invoices_recreated.append(invoice.id)
            else:
                invoices_ignored.append(invoice.id)

        self.model.write([self.record], {
            'invoices_ignored': [('add', invoices_ignored)],
            'invoices_recreated': [('add', invoices_recreated)],
            })

        self.model.__queue__.process([self.record])
        return 'end'


class ModifyHeaderStateView(StateView):
    def get_view(self, wizard, state_name):
        with Transaction().set_context(modify_header=True):
            return super(ModifyHeaderStateView, self).get_view(
                wizard, state_name)

    def get_defaults(self, wizard, state_name, fields):
        return {}


class ModifyHeader(Wizard):
    "Modify Header"
    __name__ = 'purchase.modify_header'
    start = ModifyHeaderStateView('purchase.purchase',
        'purchase.modify_header_form', [
            Button("Cancel", 'end', 'tryton-cancel'),
            Button("Modify", 'modify', 'tryton-ok', default=True),
            ])
    modify = StateTransition()

    def get_purchase(self):
        if self.record.state != 'draft':
            raise AccessError(
                gettext('purchase.msg_purchase_modify_header_draft',
                    purchase=self.record.rec_name))
        return self.record

    def value_start(self, fields):
        purchase = self.get_purchase()
        values = {}
        for fieldname in fields:
            value = getattr(purchase, fieldname)
            if isinstance(value, Model):
                if getattr(purchase.__class__, fieldname)._type == 'reference':
                    value = str(value)
                else:
                    value = value.id
            elif (value and isinstance(value, (list, tuple))
                    and isinstance(value[0], Model)):
                value = [r.id for r in value]
            values[fieldname] = value

        # Mimic an empty sale in draft state to get the fields' states right
        values['lines'] = []
        return values

    def transition_modify(self):
        pool = Pool()
        Line = pool.get('purchase.line')

        purchase = self.get_purchase()
        values = self.start._save_values
        self.model.write([purchase], values)
        self.model.log([purchase], 'write', ','.join(sorted(values.keys())))

        # Call on_change after the save to ensure parent sale
        # has the modified values
        for line in purchase.lines:
            line.on_change_product()
        Line.save(purchase.lines)

        return 'end'


class ReturnPurchaseStart(ModelView):
    "Return Purchase"
    __name__ = 'purchase.return_purchase.start'


class ReturnPurchase(Wizard):
    "Return Purchase"
    __name__ = 'purchase.return_purchase'
    start = StateView('purchase.return_purchase.start',
        'purchase.return_purchase_start_view_form', [
            Button("Cancel", 'end', 'tryton-cancel'),
            Button("Return", 'return_', 'tryton-ok', default=True),
            ])
    return_ = StateAction('purchase.act_purchase_form')

    def do_return_(self, action):
        purchases = self.records
        return_purchases = self.model.copy(purchases, default={
                'origin': lambda data: (
                    '%s,%s' % (self.model.__name__, data['id'])),
                'lines.quantity': lambda data: (
                    data['quantity'] * -1 if data['type'] == 'line'
                    else data['quantity']),
                })

        data = {'res_id': [s.id for s in return_purchases]}
        if len(return_purchases) == 1:
            action['views'].reverse()
        return action, data