/usr/share/pyshared/trytond/modules/sale/sale.py is in tryton-modules-sale 2.2.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | #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 copy
from decimal import Decimal
import datetime
from itertools import groupby
from functools import partial
from trytond.model import ModelWorkflow, ModelView, ModelSQL, fields
from trytond.modules.company import CompanyReport
from trytond.wizard import Wizard
from trytond.backend import TableHandler
from trytond.pyson import If, Eval, Bool, PYSONEncoder
from trytond.transaction import Transaction
from trytond.pool import Pool
class Sale(ModelWorkflow, ModelSQL, ModelView):
'Sale'
_name = 'sale.sale'
_rec_name = 'reference'
_description = __doc__
company = fields.Many2One('company.company', 'Company', required=True,
states={
'readonly': (Eval('state') != 'draft') | Eval('lines', []),
},
domain=[
('id', If(Eval('context', {}).contains('company'), '=', '!='),
Eval('context', {}).get('company', 0)),
],
depends=['state', 'lines'])
reference = fields.Char('Reference', readonly=True, select=1)
description = fields.Char('Description',
states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
state = fields.Selection([
('draft', 'Draft'),
('quotation', 'Quotation'),
('confirmed', 'Confirmed'),
('done', 'Done'),
('cancel', 'Canceled'),
], 'State', readonly=True, required=True)
sale_date = fields.Date('Sale Date', required=True,
states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
payment_term = fields.Many2One('account.invoice.payment_term',
'Payment Term', required=True, states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
party = fields.Many2One('party.party', 'Party', change_default=True,
required=True, select=1, states={
'readonly': Eval('state') != 'draft',
}, on_change=['party', 'payment_term'],
depends=['state'])
party_lang = fields.Function(fields.Char('Party Language',
on_change_with=['party']), 'get_function_fields')
invoice_address = fields.Many2One('party.address', 'Invoice Address',
domain=[('party', '=', Eval('party'))], states={
'readonly': Eval('state') != 'draft',
}, depends=['state', 'party'])
shipment_address = fields.Many2One('party.address', 'Shipment Address',
domain=[('party', '=', Eval('party'))], states={
'readonly': Eval('state') != 'draft',
},
depends=['party', 'state'])
warehouse = fields.Many2One('stock.location', 'Warehouse',
domain=[('type', '=', 'warehouse')], required=True, states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
currency = fields.Many2One('currency.currency', 'Currency', required=True,
states={
'readonly': (Eval('state') != 'draft') |
(Eval('lines', []) & Eval('currency', 0)),
},
depends=['state', 'lines'])
currency_digits = fields.Function(fields.Integer('Currency Digits',
on_change_with=['currency']), 'get_function_fields')
lines = fields.One2Many('sale.line', 'sale', 'Lines', states={
'readonly': Eval('state') != 'draft',
}, on_change=['lines', 'currency', 'party'],
depends=['party', 'state'])
comment = fields.Text('Comment')
untaxed_amount = fields.Function(fields.Numeric('Untaxed',
digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits']), 'get_function_fields')
tax_amount = fields.Function(fields.Numeric('Tax',
digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits']), 'get_function_fields')
total_amount = fields.Function(fields.Numeric('Total',
digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits']), 'get_function_fields')
invoice_method = fields.Selection([
('manual', 'Manual'),
('order', 'On Order Confirmed'),
('shipment', 'On Shipment Sent'),
],
'Invoice Method', required=True, states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
invoice_state = fields.Selection([
('none', 'None'),
('waiting', 'Waiting'),
('paid', 'Paid'),
('exception', 'Exception'),
], 'Invoice State', readonly=True, required=True)
invoices = fields.Many2Many('sale.sale-account.invoice',
'sale', 'invoice', 'Invoices', readonly=True)
invoices_ignored = fields.Many2Many('sale.sale-ignored-account.invoice',
'sale', 'invoice', 'Ignored Invoices', readonly=True)
invoices_recreated = fields.Many2Many('sale.sale-recreated-account.invoice',
'sale', 'invoice', 'Recreated Invoices', readonly=True)
invoice_paid = fields.Function(fields.Boolean('Invoices Paid'),
'get_function_fields')
invoice_exception = fields.Function(fields.Boolean('Invoices Exception'),
'get_function_fields')
shipment_method = fields.Selection([
('manual', 'Manual'),
('order', 'On Order Confirmed'),
('invoice', 'On Invoice Paid'),
], 'Shipment Method', required=True,
states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
shipment_state = fields.Selection([
('none', 'None'),
('waiting', 'Waiting'),
('sent', 'Sent'),
('exception', 'Exception'),
], 'Shipment State', readonly=True, required=True)
shipments = fields.Function(fields.One2Many('stock.shipment.out', None,
'Shipments'), 'get_function_fields')
moves = fields.Function(fields.One2Many('stock.move', None, 'Moves'),
'get_function_fields')
shipment_done = fields.Function(fields.Boolean('Shipment Done'),
'get_function_fields')
shipment_exception = fields.Function(fields.Boolean('Shipments Exception'),
'get_function_fields')
def __init__(self):
super(Sale, self).__init__()
self._order[0] = ('sale_date', 'DESC')
self._order[0] = ('id', 'DESC')
self._constraints += [
('check_method', 'wrong_method')
]
self._error_messages.update({
'wrong_method': 'Wrong combination of method!',
'addresses_required': 'Invoice and Shipment addresses must be '
'defined for the quotation.',
'missing_account_receivable': 'It misses '
'an "Account Receivable" on the party "%s"!',
})
def init(self, module_name):
cursor = Transaction().cursor
# Migration from 1.2: packing renamed into shipment
cursor.execute("UPDATE ir_model_data "
"SET fs_id = REPLACE(fs_id, 'packing', 'shipment') "
"WHERE fs_id like '%%packing%%' AND module = %s",
(module_name,))
cursor.execute("UPDATE ir_model_field "
"SET relation = REPLACE(relation, 'packing', 'shipment'), "
"name = REPLACE(name, 'packing', 'shipment') "
"WHERE (relation like '%%packing%%' "
"OR name like '%%packing%%') AND module = %s",
(module_name,))
table = TableHandler(cursor, self, module_name)
table.column_rename('packing_state', 'shipment_state')
table.column_rename('packing_method', 'shipment_method')
table.column_rename('packing_address', 'shipment_address')
super(Sale, self).init(module_name)
# Migration from 1.2
cursor.execute("UPDATE " + self._table + " "
"SET invoice_method = 'shipment' "
"WHERE invoice_method = 'packing'")
# Add index on create_date
table = TableHandler(cursor, self, module_name)
table.index_action('create_date', action='add')
def default_payment_term(self):
payment_term_obj = Pool().get('account.invoice.payment_term')
payment_term_ids = payment_term_obj.search(self.payment_term.domain)
if len(payment_term_ids) == 1:
return payment_term_ids[0]
return False
def default_warehouse(self):
location_obj = Pool().get('stock.location')
location_ids = location_obj.search(self.warehouse.domain)
if len(location_ids) == 1:
return location_ids[0]
return False
def default_company(self):
return Transaction().context.get('company') or False
def default_state(self):
return 'draft'
def default_sale_date(self):
date_obj = Pool().get('ir.date')
return date_obj.today()
def default_currency(self):
company_obj = Pool().get('company.company')
currency_obj = Pool().get('currency.currency')
company = Transaction().context.get('company')
if company:
return company_obj.browse(company).currency.id
return False
def default_currency_digits(self):
company_obj = Pool().get('company.company')
company = Transaction().context.get('company')
if company:
return company_obj.browse(company).currency.digits
return 2
def default_invoice_method(self):
config_obj = Pool().get('sale.configuration')
config = config_obj.browse(1)
return config.sale_invoice_method
def default_invoice_state(self):
return 'none'
def default_shipment_method(self):
config_obj = Pool().get('sale.configuration')
config = config_obj.browse(1)
return config.sale_shipment_method
def default_shipment_state(self):
return 'none'
def on_change_party(self, vals):
pool = Pool()
party_obj = pool.get('party.party')
address_obj = pool.get('party.address')
payment_term_obj = pool.get('account.invoice.payment_term')
res = {
'invoice_address': False,
'shipment_address': False,
'payment_term': False,
}
if vals.get('party'):
party = party_obj.browse(vals['party'])
res['invoice_address'] = party_obj.address_get(party.id,
type='invoice')
res['shipment_address'] = party_obj.address_get(party.id,
type='delivery')
if party.payment_term:
res['payment_term'] = party.payment_term.id
if res['invoice_address']:
res['invoice_address.rec_name'] = address_obj.browse(
res['invoice_address']).rec_name
if res['shipment_address']:
res['shipment_address.rec_name'] = address_obj.browse(
res['shipment_address']).rec_name
if not res['payment_term']:
res['payment_term'] = self.default_payment_term()
if res['payment_term']:
res['payment_term.rec_name'] = payment_term_obj.browse(
res['payment_term']).rec_name
return res
def on_change_with_currency_digits(self, vals):
currency_obj = Pool().get('currency.currency')
if vals.get('currency'):
currency = currency_obj.browse(vals['currency'])
return currency.digits
return 2
def get_currency_digits(self, sales):
'''
Return the number of digits of the currency of each sales
:param sales: a BrowseRecordList of puchases
:return: a dictionary with sale id as key and
number of digits as value
'''
res = {}
for sale in sales:
res[sale.id] = sale.currency.digits
return res
def get_tax_context(self, sale):
party_obj = Pool().get('party.party')
res = {}
if isinstance(sale, dict):
if sale.get('party'):
party = party_obj.browse(sale['party'])
if party.lang:
res['language'] = party.lang.code
else:
if sale.party.lang:
res['language'] = sale.party.lang.code
return res
def on_change_with_party_lang(self, vals):
party_obj = Pool().get('party.party')
if vals.get('party'):
party = party_obj.browse(vals['party'])
if party.lang:
return party.lang.code
return 'en_US'
def get_party_lang(self, sales):
'''
Return the code lang of the party for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
code lang as value
'''
res = {}
for sale in sales:
if sale.party.lang:
res[sale.id] = sale.party.lang.code
else:
res[sale.id] = 'en_US'
return res
def on_change_lines(self, vals):
pool = Pool()
currency_obj = pool.get('currency.currency')
tax_obj = pool.get('account.tax')
invoice_obj = pool.get('account.invoice')
res = {
'untaxed_amount': Decimal('0.0'),
'tax_amount': Decimal('0.0'),
'total_amount': Decimal('0.0'),
}
currency = None
if vals.get('currency'):
currency = currency_obj.browse(vals['currency'])
if vals.get('lines'):
taxes = {}
for line in vals['lines']:
if line.get('type', 'line') != 'line':
continue
res['untaxed_amount'] += line.get('amount', Decimal('0.0'))
tax_list = ()
with Transaction().set_context(self.get_tax_context(vals)):
tax_list = tax_obj.compute(line.get('taxes', []),
line.get('unit_price', Decimal('0.0')),
line.get('quantity', 0.0))
for tax in tax_list:
key, val = invoice_obj._compute_tax(tax,'out_invoice')
if not key in taxes:
taxes[key] = val['amount']
else:
taxes[key] += val['amount']
if currency:
for key in taxes:
res['tax_amount'] += currency_obj.round(currency,
taxes[key])
if currency:
res['untaxed_amount'] = currency_obj.round(currency,
res['untaxed_amount'])
res['tax_amount'] = currency_obj.round(currency,
res['tax_amount'])
res['total_amount'] = res['untaxed_amount'] + res['tax_amount']
if currency:
res['total_amount'] = currency_obj.round(currency,
res['total_amount'])
return res
def get_function_fields(self, ids, names):
'''
Function to compute function fields for sale ids
:param ids: the ids of the sales
:param names: the list of field name to compute
:return: a dictionary with all field names as key and
a dictionary as value with id as key
'''
res = {}
sales = self.browse(ids)
if 'currency_digits' in names:
res['currency_digits'] = self.get_currency_digits(sales)
if 'party_lang' in names:
res['party_lang'] = self.get_party_lang(sales)
if 'untaxed_amount' in names:
res['untaxed_amount'] = self.get_untaxed_amount(sales)
if 'tax_amount' in names:
res['tax_amount'] = self.get_tax_amount(sales)
if 'total_amount' in names:
res['total_amount'] = self.get_total_amount(sales)
if 'invoice_paid' in names:
res['invoice_paid'] = self.get_invoice_paid(sales)
if 'invoice_exception' in names:
res['invoice_exception'] = self.get_invoice_exception(sales)
if 'shipments' in names:
res['shipments'] = self.get_shipments(sales)
if 'moves' in names:
res['moves'] = self.get_moves(sales)
if 'shipment_done' in names:
res['shipment_done'] = self.get_shipment_done(sales)
if 'shipment_exception' in names:
res['shipment_exception'] = self.get_shipment_exception(sales)
return res
def get_untaxed_amount(self, sales):
'''
Compute the untaxed amount for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
untaxed amount as value
'''
currency_obj = Pool().get('currency.currency')
res = {}
for sale in sales:
res.setdefault(sale.id, Decimal('0.0'))
for line in sale.lines:
if line.type != 'line':
continue
res[sale.id] += line.amount
res[sale.id] = currency_obj.round(sale.currency, res[sale.id])
return res
def get_tax_amount(self, sales):
'''
Compute tax amount for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
tax amount as value
'''
pool = Pool()
currency_obj = pool.get('currency.currency')
tax_obj = pool.get('account.tax')
invoice_obj = pool.get('account.invoice')
res = {}
for sale in sales:
res.setdefault(sale.id, Decimal('0.0'))
taxes = {}
for line in sale.lines:
if line.type != 'line':
continue
# Don't round on each line to handle rounding error
tax_list = ()
with Transaction().set_context(self.get_tax_context(sale)):
tax_list = tax_obj.compute(
[t.id for t in line.taxes], line.unit_price,
line.quantity)
for tax in tax_list:
key, val = invoice_obj._compute_tax(tax, 'out_invoice')
if not key in taxes:
taxes[key] = val['amount']
else:
taxes[key] += val['amount']
for key in taxes:
res[sale.id] += currency_obj.round(sale.currency, taxes[key])
res[sale.id] = currency_obj.round(sale.currency, res[sale.id])
return res
def get_total_amount(self, sales):
'''
Return the total amount of each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
total amount as value
'''
currency_obj = Pool().get('currency.currency')
res = {}
untaxed_amounts = self.get_untaxed_amount(sales)
tax_amounts = self.get_tax_amount(sales)
for sale in sales:
res[sale.id] = currency_obj.round(sale.currency,
untaxed_amounts[sale.id] + tax_amounts[sale.id])
return res
def get_invoice_paid(self, sales):
'''
Return if all invoices have been paid for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
a boolean as value
'''
res = {}
for sale in sales:
val = True
skip_ids = set(x.id for x in sale.invoices_ignored)
skip_ids.update(x.id for x in sale.invoices_recreated)
for invoice in sale.invoices:
if invoice.state != 'paid' \
and invoice.id not in skip_ids:
val = False
break
res[sale.id] = val
return res
def get_invoice_exception(self, sales):
'''
Return if there is an invoice exception for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
a boolean as value
'''
res = {}
for sale in sales:
val = False
skip_ids = set(x.id for x in sale.invoices_ignored)
skip_ids.update(x.id for x in sale.invoices_recreated)
for invoice in sale.invoices:
if invoice.state == 'cancel' \
and invoice.id not in skip_ids:
val = True
break
res[sale.id] = val
return res
def get_shipments(self, sales):
'''
Return shipment_out ids for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
a list of shipment_out id as value
'''
res = {}
for sale in sales:
res[sale.id] = []
for line in sale.lines:
for move in line.moves:
if move.shipment_out:
if move.shipment_out.id not in res[sale.id]:
res[sale.id].append(move.shipment_out.id)
return res
def get_moves(self, sales):
'''
Return move ids for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
a list of move ids as value
'''
res = {}
for sale in sales:
res[sale.id] = []
for line in sale.lines:
res[sale.id].extend([x.id for x in line.moves])
return res
def get_shipment_done(self, sales):
'''
Return if all the shipments have been done for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
a boolean as value
'''
res = {}
for sale in sales:
val = True
for line in sale.lines:
if not line.move_done:
val = False
break
res[sale.id] = val
return res
def get_shipment_exception(self, sales):
'''
Return if there is a shipment exception for each sales
:param sales: a BrowseRecordList of sales
:return: a dictionary with sale id as key and
a boolean as value
'''
res = {}
for sale in sales:
val = False
for line in sale.lines:
if line.move_exception:
val = True
break
res[sale.id] = val
return res
def check_method(self, ids):
'''
Check the methods.
'''
for sale in self.browse(ids):
if sale.invoice_method == 'shipment' \
and sale.shipment_method in ('invoice', 'manual'):
return False
if sale.shipment_method == 'invoice' \
and sale.invoice_method in ('shipment', 'manual'):
return False
return True
def get_rec_name(self, ids, name):
if not ids:
return []
res = {}
for sale in self.browse(ids):
res[sale.id] = sale.reference or str(sale.id) \
+ ' - ' + sale.party.rec_name
return res
def search_rec_name(self, name, clause):
names = clause[2].split(' - ', 1)
res = [('reference', clause[1], names[0])]
if len(names) != 1 and names[1]:
res.append(('party', clause[1], names[1]))
return res
def copy(self, ids, default=None):
if default is None:
default = {}
default = default.copy()
default['state'] = 'draft'
default['reference'] = False
default['invoice_state'] = 'none'
default['invoices'] = False
default['invoices_ignored'] = False
default['shipment_state'] = 'none'
return super(Sale, self).copy(ids, default=default)
def check_for_quotation(self, sale_id):
sale = self.browse(sale_id)
if not sale.invoice_address or not sale.shipment_address:
self.raise_user_error('addresses_required')
return True
def set_reference(self, sale_id):
'''
Fill the reference field with the sale sequence
:param sale_id: the id of the sale
:return: True if succeed
'''
sequence_obj = Pool().get('ir.sequence')
config_obj = Pool().get('sale.configuration')
sale = self.browse(sale_id)
if sale.reference:
return True
config = config_obj.browse(1)
reference = sequence_obj.get_id(config.sale_sequence.id)
self.write(sale_id, {
'reference': reference,
})
return True
def set_sale_date(self, sale_id):
date_obj = Pool().get('ir.date')
self.write(sale_id, {
'sale_date': date_obj.today(),
})
return True
def _get_invoice_line_sale_line(self, sale):
'''
Return invoice line values for each sale lines
:param sale: the BrowseRecord of the sale
:return: a dictionary with invoiced sale line id as key
and a list of invoice lines values as value
'''
line_obj = Pool().get('sale.line')
res = {}
for line in sale.lines:
val = line_obj.get_invoice_line(line)
if val:
res[line.id] = val
return res
def _get_invoice_sale(self, sale):
'''
Return invoice values for sale
:param sale: the BrowseRecord of the sale
:return: a dictionary with invoice fields as key and
invoice values as value
'''
journal_obj = Pool().get('account.journal')
journal_id = journal_obj.search([
('type', '=', 'revenue'),
], limit=1)
if journal_id:
journal_id = journal_id[0]
res = {
'company': sale.company.id,
'type': 'out_invoice',
'reference': sale.reference,
'journal': journal_id,
'party': sale.party.id,
'invoice_address': sale.invoice_address.id,
'currency': sale.currency.id,
'account': sale.party.account_receivable.id,
'payment_term': sale.payment_term.id,
}
return res
def create_invoice(self, sale_id):
'''
Create an invoice for the sale
:param sale_id: the sale id
:return: the created invoice id or None
'''
pool = Pool()
invoice_obj = pool.get('account.invoice')
invoice_line_obj = pool.get('account.invoice.line')
sale_line_obj = pool.get('sale.line')
sale = self.browse(sale_id)
if not sale.party.account_receivable:
self.raise_user_error('missing_account_receivable',
error_args=(sale.party.rec_name,))
invoice_lines = self._get_invoice_line_sale_line(sale)
if not invoice_lines:
return
vals = self._get_invoice_sale(sale)
with Transaction().set_user(0, set_context=True):
invoice_id = invoice_obj.create(vals)
for line in sale.lines:
if line.id not in invoice_lines:
continue
for vals in invoice_lines[line.id]:
vals['invoice'] = invoice_id
with Transaction().set_user(0, set_context=True):
invoice_line_id = invoice_line_obj.create(vals)
sale_line_obj.write(line.id, {
'invoice_lines': [('add', invoice_line_id)],
})
with Transaction().set_user(0, set_context=True):
invoice_obj.update_taxes([invoice_id])
self.write(sale_id, {
'invoices': [('add', invoice_id)],
})
return invoice_id
def _get_move_sale_line(self, sale):
'''
Return a dictionary of move values for each sale lines
:param sale: the BrowseRecord of the sale
:return: a dictionary with move as key and move values as value
'''
line_obj = Pool().get('sale.line')
res = {}
for line in sale.lines:
val = line_obj.get_move(line)
if val:
res[line.id] = val
return res
def _group_shipment_key(self, moves, move):
'''
The key to group moves by shipments
:param moves: a list of moves values
:param move: a tuple of line id and a dictionary of the move values
:return: a list of key-value as tuples of the shipment
'''
planned_date = max(m['planned_date'] for m in moves)
return (('planned_date', planned_date),)
def create_shipment(self, sale_id):
'''
Create a shipment for the sale
:param sale_id: the sale id
:return: the list of created shipment id or None
'''
pool = Pool()
shipment_obj = pool.get('stock.shipment.out')
move_obj = pool.get('stock.move')
sale_line_obj = pool.get('sale.line')
sale = self.browse(sale_id)
moves = self._get_move_sale_line(sale)
if not moves:
return
keyfunc = partial(self._group_shipment_key, moves.values())
moves = moves.items()
moves = sorted(moves, key=keyfunc)
shipments = []
with Transaction().set_user(0, set_context=True):
for key, grouped_moves in groupby(moves, key=keyfunc):
values = {
'customer': sale.party.id,
'delivery_address': sale.shipment_address.id,
'reference': sale.reference,
'warehouse': sale.warehouse.id,
'company': sale.company.id,
}
values.update(dict(key))
shipment_id = shipment_obj.create(values)
shipments.append(shipment_id)
for line_id, values in grouped_moves:
values['shipment_out'] = shipment_id
move_id = move_obj.create(values)
sale_line_obj.write(line_id, {
'moves': [('add', move_id)],
})
shipment_obj.workflow_trigger_validate(shipment_id, 'waiting')
return shipments
def wkf_draft(self, sale):
self.write(sale.id, {'state': 'draft'})
def wkf_quotation(self, sale):
self.check_for_quotation(sale.id)
self.set_reference(sale.id)
self.write(sale.id, {'state': 'quotation'})
def wkf_confirmed(self, sale):
self.set_sale_date(sale.id)
self.write(sale.id, {'state': 'confirmed'})
def wkf_waiting_invoice_sale(self, sale):
self.create_invoice(sale.id)
self.write(sale.id, {'invoice_state': 'waiting'})
def wkf_invoice_sale_exception(self, sale):
self.write(sale.id, {'invoice_state': 'exception'})
def wkf_invoice_sale_done(self, sale):
self.write(sale.id, {'invoice_state': 'paid'})
def wkf_shipment_invoice(self, sale):
self.create_shipment(sale.id)
def wkf_waiting_shipment_invoice(self, sale):
self.write(sale.id, {'shipment_state': 'waiting'})
self.create_shipment(sale.id)
def wkf_shipment_invoice_exception(self, sale):
self.write(sale.id, {'shipment_state': 'exception'})
def wkf_shipment_invoice_done(self, sale):
self.write(sale.id, {'shipment_state': 'sent'})
def wkf_shipment(self, sale):
self.create_shipment(sale.id)
def wkf_waiting_shipment(self, sale):
self.write(sale.id, {'shipment_state': 'waiting'})
self.create_shipment(sale.id)
def wkf_shipment_exception(self, sale):
self.write(sale.id, {'shipment_state': 'exception'})
def wkf_invoice_shipment(self, sale):
self.create_invoice(sale.id)
self.write(sale.id, {'invoice_state': 'waiting'})
def wkf_waiting_invoice_shipment(self, sale):
self.write(sale.id,
{'invoice_state': 'waiting', 'shipment_state': 'sent'})
def wkf_invoice_shipment_exception(self, sale):
self.write(sale.id, {'invoice_state': 'exception'})
def wkf_invoice_shipment_done(self, sale):
self.write(sale.id, {'invoice_state': 'paid'})
def wkf_invoice_shipment_method_done(self, sale):
self.write(sale.id, {'shipment_state': 'sent'})
def wkf_done(self, sale):
self.write(sale.id, {'state': 'done'})
def wkf_cancel(self, sale):
self.write(sale.id, {'state': 'cancel'})
def wkf_draft2quotation(self, sale):
return bool(sale.lines)
def wkf_invoice_method2waiting_invoice_sale(self, sale):
return sale.invoice_method == 'order'
def wkf_invoice_method2invoice_method_done(self, sale):
return sale.invoice_method != 'order'
def wkf_triggered_invoices(self, sale):
return [x.id for x in sale.invoices]
def wkf_waiting_invoice_sale2invoice_sale_exception(self, sale):
return sale.invoice_exception
def wkf_waiting_invoice_sale2invoice_sale_done(self, sale):
return sale.invoice_paid
def wkf_shipment_invoice_method2shipment_invoice_method_done(self, sale):
return sale.shipment_method != 'invoice'
def wkf_shipment_invoice_method2shipment_invoice(self, sale):
return self.shipment_method == 'invoice'
def wkf_triggered_shipments(self, sale):
return [x.id for x in sale.shipments]
def wkf_waiting_shipment_invoice2shipment_invoice_exception(self, sale):
return sale.shipment_exception
def wkf_waiting_shipment_invoice2shipment_invoice_done(self, sale):
return sale.shipment_done
def wkf_shipment_method2shipment_method_done(self, sale):
return sale.shipment_method != 'order'
def wkf_shipment_method2shipment(self, sale):
return sale.shipment_method == 'order'
def wkf_waiting_shipment2shipment_exception(self, sale):
return sale.shipment_exception
def wkf_waiting_shipment2invoice_shipment_method(self, sale):
return not sale.shipment_exception
def wkf_waiting_shipment2invoice_shipment_method_nosignal(self, sale):
return sale.shipment_done
def wkf_invoice_shipment_method2invoice_shipment(self, sale):
return sale.invoice_method == 'shipment'
def wkf_invoice_shipment_method2invoice_shipment_method_done(self, sale):
return sale.invoice_method != 'shipment' and sale.shipment_done
def wkf_invoice_shipment_method2waiting_shipment(self, sale):
return sale.invoice_method != 'shipment' and not sale.shipment_done
def wkf_invoice_shipment2waiting_shipment(self, sale):
return not sale.shipment_done
def wkf_invoice_shipment2waiting_invoice_shipment(self, sale):
return sale.shipment_done
def wkf_waiting_invoice_shipment2invoice_shipment_exception(self, sale):
return sale.invoice_exception
def wkf_waiting_invoice_shipment2invoice_shipment_done(self, sale):
return sale.invoice_paid
Sale()
class SaleInvoice(ModelSQL):
'Sale - Invoice'
_name = 'sale.sale-account.invoice'
_table = 'sale_invoices_rel'
_description = __doc__
sale = fields.Many2One('sale.sale', 'Sale', ondelete='CASCADE', select=1,
required=True)
invoice = fields.Many2One('account.invoice', 'Invoice',
ondelete='RESTRICT', select=1, required=True)
SaleInvoice()
class SaleIgnoredInvoice(ModelSQL):
'Sale - Ignored Invoice'
_name = 'sale.sale-ignored-account.invoice'
_table = 'sale_invoice_ignored_rel'
_description = __doc__
sale = fields.Many2One('sale.sale', 'Sale', ondelete='CASCADE', select=1,
required=True)
invoice = fields.Many2One('account.invoice', 'Invoice',
ondelete='RESTRICT', select=1, required=True)
SaleIgnoredInvoice()
class SaleRecreatedInvoice(ModelSQL):
'Sale - Recreated Invoice'
_name = 'sale.sale-recreated-account.invoice'
_table = 'sale_invoice_recreated_rel'
_description = __doc__
sale = fields.Many2One('sale.sale', 'Sale', ondelete='CASCADE', select=1,
required=True)
invoice = fields.Many2One('account.invoice', 'Invoice',
ondelete='RESTRICT', select=1, required=True)
SaleRecreatedInvoice()
class SaleLine(ModelSQL, ModelView):
'Sale Line'
_name = 'sale.line'
_rec_name = 'description'
_description = __doc__
sale = fields.Many2One('sale.sale', 'Sale', ondelete='CASCADE', select=1)
sequence = fields.Integer('Sequence')
type = fields.Selection([
('line', 'Line'),
('subtotal', 'Subtotal'),
('title', 'Title'),
('comment', 'Comment'),
], 'Type', select=1, required=True)
quantity = fields.Float('Quantity',
digits=(16, Eval('unit_digits', 2)),
states={
'invisible': Eval('type') != 'line',
'required': Eval('type') == 'line',
'readonly': ~Eval('_parent_sale', {}),
}, on_change=['product', 'quantity', 'unit',
'_parent_sale.currency', '_parent_sale.party'],
depends=['type', 'unit_digits'])
unit = fields.Many2One('product.uom', 'Unit',
states={
'required': Bool(Eval('product')),
'invisible': Eval('type') != 'line',
'readonly': ~Eval('_parent_sale', {}),
}, domain=[
('category', '=',
(Eval('product'), 'product.default_uom.category')),
],
context={
'category': (Eval('product'), 'product.default_uom.category'),
},
on_change=['product', 'quantity', 'unit', '_parent_sale.currency',
'_parent_sale.party'],
depends=['product', 'type'])
unit_digits = fields.Function(fields.Integer('Unit Digits',
on_change_with=['unit']), 'get_unit_digits')
product = fields.Many2One('product.product', 'Product',
domain=[('salable', '=', True)],
states={
'invisible': Eval('type') != 'line',
'readonly': ~Eval('_parent_sale', {}),
},
on_change=['product', 'unit', 'quantity', 'description',
'_parent_sale.party', '_parent_sale.currency'],
context={
'locations': If(Bool(Eval('_parent_sale', {}).get( 'warehouse')),
[Eval('_parent_sale', {}).get('warehouse', 0)], []),
'stock_date_end': Eval('_parent_sale', {}).get('sale_date'),
'salable': True,
'stock_skip_warehouse': True,
}, depends=['type'])
unit_price = fields.Numeric('Unit Price', digits=(16, 4),
states={
'invisible': Eval('type') != 'line',
'required': Eval('type') == 'line',
}, depends=['type'])
amount = fields.Function(fields.Numeric('Amount',
digits=(16, Eval('_parent_sale', {}).get('currency_digits', 2)),
states={
'invisible': ~Eval('type').in_(['line', 'subtotal']),
'readonly': ~Eval('_parent_sale'),
}, on_change_with=['type', 'quantity', 'unit_price',
'_parent_sale.currency'],
depends=['type']), 'get_amount')
description = fields.Text('Description', size=None, required=True)
note = fields.Text('Note')
taxes = fields.Many2Many('sale.line-account.tax', 'line', 'tax', 'Taxes',
domain=[('parent', '=', False)], states={
'invisible': Eval('type') != 'line',
}, depends=['type'])
invoice_lines = fields.Many2Many('sale.line-account.invoice.line',
'sale_line', 'invoice_line', 'Invoice Lines', readonly=True)
moves = fields.One2Many('stock.move', 'sale_line', 'Moves',
readonly=True)
moves_ignored = fields.Many2Many('sale.line-ignored-stock.move',
'sale_line', 'move', 'Ignored Moves', readonly=True)
moves_recreated = fields.Many2Many('sale.line-recreated-stock.move',
'sale_line', 'move', 'Recreated Moves', readonly=True)
move_done = fields.Function(fields.Boolean('Moves Done'), 'get_move_done')
move_exception = fields.Function(fields.Boolean('Moves Exception'),
'get_move_exception')
def __init__(self):
super(SaleLine, self).__init__()
self._order.insert(0, ('sequence', 'ASC'))
self._error_messages.update({
'customer_location_required': 'The customer location is required!',
'missing_account_revenue': 'It misses '
'an "Account Revenue" on product "%s"!',
'missing_account_revenue_property': 'It misses '
'an "account Revenue" default property!',
})
def init(self, module_name):
super(SaleLine, self).init(module_name)
cursor = Transaction().cursor
table = TableHandler(cursor, self, module_name)
# Migration from 1.0 comment change into note
if table.column_exist('comment'):
cursor.execute('UPDATE "' + self._table + '" SET note = comment')
table.drop_column('comment', exception=True)
def default_type(self):
return 'line'
def default_quantity(self):
return 0.0
def default_unit_price(self):
return Decimal('0.0')
def on_change_with_unit_digits(self, vals):
uom_obj = Pool().get('product.uom')
if vals.get('unit'):
uom = uom_obj.browse(vals['unit'])
return uom.digits
return 2
def get_unit_digits(self, ids, name):
res = {}
for line in self.browse(ids):
if line.unit:
res[line.id] = line.unit.digits
else:
res[line.id] = 2
return res
def get_move_done(self, ids, name):
uom_obj = Pool().get('product.uom')
res = {}
for line in self.browse(ids):
val = True
if not line.product:
res[line.id] = True
continue
if line.product.type == 'service':
res[line.id] = True
continue
skip_ids = set(x.id for x in line.moves_ignored)
skip_ids.update(x.id for x in line.moves_recreated)
quantity = line.quantity
for move in line.moves:
if move.state != 'done' \
and move.id not in skip_ids:
val = False
break
quantity -= uom_obj.compute_qty(move.uom, move.quantity,
line.unit)
if val:
if quantity > 0.0:
val = False
res[line.id] = val
return res
def get_move_exception(self, ids, name):
res = {}
for line in self.browse(ids):
val = False
skip_ids = set(x.id for x in line.moves_ignored)
skip_ids.update(x.id for x in line.moves_recreated)
for move in line.moves:
if move.state == 'cancel' \
and move.id not in skip_ids:
val = True
break
res[line.id] = val
return res
def _get_tax_rule_pattern(self, party, vals):
'''
Get tax rule pattern
:param party: the BrowseRecord of the party
:param vals: a dictionary with value from on_change
:return: a dictionary to use as pattern for tax rule
'''
res = {}
return res
def _get_context_sale_price(self, product, vals):
context = {}
if vals.get('_parent_sale.currency'):
context['currency'] = vals['_parent_sale.currency']
if vals.get('_parent_sale.party'):
context['customer'] = vals['_parent_sale.party']
if vals.get('_parent_sale.sale_date'):
context['sale_date'] = vals['_parent_sale.sale_date']
if vals.get('unit'):
context['uom'] = vals['unit']
else:
context['uom'] = product.sale_uom.id
return context
def on_change_product(self, vals):
pool = Pool()
party_obj = pool.get('party.party')
product_obj = pool.get('product.product')
uom_obj = pool.get('product.uom')
tax_rule_obj = pool.get('account.tax.rule')
if not vals.get('product'):
return {}
res = {}
party = None
party_context = {}
if vals.get('_parent_sale.party'):
party = party_obj.browse(vals['_parent_sale.party'])
if party.lang:
party_context['language'] = party.lang.code
product = product_obj.browse(vals['product'])
with Transaction().set_context(
self._get_context_sale_price(product,vals)):
res['unit_price'] = product_obj.get_sale_price([product.id],
vals.get('quantity', 0))[product.id]
if res['unit_price']:
res['unit_price'] = res['unit_price'].quantize(
Decimal(1) / 10 ** self.unit_price.digits[1])
res['taxes'] = []
pattern = self._get_tax_rule_pattern(party, vals)
for tax in product.customer_taxes_used:
if party and party.customer_tax_rule:
tax_ids = tax_rule_obj.apply(party.customer_tax_rule, tax,
pattern)
if tax_ids:
res['taxes'].extend(tax_ids)
continue
res['taxes'].append(tax.id)
if party and party.customer_tax_rule:
tax_ids = tax_rule_obj.apply(party.customer_tax_rule, False,
pattern)
if tax_ids:
res['taxes'].extend(tax_ids)
if not vals.get('description'):
with Transaction().set_context(party_context):
res['description'] = product_obj.browse(product.id).rec_name
category = product.sale_uom.category
if not vals.get('unit') \
or vals.get('unit') not in [x.id for x in category.uoms]:
res['unit'] = product.sale_uom.id
res['unit.rec_name'] = product.sale_uom.rec_name
res['unit_digits'] = product.sale_uom.digits
vals = vals.copy()
vals['unit_price'] = res['unit_price']
vals['type'] = 'line'
res['amount'] = self.on_change_with_amount(vals)
return res
def on_change_quantity(self, vals):
product_obj = Pool().get('product.product')
if not vals.get('product'):
return {}
res = {}
product = product_obj.browse(vals['product'])
with Transaction().set_context(
self._get_context_sale_price(product, vals)):
res['unit_price'] = product_obj.get_sale_price([vals['product']],
vals.get('quantity', 0))[vals['product']]
if res['unit_price']:
res['unit_price'] = res['unit_price'].quantize(
Decimal(1) / 10 ** self.unit_price.digits[1])
return res
def on_change_unit(self, vals):
return self.on_change_quantity(vals)
def on_change_with_amount(self, vals):
currency_obj = Pool().get('currency.currency')
if vals.get('type') == 'line':
currency = vals.get('_parent_sale.currency')
if currency and isinstance(currency, (int, long)):
currency = currency_obj.browse(vals['_parent_sale.currency'])
amount = Decimal(str(vals.get('quantity') or '0.0')) * \
(vals.get('unit_price') or Decimal('0.0'))
if currency:
return currency_obj.round(currency, amount)
return amount
return Decimal('0.0')
def get_amount(self, ids, name):
currency_obj = Pool().get('currency.currency')
res = {}
for line in self.browse(ids):
if line.type == 'line':
res[line.id] = currency_obj.round(line.sale.currency,
Decimal(str(line.quantity)) * line.unit_price)
elif line.type == 'subtotal':
res[line.id] = Decimal('0.0')
for line2 in line.sale.lines:
if line2.type == 'line':
res[line.id] += currency_obj.round(line2.sale.currency,
Decimal(str(line2.quantity)) *
line2.unit_price)
elif line2.type == 'subtotal':
if line.id == line2.id:
break
res[line.id] = Decimal('0.0')
else:
res[line.id] = Decimal('0.0')
return res
def get_invoice_line(self, line):
'''
Return invoice line values for sale line
:param line: the BrowseRecord of the line
:return: a list of invoice line values
'''
uom_obj = Pool().get('product.uom')
property_obj = Pool().get('ir.property')
res = {}
res['sequence'] = line.sequence
res['type'] = line.type
res['description'] = line.description
res['note'] = line.note
if line.type != 'line':
return [res]
if (line.sale.invoice_method == 'order'
or not line.product
or line.product.type == 'service'):
quantity = line.quantity
else:
quantity = 0.0
for move in line.moves:
if move.state == 'done':
quantity += uom_obj.compute_qty(move.uom, move.quantity,
line.unit)
ignored_ids = set(
l.id for i in line.sale.invoices_ignored for l in i.lines)
for invoice_line in line.invoice_lines:
if ((invoice_line.invoice and
invoice_line.invoice.state != 'cancel') or
invoice_line.id in ignored_ids):
quantity -= uom_obj.compute_qty(invoice_line.unit,
invoice_line.quantity, line.unit)
res['quantity'] = quantity
if res['quantity'] <= 0.0:
return []
res['unit'] = line.unit.id
res['product'] = line.product.id
res['unit_price'] = line.unit_price
res['taxes'] = [('set', [x.id for x in line.taxes])]
if line.product:
res['account'] = line.product.account_revenue_used.id
if not res['account']:
self.raise_user_error('missing_account_revenue',
error_args=(line.product.rec_name,))
else:
for model in ('product.template', 'product.category'):
res['account'] = property_obj.get('account_revenue', model)
if res['account']:
break
if not res['account']:
self.raise_user_error('missing_account_revenue_property')
return [res]
def copy(self, ids, default=None):
if default is None:
default = {}
default = default.copy()
default['moves'] = False
default['moves_ignored'] = False
default['moves_recreated'] = False
default['invoice_lines'] = False
return super(SaleLine, self).copy(ids, default=default)
def get_move(self, line):
'''
Return move values for the sale line
:param line: the BrowseRecord of the line
:return: a dictionary of values of move
'''
uom_obj = Pool().get('product.uom')
product_obj = Pool().get('product.product')
res = {}
if line.type != 'line':
return
if not line.product:
return
if line.product.type == 'service':
return
skip_ids = set(x.id for x in line.moves_recreated)
quantity = line.quantity
for move in line.moves:
if move.id not in skip_ids:
quantity -= uom_obj.compute_qty(move.uom, move.quantity,
line.unit)
if quantity <= 0.0:
return
if not line.sale.party.customer_location:
self.raise_user_error('customer_location_required')
res['quantity'] = quantity
res['uom'] = line.unit.id
res['product'] = line.product.id
res['from_location'] = line.sale.warehouse.output_location.id
res['to_location'] = line.sale.party.customer_location.id
res['state'] = 'draft'
res['company'] = line.sale.company.id
res['unit_price'] = line.unit_price
res['currency'] = line.sale.currency.id
res['planned_date'] = product_obj.compute_delivery_date(
line.product)
return res
SaleLine()
class SaleLineTax(ModelSQL):
'Sale Line - Tax'
_name = 'sale.line-account.tax'
_table = 'sale_line_account_tax'
_description = __doc__
line = fields.Many2One('sale.line', 'Sale Line', ondelete='CASCADE',
select=1, required=True)
tax = fields.Many2One('account.tax', 'Tax', ondelete='RESTRICT',
select=1, required=True)
SaleLineTax()
class SaleLineInvoiceLine(ModelSQL):
'Sale Line - Invoice Line'
_name = 'sale.line-account.invoice.line'
_table = 'sale_line_invoice_lines_rel'
_description = __doc__
sale_line = fields.Many2One('sale.line', 'Sale Line', ondelete='CASCADE',
select=1, required=True)
invoice_line = fields.Many2One('account.invoice.line', 'Invoice Line',
ondelete='RESTRICT', select=1, required=True)
SaleLineInvoiceLine()
class SaleLineIgnoredMove(ModelSQL):
'Sale Line - Ignored Move'
_name = 'sale.line-ignored-stock.move'
_table = 'sale_line_moves_ignored_rel'
_description = __doc__
sale_line = fields.Many2One('sale.line', 'Sale Line', ondelete='CASCADE',
select=1, required=True)
move = fields.Many2One('stock.move', 'Move', ondelete='RESTRICT',
select=1, required=True)
SaleLineIgnoredMove()
class SaleLineRecreatedMove(ModelSQL):
'Sale Line - Recreated Move'
_name = 'sale.line-recreated-stock.move'
_table = 'sale_line_moves_recreated_rel'
_description = __doc__
sale_line = fields.Many2One('sale.line', 'Sale Line', ondelete='CASCADE',
select=1, required=True)
move = fields.Many2One('stock.move', 'Move', ondelete='RESTRICT',
select=1, required=True)
SaleLineRecreatedMove()
class SaleReport(CompanyReport):
_name = 'sale.sale'
SaleReport()
class Template(ModelSQL, ModelView):
_name = 'product.template'
salable = fields.Boolean('Salable', states={
'readonly': ~Eval('active', True),
}, depends=['active'])
sale_uom = fields.Many2One('product.uom', 'Sale UOM', states={
'readonly': ~Eval('active', True),
'invisible': ~Eval('salable', False),
'required': Eval('salable', False),
},
domain=[
('category', '=', (Eval('default_uom'), 'uom.category')),
],
context={'category': (Eval('default_uom'), 'uom.category')},
on_change_with=['default_uom', 'sale_uom', 'salable'],
depends=['active', 'salable', 'default_uom'])
delivery_time = fields.Integer('Delivery Time', states={
'readonly': ~Eval('active', True),
'invisible': ~Eval('salable', False),
},
depends=['active', 'salable'],
help='In number of days')
def __init__(self):
super(Template, self).__init__()
self.account_revenue = copy.copy(self.account_revenue)
self.account_revenue.states = copy.copy(self.account_revenue.states)
required = ~Eval('account_category', False) & Eval('salable', False)
if not self.account_revenue.states.get('required'):
self.account_revenue.states['required'] = required
else:
self.account_revenue.states['required'] = (
self.account_revenue.states['required'] | required)
if 'account_category' not in self.account_revenue.depends:
self.account_revenue = copy.copy(self.account_revenue)
self.account_revenue.depends = \
copy.copy(self.account_revenue.depends)
self.account_revenue.depends.append('account_category')
if 'salable' not in self.account_revenue.depends:
self.account_revenue = copy.copy(self.account_revenue)
self.account_revenue.depends = \
copy.copy(self.account_revenue.depends)
self.account_revenue.depends.append('salable')
self._reset_columns()
def default_salable(self):
return True if Transaction().context.get('salable') else False
def on_change_with_sale_uom(self, vals):
uom_obj = Pool().get('product.uom')
res = False
if vals.get('default_uom'):
default_uom = uom_obj.browse(vals['default_uom'])
if vals.get('sale_uom'):
sale_uom = uom_obj.browse(vals['sale_uom'])
if default_uom.category.id == sale_uom.category.id:
res = sale_uom.id
else:
res = default_uom.id
else:
res = default_uom.id
return res
Template()
class Product(ModelSQL, ModelView):
_name = 'product.product'
def get_sale_price(self, ids, quantity=0):
'''
Return the sale price for product ids.
:param ids: the product ids
:param quantity: the quantity of the products
uom: the unit of measure
currency: the currency id for the returned price
:return: a dictionary with for each product ids keys the computed price
'''
pool = Pool()
uom_obj = pool.get('product.uom')
user_obj = pool.get('res.user')
currency_obj = pool.get('currency.currency')
date_obj = pool.get('ir.date')
today = date_obj.today()
res = {}
uom = None
if Transaction().context.get('uom'):
uom = uom_obj.browse(Transaction().context.get('uom'))
currency = None
if Transaction().context.get('currency'):
currency = currency_obj.browse(
Transaction().context.get('currency'))
user2 = user_obj.browse(Transaction().user)
for product in self.browse(ids):
res[product.id] = product.list_price
if uom:
res[product.id] = uom_obj.compute_price(
product.default_uom, res[product.id], uom)
if currency and user2.company:
if user2.company.currency.id != currency.id:
date = Transaction().context.get('sale_date') or today
with Transaction().set_context(date=date):
res[product.id] = currency_obj.compute(
user2.company.currency.id, res[product.id],
currency.id, round=False)
return res
def compute_delivery_date(self, product, date=None):
'''
Compute the delivery date for the Product at a the given date
'''
date_obj = Pool().get('ir.date')
if not date:
date = date_obj.today()
return date + datetime.timedelta(product.delivery_time)
Product()
class ShipmentOut(ModelSQL, ModelView):
_name = 'stock.shipment.out'
def __init__(self):
super(ShipmentOut, self).__init__()
self._error_messages.update({
'reset_move': 'You cannot reset to draft a move generated '
'by a sale.',
})
def write(self, ids, vals):
sale_obj = Pool().get('sale.sale')
sale_line_obj = Pool().get('sale.line')
res = super(ShipmentOut, self).write(ids, vals)
if 'state' in vals and vals['state'] in ('done', 'cancel'):
sale_ids = []
move_ids = []
if isinstance(ids, (int, long)):
ids = [ids]
for shipment in self.browse(ids):
move_ids.extend([x.id for x in shipment.outgoing_moves])
sale_line_ids = sale_line_obj.search([
('moves', 'in', move_ids),
])
if sale_line_ids:
for sale_line in sale_line_obj.browse(sale_line_ids):
if sale_line.sale.id not in sale_ids:
sale_ids.append(sale_line.sale.id)
sale_obj.workflow_trigger_validate(sale_ids, 'shipment_update')
return res
def button_draft(self, ids):
for shipment in self.browse(ids):
for move in shipment.outgoing_moves:
if move.state == 'cancel' and move.sale_line:
self.raise_user_error('reset_move')
return super(ShipmentOut, self).button_draft(ids)
ShipmentOut()
class Move(ModelSQL, ModelView):
_name = 'stock.move'
sale_line = fields.Many2One('sale.line', 'Sale Line', select=1,
states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
sale = fields.Function(fields.Many2One('sale.sale', 'Sale', select=1),
'get_sale', searcher='search_sale')
sale_exception_state = fields.Function(fields.Selection([
('', ''),
('ignored', 'Ignored'),
('recreated', 'Recreated'),
], 'Exception State'), 'get_sale_exception_state')
def get_sale(self, ids, name):
sale_obj = Pool().get('sale.sale')
res = {}
for move in self.browse(ids):
res[move.id] = False
if move.sale_line:
res[move.id] = move.sale_line.sale.id
return res
def search_sale(self, name, clause):
return [('sale_line.' + name,) + clause[1:]]
def get_sale_exception_state(self, ids, name):
res = {}.fromkeys(ids, '')
for move in self.browse(ids):
if not move.sale_line:
continue
if move.id in (x.id for x in move.sale_line.moves_recreated):
res[move.id] = 'recreated'
if move.id in (x.id for x in move.sale_line.moves_ignored):
res[move.id] = 'ignored'
return res
def write(self, ids, vals):
sale_obj = Pool().get('sale.sale')
sale_line_obj = Pool().get('sale.line')
res = super(Move, self).write(ids, vals)
if 'state' in vals and vals['state'] in ('cancel',):
if isinstance(ids, (int, long)):
ids = [ids]
sale_ids = set()
sale_line_ids = sale_line_obj.search([
('moves', 'in', ids),
])
if sale_line_ids:
for sale_line in sale_line_obj.browse(sale_line_ids):
sale_ids.add(sale_line.sale.id)
if sale_ids:
sale_obj.workflow_trigger_validate(list(sale_ids),
'shipment_update')
return res
def delete(self, ids):
sale_obj = Pool().get('sale.sale')
sale_line_obj = Pool().get('sale.line')
if isinstance(ids, (int, long)):
ids = [ids]
sale_ids = set()
sale_line_ids = sale_line_obj.search([
('moves', 'in', ids),
])
res = super(Move, self).delete(ids)
if sale_line_ids:
for sale_line in sale_line_obj.browse(sale_line_ids):
sale_ids.add(sale_line.sale.id)
if sale_ids:
sale_obj.workflow_trigger_validate(list(sale_ids),
'shipment_update')
return res
Move()
class Invoice(ModelSQL, ModelView):
_name = 'account.invoice'
sale_exception_state = fields.Function(fields.Selection([
('', ''),
('ignored', 'Ignored'),
('recreated', 'Recreated'),
], 'Exception State'), 'get_sale_exception_state')
def __init__(self):
super(Invoice, self).__init__()
self._error_messages.update({
'delete_sale_invoice': 'You can not delete invoices '
'that come from a sale!',
'reset_invoice_sale': 'You cannot reset to draft '
'an invoice generated by a sale.',
})
def button_draft(self, ids):
sale_obj = Pool().get('sale.sale')
sale_ids = sale_obj.search([
('invoices', 'in', ids),
])
if sale_ids:
self.raise_user_error('reset_invoice_sale')
return super(Invoice, self).button_draft(ids)
def get_sale_exception_state(self, ids, name):
sale_obj = Pool().get('sale.sale')
sale_ids = sale_obj.search([
('invoices', 'in', ids),
])
sales = sale_obj.browse(sale_ids)
recreated_ids = tuple(i.id for p in sales for i in p.invoices_recreated)
ignored_ids = tuple(i.id for p in sales for i in p.invoices_ignored)
res = {}.fromkeys(ids, '')
for invoice in self.browse(ids):
if invoice.id in recreated_ids:
res[invoice.id] = 'recreated'
elif invoice.id in ignored_ids:
res[invoice.id] = 'ignored'
return res
def delete(self, ids):
if not ids:
return True
if isinstance(ids, (int, long)):
ids = [ids]
Transaction().cursor.execute('SELECT id FROM sale_invoices_rel '
'WHERE invoice IN (' + ','.join(('%s',) * len(ids)) + ')',
ids)
if Transaction().cursor.fetchone():
self.raise_user_error('delete_sale_invoice')
return super(Invoice, self).delete(ids)
Invoice()
class OpenCustomer(Wizard):
'Open Customers'
_name = 'sale.open_customer'
states = {
'init': {
'result': {
'type': 'action',
'action': '_action_open',
'state': 'end',
},
},
}
def _action_open(self, datas):
pool = Pool()
model_data_obj = pool.get('ir.model.data')
act_window_obj = pool.get('ir.action.act_window')
wizard_obj = pool.get('ir.action.wizard')
act_window_id = model_data_obj.get_id('party', 'act_party_form')
res = act_window_obj.read(act_window_id)
Transaction().cursor.execute("SELECT DISTINCT(party) FROM sale_sale")
customer_ids = [line[0] for line in Transaction().cursor.fetchall()]
res['pyson_domain'] = PYSONEncoder().encode(
[('id', 'in', customer_ids)])
model_data_ids = model_data_obj.search([
('fs_id', '=', 'act_open_customer'),
('module', '=', 'sale'),
('inherit', '=', False),
], limit=1)
model_data = model_data_obj.browse(model_data_ids[0])
wizard = wizard_obj.browse(model_data.db_id)
res['name'] = wizard.name
return res
OpenCustomer()
class HandleShipmentExceptionAsk(ModelView):
'Shipment Exception Ask'
_name = 'sale.handle.shipment.exception.ask'
_description = __doc__
recreate_moves = fields.Many2Many(
'stock.move', None, None, 'Recreate Moves',
domain=[('id', 'in', Eval('domain_moves'))], depends=['domain_moves'])
domain_moves = fields.Many2Many(
'stock.move', None, None, 'Domain Moves')
def init(self, module_name):
cursor = Transaction().cursor
# Migration from 1.2: packing renamed into shipment
cursor.execute("UPDATE ir_model "
"SET model = REPLACE(model, 'packing', 'shipment') "
"WHERE model like '%%packing%%' AND module = %s",
(module_name,))
super(HandleShipmentExceptionAsk, self).init(module_name)
def default_recreate_moves(self):
return self.default_domain_moves()
def default_domain_moves(self):
sale_line_obj = Pool().get('sale.line')
active_id = Transaction().context.get('active_id')
if not active_id:
return []
line_ids = sale_line_obj.search([
('sale', '=', active_id),
])
lines = sale_line_obj.browse(line_ids)
domain_moves = []
for line in lines:
skip_ids = set(x.id for x in line.moves_ignored)
skip_ids.update(x.id for x in line.moves_recreated)
for move in line.moves:
if move.state == 'cancel' and move.id not in skip_ids:
domain_moves.append(move.id)
return domain_moves
HandleShipmentExceptionAsk()
class HandleShipmentException(Wizard):
'Handle Shipment Exception'
_name = 'sale.handle.shipment.exception'
states = {
'init': {
'actions': [],
'result': {
'type': 'form',
'object': 'sale.handle.shipment.exception.ask',
'state': [
('end', 'Cancel', 'tryton-cancel'),
('ok', 'Ok', 'tryton-ok', True),
],
},
},
'ok': {
'result': {
'type': 'action',
'action': '_handle_moves',
'state': 'end',
},
},
}
def _handle_moves(self, data):
pool = Pool()
sale_obj = pool.get('sale.sale')
sale_line_obj = pool.get('sale.line')
move_obj = pool.get('stock.move')
shipment_obj = pool.get('stock.shipment.out')
to_recreate = data['form']['recreate_moves'][0][1]
domain_moves = data['form']['domain_moves'][0][1]
sale = sale_obj.browse(data['id'])
for line in sale.lines:
moves_ignored = []
moves_recreated = []
skip_ids = set(x.id for x in line.moves_ignored)
skip_ids.update(x.id for x in line.moves_recreated)
for move in line.moves:
if move.id not in domain_moves or move.id in skip_ids:
continue
if move.id in to_recreate:
moves_recreated.append(move.id)
else:
moves_ignored.append(move.id)
sale_line_obj.write(line.id,{
'moves_ignored': [('add', moves_ignored)],
'moves_recreated': [('add', moves_recreated)],
})
sale_obj.workflow_trigger_validate(data['id'], 'shipment_ok')
HandleShipmentException()
class HandleInvoiceExceptionAsk(ModelView):
'Invoice Exception Ask'
_name = 'sale.handle.invoice.exception.ask'
_description = __doc__
recreate_invoices = fields.Many2Many(
'account.invoice', None, None, 'Recreate Invoices',
domain=[('id', 'in', Eval('domain_invoices'))],
depends=['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')
def default_recreate_invoices(self):
return self.default_domain_invoices()
def default_domain_invoices(self):
sale_obj = Pool().get('sale.sale')
active_id = Transaction().context.get('active_id')
if not active_id:
return []
sale = sale_obj.browse(active_id)
skip_ids = set(x.id for x in sale.invoices_ignored)
skip_ids.update(x.id for x in sale.invoices_recreated)
domain_invoices = []
for invoice in sale.invoices:
if invoice.state == 'cancel' and invoice.id not in skip_ids:
domain_invoices.append(invoice.id)
return domain_invoices
HandleInvoiceExceptionAsk()
class HandleInvoiceException(Wizard):
'Handle Invoice Exception'
_name = 'sale.handle.invoice.exception'
states = {
'init': {
'actions': [],
'result': {
'type': 'form',
'object': 'sale.handle.invoice.exception.ask',
'state': [
('end', 'Cancel', 'tryton-cancel'),
('ok', 'Ok', 'tryton-ok', True),
],
},
},
'ok': {
'result': {
'type': 'action',
'action': '_handle_invoices',
'state': 'end',
},
},
}
def _handle_invoices(self, data):
sale_obj = Pool().get('sale.sale')
invoice_obj = Pool().get('account.invoice')
to_recreate = data['form']['recreate_invoices'][0][1]
domain_invoices = data['form']['domain_invoices'][0][1]
sale = sale_obj.browse(data['id'])
skip_ids = set(x.id for x in sale.invoices_ignored)
skip_ids.update(x.id for x in sale.invoices_recreated)
invoices_ignored = []
invoices_recreated = []
for invoice in sale.invoices:
if invoice.id not in domain_invoices or invoice.id in skip_ids:
continue
if invoice.id in to_recreate:
invoices_recreated.append(invoice.id)
else:
invoices_ignored.append(invoice.id)
sale_obj.write(sale.id,{
'invoices_ignored': [('add', invoices_ignored)],
'invoices_recreated': [('add', invoices_recreated)],
})
sale_obj.workflow_trigger_validate(data['id'], 'invoice_ok')
HandleInvoiceException()
|