/usr/share/pyshared/trytond/modules/sale/sale.py is in tryton-modules-sale 3.0.0-2.
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 | #This file is part of Tryton. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
from decimal import Decimal
from itertools import groupby, chain
from functools import partial
from sql import Table
from sql.functions import Overlay, Position
from sql.operators import Concat
from trytond.model import Workflow, ModelView, ModelSQL, fields
from trytond.modules.company import CompanyReport
from trytond.wizard import Wizard, StateAction, StateView, StateTransition, \
Button
from trytond import backend
from trytond.pyson import If, Eval, Bool, PYSONEncoder, Id
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Sale', 'SaleInvoice', 'SaleIgnoredInvoice', 'SaleRecreatedInvoice',
'SaleLine', 'SaleLineTax', 'SaleLineIgnoredMove',
'SaleLineRecreatedMove', 'SaleReport', 'OpenCustomer',
'HandleShipmentExceptionAsk', 'HandleShipmentException',
'HandleInvoiceExceptionAsk', 'HandleInvoiceException',
'ReturnSaleStart', 'ReturnSale']
__metaclass__ = PoolMeta
_ZERO = Decimal(0)
class Sale(Workflow, ModelSQL, ModelView):
'Sale'
__name__ = 'sale.sale'
_rec_name = 'reference'
company = fields.Many2One('company.company', 'Company', required=True,
states={
'readonly': (Eval('state') != 'draft') | Eval('lines', [0]),
},
domain=[
('id', If(Eval('context', {}).contains('company'), '=', '!='),
Eval('context', {}).get('company', -1)),
],
depends=['state'], select=True)
reference = fields.Char('Reference', readonly=True, select=True)
description = fields.Char('Description',
states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
state = fields.Selection([
('draft', 'Draft'),
('quotation', 'Quotation'),
('confirmed', 'Confirmed'),
('processing', 'Processing'),
('done', 'Done'),
('cancel', 'Canceled'),
], 'State', readonly=True, required=True)
sale_date = fields.Date('Sale Date',
states={
'readonly': ~Eval('state').in_(['draft', 'quotation']),
'required': ~Eval('state').in_(['draft', 'quotation', 'cancel']),
},
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', required=True, select=True,
states={
'readonly': Eval('state') != 'draft',
}, on_change=['party', 'payment_term'],
depends=['state'])
party_lang = fields.Function(fields.Char('Party Language',
on_change_with=['party']), 'on_change_with_party_lang')
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')], states={
'readonly': Eval('state') != 'draft',
},
depends=['state'])
currency = fields.Many2One('currency.currency', 'Currency', required=True,
states={
'readonly': (Eval('state') != 'draft') |
(Eval('lines', [0]) & Eval('currency', 0)),
},
depends=['state'])
currency_digits = fields.Function(fields.Integer('Currency Digits',
on_change_with=['currency']), 'on_change_with_currency_digits')
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_amount')
untaxed_amount_cache = fields.Numeric('Untaxed Cache',
digits=(16, Eval('currency_digits', 2)),
readonly=True,
depends=['currency_digits'])
tax_amount = fields.Function(fields.Numeric('Tax',
digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits']), 'get_amount')
tax_amount_cache = fields.Numeric('Tax Cache',
digits=(16, Eval('currency_digits', 2)),
readonly=True,
depends=['currency_digits'])
total_amount = fields.Function(fields.Numeric('Total',
digits=(16, Eval('currency_digits', 2)),
depends=['currency_digits']), 'get_amount')
total_amount_cache = fields.Numeric('Total Tax',
digits=(16, Eval('currency_digits', 2)),
readonly=True,
depends=['currency_digits'])
invoice_method = fields.Selection([
('manual', 'Manual'),
('order', 'On Order Processed'),
('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)
shipment_method = fields.Selection([
('manual', 'Manual'),
('order', 'On Order Processed'),
('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_shipments', searcher='search_shipments')
shipment_returns = fields.Function(
fields.One2Many('stock.shipment.out.return', None, 'Shipment Returns'),
'get_shipment_returns', searcher='search_shipment_returns')
moves = fields.Function(fields.One2Many('stock.move', None, 'Moves'),
'get_moves')
@classmethod
def __setup__(cls):
super(Sale, cls).__setup__()
cls._order.insert(0, ('sale_date', 'DESC'))
cls._order.insert(1, ('id', 'DESC'))
cls._error_messages.update({
'invalid_method': ('Invalid combination of shipment and '
'invoicing methods on sale "%s".'),
'addresses_required': (
'Invoice and Shipment addresses must be '
'defined for the quotation of sale "%s".'),
'warehouse_required': ('Warehouse must be defined for the '
'quotation of sale "%s".'),
'missing_account_receivable': ('It misses '
'an "Account Receivable" on the party "%s".'),
'delete_cancel': ('Sale "%s" must be cancelled before '
'deletion.'),
})
cls._transitions |= set((
('draft', 'quotation'),
('quotation', 'confirmed'),
('confirmed', 'processing'),
('processing', 'processing'),
('draft', 'cancel'),
('quotation', 'cancel'),
('quotation', 'draft'),
('cancel', 'draft'),
))
cls._buttons.update({
'cancel': {
'invisible': ~Eval('state').in_(['draft', 'quotation']),
},
'draft': {
'invisible': ~Eval('state').in_(['cancel', 'quotation']),
'icon': If(Eval('state') == 'cancel', 'tryton-clear',
'tryton-go-previous'),
},
'quote': {
'invisible': Eval('state') != 'draft',
'readonly': ~Eval('lines', []),
},
'confirm': {
'invisible': Eval('state') != 'quotation',
},
'process': {
'invisible': Eval('state') != 'confirmed',
},
'handle_invoice_exception': {
'invisible': ((Eval('invoice_state') != 'exception')
| (Eval('state') == 'cancel')),
'readonly': ~Eval('groups', []).contains(
Id('sale', 'group_sale')),
},
'handle_shipment_exception': {
'invisible': ((Eval('shipment_state') != 'exception')
| (Eval('state') == 'cancel')),
'readonly': ~Eval('groups', []).contains(
Id('sale', 'group_sale')),
},
})
# The states where amounts are cached
cls._states_cached = ['confirmed', 'processing', 'done', 'cancel']
@classmethod
def __register__(cls, module_name):
pool = Pool()
SaleLine = pool.get('sale.line')
TableHandler = backend.get('TableHandler')
sale_line_invoice_line_table_name = 'sale_line_invoice_lines_rel'
Move = pool.get('stock.move')
cursor = Transaction().cursor
model_data = Table('ir_model_data')
model_field = Table('ir_model_field')
sql_table = cls.__table__()
# Migration from 1.2: packing renamed into shipment
cursor.execute(*model_data.update(
columns=[model_data.fs_id],
values=[Overlay(model_data.fs_id, 'shipment',
Position('packing', model_data.fs_id),
len('packing'))],
where=model_data.fs_id.like('%packing%')
& (model_data.module == module_name)))
cursor.execute(*model_field.update(
columns=[model_field.relation],
values=[Overlay(model_field.relation, 'shipment',
Position('packing', model_field.relation),
len('packing'))],
where=model_field.relation.like('%packing%')
& (model_field.module == module_name)))
cursor.execute(*model_field.update(
columns=[model_field.name],
values=[Overlay(model_field.name, 'shipment',
Position('packing', model_field.name),
len('packing'))],
where=model_field.name.like('%packing%')
& (model_field.module == module_name)))
table = TableHandler(cursor, cls, 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, cls).__register__(module_name)
# Migration from 1.2
cursor.execute(*sql_table.update(
columns=[sql_table.invoice_method],
values=['shipment'],
where=sql_table.invoice_method == 'packing'))
table = TableHandler(cursor, cls, module_name)
# Migration from 2.2
table.not_null_action('sale_date', 'remove')
# state confirmed splitted into confirmed and processing
if (TableHandler.table_exist(cursor, SaleLine._table)
and TableHandler.table_exist(cursor,
sale_line_invoice_line_table_name)
and TableHandler.table_exist(cursor, Move._table)):
sale_line = SaleLine.__table__()
sale_line_invoice_line = \
Table(sale_line_invoice_line_table_name)
move = Move.__table__()
# Wrap subquery inside an other inner subquery because MySQL syntax
# doesn't allow update a table and select from the same table in a
# subquery.
sub_query = sql_table.join(sale_line,
condition=sale_line.sale == sql_table.id
).join(sale_line_invoice_line, 'LEFT',
condition=sale_line_invoice_line.sale_line == sale_line.id
).join(move, 'LEFT',
condition=(move.origin == Concat(SaleLine.__name__,
sale_line.id))
).select(sql_table.id,
where=(sql_table.state == 'confirmed')
& ((sale_line_invoice_line.id != None)
| (move.id != None)))
cursor.execute(*sql_table.update(
columns=[sql_table.state],
values=['processing'],
where=sql_table.id.in_(sub_query.select(sub_query.id))))
# Add index on create_date
table = TableHandler(cursor, cls, module_name)
table.index_action('create_date', action='add')
@classmethod
def default_payment_term(cls):
PaymentTerm = Pool().get('account.invoice.payment_term')
payment_terms = PaymentTerm.search(cls.payment_term.domain)
if len(payment_terms) == 1:
return payment_terms[0].id
@classmethod
def default_warehouse(cls):
Location = Pool().get('stock.location')
locations = Location.search(cls.warehouse.domain)
if len(locations) == 1:
return locations[0].id
@staticmethod
def default_company():
return Transaction().context.get('company')
@staticmethod
def default_state():
return 'draft'
@staticmethod
def default_currency():
Company = Pool().get('company.company')
company = Transaction().context.get('company')
if company:
return Company(company).currency.id
@staticmethod
def default_currency_digits():
Company = Pool().get('company.company')
company = Transaction().context.get('company')
if company:
return Company(company).currency.digits
return 2
@staticmethod
def default_invoice_method():
Config = Pool().get('sale.configuration')
config = Config(1)
return config.sale_invoice_method
@staticmethod
def default_invoice_state():
return 'none'
@staticmethod
def default_shipment_method():
Config = Pool().get('sale.configuration')
config = Config(1)
return config.sale_shipment_method
@staticmethod
def default_shipment_state():
return 'none'
def on_change_party(self):
invoice_address = None
shipment_address = None
payment_term = None
if self.party:
invoice_address = self.party.address_get(type='invoice')
shipment_address = self.party.address_get(type='delivery')
if self.party.customer_payment_term:
payment_term = self.party.customer_payment_term
changes = {}
if invoice_address:
changes['invoice_address'] = invoice_address.id
changes['invoice_address.rec_name'] = invoice_address.rec_name
else:
changes['invoice_address'] = None
if shipment_address:
changes['shipment_address'] = shipment_address.id
changes['shipment_address.rec_name'] = shipment_address.rec_name
else:
changes['shipment_address'] = None
if payment_term:
changes['payment_term'] = payment_term.id
changes['payment_term.rec_name'] = payment_term.rec_name
else:
changes['payment_term'] = self.default_payment_term()
return changes
def on_change_with_currency_digits(self, name=None):
if self.currency:
return self.currency.digits
return 2
def get_tax_context(self):
res = {}
if self.party and self.party.lang:
res['language'] = self.party.lang.code
return res
def on_change_with_party_lang(self, name=None):
Config = Pool().get('ir.configuration')
if self.party and self.party.lang:
return self.party.lang.code
return Config.get_language()
def on_change_lines(self):
pool = Pool()
Tax = pool.get('account.tax')
Invoice = pool.get('account.invoice')
res = {
'untaxed_amount': Decimal('0.0'),
'tax_amount': Decimal('0.0'),
'total_amount': Decimal('0.0'),
}
if self.lines:
taxes = {}
for line in self.lines:
if getattr(line, 'type', 'line') != 'line':
continue
res['untaxed_amount'] += line.amount or Decimal(0)
tax_list = ()
with Transaction().set_context(self.get_tax_context()):
tax_list = Tax.compute(getattr(line, 'taxes', []),
line.unit_price or Decimal('0.0'),
line.quantity or 0.0)
for tax in tax_list:
key, val = Invoice._compute_tax(tax, 'out_invoice')
if not key in taxes:
taxes[key] = val['amount']
else:
taxes[key] += val['amount']
if self.currency:
for key in taxes:
res['tax_amount'] += self.currency.round(taxes[key])
if self.currency:
res['untaxed_amount'] = self.currency.round(res['untaxed_amount'])
res['tax_amount'] = self.currency.round(res['tax_amount'])
res['total_amount'] = res['untaxed_amount'] + res['tax_amount']
if self.currency:
res['total_amount'] = self.currency.round(res['total_amount'])
return res
def get_tax_amount(self):
pool = Pool()
Tax = pool.get('account.tax')
Invoice = pool.get('account.invoice')
context = self.get_tax_context()
taxes = {}
for line in self.lines:
if line.type != 'line':
continue
with Transaction().set_context(context):
tax_list = Tax.compute(line.taxes, line.unit_price,
line.quantity)
# Don't round on each line to handle rounding error
for tax in tax_list:
key, val = Invoice._compute_tax(tax, 'out_invoice')
if not key in taxes:
taxes[key] = val['amount']
else:
taxes[key] += val['amount']
return sum((self.currency.round(tax) for tax in taxes.values()), _ZERO)
@classmethod
def get_amount(cls, sales, names):
untaxed_amount = {}
tax_amount = {}
total_amount = {}
for sale in sales:
if (sale.state in cls._states_cached
and sale.untaxed_amount_cache is not None
and sale.tax_amount_cache is not None
and sale.total_amount_cache is not None):
untaxed_amount[sale.id] = sale.untaxed_amount_cache
tax_amount[sale.id] = sale.tax_amount_cache
total_amount[sale.id] = sale.total_amount_cache
else:
untaxed_amount[sale.id] = sum(
(line.amount for line in sale.lines
if line.type == 'line'), _ZERO)
tax_amount[sale.id] = sale.get_tax_amount()
total_amount[sale.id] = (
untaxed_amount[sale.id] + tax_amount[sale.id])
result = {
'untaxed_amount': untaxed_amount,
'tax_amount': tax_amount,
'total_amount': total_amount,
}
for key in result.keys():
if key not in names:
del result[key]
return result
def get_invoice_state(self):
'''
Return the invoice state for the sale.
'''
skip_ids = set(x.id for x in self.invoices_ignored)
skip_ids.update(x.id for x in self.invoices_recreated)
invoices = [i for i in self.invoices if i.id not in skip_ids]
if invoices:
if any(i.state == 'cancel' for i in invoices):
return 'exception'
elif all(i.state == 'paid' for i in invoices):
return 'paid'
else:
return 'waiting'
return 'none'
def set_invoice_state(self):
'''
Set the invoice state.
'''
state = self.get_invoice_state()
if self.invoice_state != state:
self.write([self], {
'invoice_state': state,
})
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
get_shipments = get_shipments_returns('stock.shipment.out')
get_shipment_returns = get_shipments_returns('stock.shipment.out.return')
def search_shipments_returns(model_name):
'''
Search on shipments or returns
'''
def method(self, name, clause):
return [('lines.moves.shipment.id',) + tuple(clause[1:])
+ (model_name,)]
return classmethod(method)
search_shipments = search_shipments_returns('stock.shipment.out')
search_shipment_returns = search_shipments_returns(
'stock.shipment.out.return')
def get_moves(self, name):
return [m.id for l in self.lines for m in l.moves]
def get_shipment_state(self):
'''
Return the shipment state for the sale.
'''
if self.moves:
if any(l.move_exception for l in self.lines):
return 'exception'
elif all(l.move_done for l in self.lines):
return 'sent'
else:
return 'waiting'
return 'none'
def set_shipment_state(self):
'''
Set the shipment state.
'''
state = self.get_shipment_state()
if self.shipment_state != state:
self.write([self], {
'shipment_state': state,
})
@classmethod
def validate(cls, sales):
super(Sale, cls).validate(sales)
for sale in sales:
sale.check_method()
def check_method(self):
'''
Check the methods.
'''
if (self.invoice_method == 'shipment'
and self.shipment_method in ('invoice', 'manual')):
self.raise_user_error('invalid_method', (self.rec_name,))
if (self.shipment_method == 'invoice'
and self.invoice_method in ('shipment', 'manual')):
self.raise_user_error('invalid_method', (self.rec_name,))
def get_rec_name(self, name):
return (self.reference or str(self.id)
+ ' - ' + self.party.rec_name)
@classmethod
def search_rec_name(cls, 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
@classmethod
def copy(cls, sales, default=None):
if default is None:
default = {}
default = default.copy()
default['state'] = 'draft'
default['reference'] = None
default['invoice_state'] = 'none'
default['invoices'] = None
default['invoices_ignored'] = None
default['shipment_state'] = 'none'
default.setdefault('sale_date', None)
return super(Sale, cls).copy(sales, default=default)
def check_for_quotation(self):
if not self.invoice_address or not self.shipment_address:
self.raise_user_error('addresses_required', (self.rec_name,))
for line in self.lines:
if line.quantity >= 0:
location = line.from_location
else:
location = line.to_location
if ((not location or not line.warehouse)
and line.product
and line.product.type in ('goods', 'assets')):
self.raise_user_error('warehouse_required',
(self.rec_name,))
@classmethod
def set_reference(cls, sales):
'''
Fill the reference field with the sale sequence
'''
pool = Pool()
Sequence = pool.get('ir.sequence')
Config = pool.get('sale.configuration')
config = Config(1)
for sale in sales:
if sale.reference:
continue
reference = Sequence.get_id(config.sale_sequence.id)
cls.write([sale], {
'reference': reference,
})
@classmethod
def set_sale_date(cls, sales):
Date = Pool().get('ir.date')
for sale in sales:
if not sale.sale_date:
cls.write([sale], {
'sale_date': Date.today(),
})
@classmethod
def store_cache(cls, sales):
for sale in sales:
cls.write([sale], {
'untaxed_amount_cache': sale.untaxed_amount,
'tax_amount_cache': sale.tax_amount,
'total_amount_cache': sale.total_amount,
})
def _get_invoice_line_sale_line(self, invoice_type):
'''
Return invoice line for each sale lines according to invoice_type
'''
res = {}
for line in self.lines:
val = line.get_invoice_line(invoice_type)
if val:
res[line.id] = val
return res
def _get_invoice_sale(self, invoice_type):
'''
Return invoice of type invoice_type
'''
pool = Pool()
Invoice = pool.get('account.invoice')
Journal = pool.get('account.journal')
journals = Journal.search([
('type', '=', 'revenue'),
], limit=1)
if journals:
journal, = journals
else:
journal = None
with Transaction().set_user(0, set_context=True):
return Invoice(
company=self.company,
type=invoice_type,
journal=journal,
party=self.party,
invoice_address=self.invoice_address,
currency=self.currency,
account=self.party.account_receivable,
payment_term=self.payment_term,
)
def create_invoice(self, invoice_type):
'''
Create and return an invoice of type invoice_type
'''
pool = Pool()
Invoice = pool.get('account.invoice')
if self.invoice_method == 'manual':
return
if not self.party.account_receivable:
self.raise_user_error('missing_account_receivable',
(self.party.rec_name,))
invoice_lines = self._get_invoice_line_sale_line(invoice_type)
if not invoice_lines:
return
invoice = self._get_invoice_sale(invoice_type)
invoice.lines = ((list(invoice.lines)
if hasattr(invoice, 'lines') else [])
+ list(chain.from_iterable(invoice_lines.itervalues())))
invoice.save()
with Transaction().set_user(0, set_context=True):
Invoice.update_taxes([invoice])
self.write([self], {
'invoices': [('add', [invoice.id])],
})
return invoice
def _get_move_sale_line(self, shipment_type):
'''
Return move for each sale lines of the right shipment_type
'''
res = {}
for line in self.lines:
val = line.get_move(shipment_type)
if val:
res[line.id] = val
return res
def _group_shipment_key(self, moves, move):
'''
The key to group moves by shipments
move is a tuple of line id and a move
'''
SaleLine = Pool().get('sale.line')
line_id, move = move
line = SaleLine(line_id)
planned_date = max(m.planned_date for m in moves)
return (
('planned_date', planned_date),
('warehouse', line.warehouse.id),
)
_group_return_key = _group_shipment_key
def create_shipment(self, shipment_type):
'''
Create and return shipments of type shipment_type
'''
pool = Pool()
if self.shipment_method == 'manual':
return
moves = self._get_move_sale_line(shipment_type)
if not moves:
return
if shipment_type == 'out':
keyfunc = partial(self._group_shipment_key, moves.values())
Shipment = pool.get('stock.shipment.out')
elif shipment_type == 'return':
keyfunc = partial(self._group_return_key, moves.values())
Shipment = pool.get('stock.shipment.out.return')
moves = moves.items()
moves = sorted(moves, key=keyfunc)
shipments = []
for key, grouped_moves in groupby(moves, key=keyfunc):
values = {
'customer': self.party.id,
'delivery_address': self.shipment_address.id,
'company': self.company.id,
}
values.update(dict(key))
with Transaction().set_user(0, set_context=True):
shipment = Shipment(**values)
shipment.moves = [x[1] for x in grouped_moves]
shipment.save()
shipments.append(shipment)
if shipment_type == 'out':
with Transaction().set_user(0, set_context=True):
Shipment.wait(shipments)
return shipments
def is_done(self):
return ((self.invoice_state == 'paid'
or self.invoice_method == 'manual')
and (self.shipment_state == 'sent'
or self.shipment_method == 'manual'))
@classmethod
def delete(cls, sales):
# Cancel before delete
cls.cancel(sales)
for sale in sales:
if sale.state != 'cancel':
cls.raise_user_error('delete_cancel', (sale.rec_name,))
super(Sale, cls).delete(sales)
@classmethod
@ModelView.button
@Workflow.transition('cancel')
def cancel(cls, sales):
cls.store_cache(sales)
@classmethod
@ModelView.button
@Workflow.transition('draft')
def draft(cls, sales):
pass
@classmethod
@ModelView.button
@Workflow.transition('quotation')
def quote(cls, sales):
for sale in sales:
sale.check_for_quotation()
cls.set_reference(sales)
@classmethod
@ModelView.button
@Workflow.transition('confirmed')
def confirm(cls, sales):
cls.set_sale_date(sales)
cls.store_cache(sales)
@classmethod
@ModelView.button_action('sale.wizard_invoice_handle_exception')
def handle_invoice_exception(cls, sales):
pass
@classmethod
@ModelView.button_action('sale.wizard_shipment_handle_exception')
def handle_shipment_exception(cls, sales):
pass
@classmethod
@ModelView.button
@Workflow.transition('processing')
def process(cls, sales):
done = []
for sale in sales:
if sale.state in ('done', 'cancel'):
continue
sale.create_invoice('out_invoice')
sale.create_invoice('out_credit_note')
sale.set_invoice_state()
sale.create_shipment('out')
sale.create_shipment('return')
sale.set_shipment_state()
if sale.is_done():
done.append(sale)
if done:
cls.write(done, {
'state': 'done',
})
class SaleInvoice(ModelSQL):
'Sale - Invoice'
__name__ = 'sale.sale-account.invoice'
_table = 'sale_invoices_rel'
sale = fields.Many2One('sale.sale', 'Sale', ondelete='CASCADE',
select=True, required=True)
invoice = fields.Many2One('account.invoice', 'Invoice',
ondelete='RESTRICT', select=True, required=True)
class SaleIgnoredInvoice(ModelSQL):
'Sale - Ignored Invoice'
__name__ = 'sale.sale-ignored-account.invoice'
_table = 'sale_invoice_ignored_rel'
sale = fields.Many2One('sale.sale', 'Sale', ondelete='CASCADE',
select=True, required=True)
invoice = fields.Many2One('account.invoice', 'Invoice',
ondelete='RESTRICT', select=True, required=True)
class SaleRecreatedInvoice(ModelSQL):
'Sale - Recreated Invoice'
__name__ = 'sale.sale-recreated-account.invoice'
_table = 'sale_invoice_recreated_rel'
sale = fields.Many2One('sale.sale', 'Sale', ondelete='CASCADE',
select=True, required=True)
invoice = fields.Many2One('account.invoice', 'Invoice',
ondelete='RESTRICT', select=True, required=True)
class SaleLine(ModelSQL, ModelView):
'Sale Line'
__name__ = 'sale.line'
_rec_name = 'description'
sale = fields.Many2One('sale.sale', 'Sale', ondelete='CASCADE',
select=True)
sequence = fields.Integer('Sequence')
type = fields.Selection([
('line', 'Line'),
('subtotal', 'Subtotal'),
('title', 'Title'),
('comment', 'Comment'),
], 'Type', select=True, 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',
'_parent_sale.sale_date'],
depends=['type', 'unit_digits'])
unit = fields.Many2One('product.uom', 'Unit',
states={
'required': Bool(Eval('product')),
'invisible': Eval('type') != 'line',
'readonly': ~Eval('_parent_sale', {}),
},
domain=[
If(Bool(Eval('product_uom_category')),
('category', '=', Eval('product_uom_category')),
('category', '!=', -1)),
],
on_change=['product', 'quantity', 'unit', '_parent_sale.currency',
'_parent_sale.party'],
depends=['product', 'type', 'product_uom_category'])
unit_digits = fields.Function(fields.Integer('Unit Digits',
on_change_with=['unit']), 'on_change_with_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',
'_parent_sale.sale_date'],
context={
'locations': If(Bool(Eval('_parent_sale', {}).get('warehouse')),
[Eval('_parent_sale', {}).get('warehouse', 0)], []),
'stock_date_end': Eval('_parent_sale', {}).get('sale_date'),
'stock_skip_warehouse': True,
}, depends=['type'])
product_uom_category = fields.Function(
fields.Many2One('product.uom.category', 'Product Uom Category',
on_change_with=['product']),
'on_change_with_product_uom_category')
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', 'unit',
'_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', '=', None), ['OR',
('group', '=', None),
('group.kind', 'in', ['sale', 'both'])],
],
states={
'invisible': Eval('type') != 'line',
}, depends=['type'])
invoice_lines = fields.One2Many('account.invoice.line', 'origin',
'Invoice Lines', readonly=True)
moves = fields.One2Many('stock.move', 'origin', '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')
warehouse = fields.Function(fields.Many2One('stock.location',
'Warehouse'), 'get_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',
on_change_with=['product', 'quantity', '_parent_sale.sale_date'],
states={
'invisible': ((Eval('type') != 'line')
| (If(Bool(Eval('quantity')), Eval('quantity', 0), 0)
<= 0)),
},
depends=['type', 'quantity']),
'on_change_with_delivery_date')
@classmethod
def __setup__(cls):
super(SaleLine, cls).__setup__()
cls._order.insert(0, ('sequence', 'ASC'))
cls._error_messages.update({
'customer_location_required': (
'Sale "%(sale)s" is missing the '
'customer location in line "%(line)s".'),
'missing_account_revenue': ('Product "%(product)s" of sale '
'%(sale)s misses a revenue account.'),
'missing_account_revenue_property': ('Sale "%(sale)s" '
'misses an "account revenue" default property.'),
})
@classmethod
def __register__(cls, module_name):
TableHandler = backend.get('TableHandler')
cursor = Transaction().cursor
sql_table = cls.__table__()
super(SaleLine, cls).__register__(module_name)
table = TableHandler(cursor, cls, module_name)
# Migration from 1.0 comment change into note
if table.column_exist('comment'):
cursor.execute(*sql_table.update(
columns=[sql_table.note],
values=[sql_table.comment]))
table.drop_column('comment', exception=True)
# Migration from 2.4: drop required on sequence
table.not_null_action('sequence', action='remove')
@staticmethod
def order_sequence(tables):
table, _ = tables[None]
return [table.sequence == None, table.sequence]
@staticmethod
def default_type():
return 'line'
@staticmethod
def default_unit_digits():
return 2
def on_change_with_unit_digits(self, name=None):
if self.unit:
return self.unit.digits
return 2
def get_move_done(self, name):
Uom = Pool().get('product.uom')
done = True
if not self.product:
return True
if self.product.type == 'service':
return True
skip_ids = set(x.id for x in self.moves_ignored)
skip_ids.update(x.id for x in self.moves_recreated)
quantity = self.quantity
for move in self.moves:
if move.state != 'done' \
and move.id not in skip_ids:
done = False
break
quantity -= Uom.compute_qty(move.uom, move.quantity, self.unit)
if done:
if quantity > 0.0:
done = False
return done
def get_move_exception(self, name):
skip_ids = set(x.id for x in self.moves_ignored)
skip_ids.update(x.id for x in self.moves_recreated)
for move in self.moves:
if move.state == 'cancel' \
and move.id not in skip_ids:
return True
return False
def _get_tax_rule_pattern(self):
'''
Get tax rule pattern
'''
return {}
def _get_context_sale_price(self):
context = {}
if getattr(self, 'sale', None):
if getattr(self.sale, 'currency', None):
context['currency'] = self.sale.currency.id
if getattr(self.sale, 'party', None):
context['customer'] = self.sale.party.id
if getattr(self.sale, 'sale_date', None):
context['sale_date'] = self.sale.sale_date
if self.unit:
context['uom'] = self.unit.id
else:
context['uom'] = self.product.sale_uom.id
return context
def on_change_product(self):
Product = Pool().get('product.product')
if not self.product:
return {}
res = {}
party = None
party_context = {}
if self.sale and self.sale.party:
party = self.sale.party
if party.lang:
party_context['language'] = party.lang.code
category = self.product.sale_uom.category
if not self.unit or self.unit not in category.uoms:
res['unit'] = self.product.sale_uom.id
self.unit = self.product.sale_uom
res['unit.rec_name'] = self.product.sale_uom.rec_name
res['unit_digits'] = self.product.sale_uom.digits
with Transaction().set_context(self._get_context_sale_price()):
res['unit_price'] = Product.get_sale_price([self.product],
self.quantity or 0)[self.product.id]
if res['unit_price']:
res['unit_price'] = res['unit_price'].quantize(
Decimal(1) / 10 ** self.__class__.unit_price.digits[1])
res['taxes'] = []
pattern = self._get_tax_rule_pattern()
for tax in self.product.customer_taxes_used:
if party and party.customer_tax_rule:
tax_ids = party.customer_tax_rule.apply(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 = party.customer_tax_rule.apply(None, pattern)
if tax_ids:
res['taxes'].extend(tax_ids)
if not self.description:
with Transaction().set_context(party_context):
res['description'] = Product(self.product.id).rec_name
self.unit_price = res['unit_price']
self.type = 'line'
res['amount'] = self.on_change_with_amount()
return res
def on_change_with_product_uom_category(self, name=None):
if self.product:
return self.product.default_uom_category.id
def on_change_quantity(self):
Product = Pool().get('product.product')
if not self.product:
return {}
res = {}
with Transaction().set_context(
self._get_context_sale_price()):
res['unit_price'] = Product.get_sale_price([self.product],
self.quantity or 0)[self.product.id]
if res['unit_price']:
res['unit_price'] = res['unit_price'].quantize(
Decimal(1) / 10 ** self.__class__.unit_price.digits[1])
return res
def on_change_unit(self):
return self.on_change_quantity()
def on_change_with_amount(self):
if self.type == 'line':
currency = self.sale.currency if self.sale else None
amount = Decimal(str(self.quantity or '0.0')) * \
(self.unit_price or Decimal('0.0'))
if currency:
return currency.round(amount)
return amount
return Decimal('0.0')
def get_amount(self, name):
if self.type == 'line':
return self.sale.currency.round(
Decimal(str(self.quantity)) * self.unit_price)
elif self.type == 'subtotal':
amount = Decimal('0.0')
for line2 in self.sale.lines:
if line2.type == 'line':
amount += line2.sale.currency.round(
Decimal(str(line2.quantity)) * line2.unit_price)
elif line2.type == 'subtotal':
if self == line2:
break
amount = Decimal('0.0')
return amount
return Decimal('0.0')
def get_warehouse(self, name):
return self.sale.warehouse.id if self.sale.warehouse else None
def get_from_location(self, name):
if self.quantity >= 0:
if self.warehouse:
return self.warehouse.output_location.id
else:
return self.sale.party.customer_location.id
def get_to_location(self, name):
if self.quantity >= 0:
return self.sale.party.customer_location.id
else:
if self.warehouse:
return self.warehouse.input_location.id
def on_change_with_delivery_date(self, name=None):
if self.product and self.quantity > 0:
date = self.sale.sale_date if self.sale else None
return self.product.compute_delivery_date(date=date)
def get_invoice_line(self, invoice_type):
'''
Return a list of invoice lines for sale line according to invoice_type
'''
pool = Pool()
Uom = pool.get('product.uom')
Property = pool.get('ir.property')
InvoiceLine = pool.get('account.invoice.line')
with Transaction().set_user(0, set_context=True):
invoice_line = InvoiceLine()
invoice_line.type = self.type
invoice_line.description = self.description
invoice_line.note = self.note
invoice_line.origin = self
if self.type != 'line':
if (self.sale.invoice_method == 'order'
and not self.invoice_lines
and ((all(l.quantity >= 0 for l in self.sale.lines
if l.type == 'line')
and invoice_type == 'out_invoice')
or (all(l.quantity <= 0 for l in self.sale.lines
if l.type == 'line')
and invoice_type == 'out_credit_note'))):
return [invoice_line]
else:
return []
if (invoice_type == 'out_invoice') != (self.quantity >= 0):
return []
if (self.sale.invoice_method == 'order'
or not self.product
or self.product.type == 'service'):
quantity = abs(self.quantity)
else:
quantity = 0.0
for move in self.moves:
if move.state == 'done':
quantity += Uom.compute_qty(move.uom, move.quantity,
self.unit)
skip_ids = set(l.id for i in self.sale.invoices_recreated
for l in i.lines)
for old_invoice_line in self.invoice_lines:
if old_invoice_line.type != 'line':
continue
if old_invoice_line.id not in skip_ids:
quantity -= Uom.compute_qty(old_invoice_line.unit,
old_invoice_line.quantity, self.unit)
invoice_line.quantity = quantity
if invoice_line.quantity <= 0.0:
return []
invoice_line.unit = self.unit
invoice_line.product = self.product
invoice_line.unit_price = self.unit_price
invoice_line.taxes = self.taxes
invoice_line.invoice_type = invoice_type
if self.product:
invoice_line.account = self.product.account_revenue_used
if not invoice_line.account:
self.raise_user_error('missing_account_revenue', {
'sale': self.sale.rec_name,
'product': self.product.rec_name,
})
else:
for model in ('product.template', 'product.category'):
invoice_line.account = Property.get('account_revenue', model)
if invoice_line.account:
break
if not invoice_line.account:
self.raise_user_error('missing_account_revenue_property', {
'sale': self.sale.rec_name,
})
return [invoice_line]
@classmethod
def copy(cls, lines, default=None):
if default is None:
default = {}
default = default.copy()
default['moves'] = None
default['moves_ignored'] = None
default['moves_recreated'] = None
default['invoice_lines'] = None
return super(SaleLine, cls).copy(lines, default=default)
def get_move(self, shipment_type):
'''
Return moves for the sale line according ot shipment_type
'''
pool = Pool()
Uom = pool.get('product.uom')
Move = pool.get('stock.move')
if self.type != 'line':
return
if not self.product:
return
if self.product.type == 'service':
return
if (shipment_type == 'out') != (self.quantity >= 0):
return
if self.sale.shipment_method == 'order':
quantity = abs(self.quantity)
else:
quantity = 0.0
for invoice_line in self.invoice_lines:
if invoice_line.invoice.state == 'paid':
quantity += Uom.compute_qty(invoice_line.unit,
invoice_line.quantity, self.unit)
skip_ids = set(x.id for x in self.moves_recreated)
for move in self.moves:
if move.id not in skip_ids:
quantity -= Uom.compute_qty(move.uom, move.quantity,
self.unit)
if quantity <= 0.0:
return
if not self.sale.party.customer_location:
self.raise_user_error('customer_location_required', {
'sale': self.sale.rec_name,
'line': self.rec_name,
})
with Transaction().set_user(0, set_context=True):
move = Move()
move.quantity = quantity
move.uom = self.unit
move.product = self.product
move.from_location = self.from_location
move.to_location = self.to_location
move.state = 'draft'
move.company = self.sale.company
move.unit_price = self.unit_price
move.currency = self.sale.currency
move.planned_date = self.delivery_date
move.origin = self
return move
class SaleLineTax(ModelSQL):
'Sale Line - Tax'
__name__ = 'sale.line-account.tax'
_table = 'sale_line_account_tax'
line = fields.Many2One('sale.line', 'Sale Line', ondelete='CASCADE',
select=True, required=True)
tax = fields.Many2One('account.tax', 'Tax', ondelete='RESTRICT',
select=True, required=True)
class SaleLineIgnoredMove(ModelSQL):
'Sale Line - Ignored Move'
__name__ = 'sale.line-ignored-stock.move'
_table = 'sale_line_moves_ignored_rel'
sale_line = fields.Many2One('sale.line', 'Sale Line', ondelete='CASCADE',
select=True, required=True)
move = fields.Many2One('stock.move', 'Move', ondelete='RESTRICT',
select=True, required=True)
class SaleLineRecreatedMove(ModelSQL):
'Sale Line - Recreated Move'
__name__ = 'sale.line-recreated-stock.move'
_table = 'sale_line_moves_recreated_rel'
sale_line = fields.Many2One('sale.line', 'Sale Line', ondelete='CASCADE',
select=True, required=True)
move = fields.Many2One('stock.move', 'Move', ondelete='RESTRICT',
select=True, required=True)
class SaleReport(CompanyReport):
__name__ = 'sale.sale'
class OpenCustomer(Wizard):
'Open Customers'
__name__ = 'sale.open_customer'
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')
Sale = pool.get('sale.sale')
cursor = Transaction().cursor
sale = Sale.__table__()
cursor.execute(*sale.select(sale.party, group_by=sale.party))
customer_ids = [line[0] for line in Transaction().cursor.fetchall()]
action['pyson_domain'] = PYSONEncoder().encode(
[('id', 'in', customer_ids)])
model_data, = ModelData.search([
('fs_id', '=', 'act_open_customer'),
('module', '=', 'sale'),
], limit=1)
wizard = Wizard(model_data.db_id)
action['name'] = wizard.name
return action, {}
def transition_open_(self):
return 'end'
class HandleShipmentExceptionAsk(ModelView):
'Handle Shipment Exception'
__name__ = 'sale.handle.shipment.exception.ask'
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')
@classmethod
def __register__(cls, module_name):
cursor = Transaction().cursor
model = Table('ir_model')
# Migration from 1.2: packing renamed into shipment
cursor.execute(*model.update(
columns=[model.model],
values=[Overlay(model.model, 'shipment',
Position('packing', model.model),
len('packing'))],
where=model.model.like('%packing%')
& (model.module == module_name)))
super(HandleShipmentExceptionAsk, cls).__register__(module_name)
class HandleShipmentException(Wizard):
'Handle Shipment Exception'
__name__ = 'sale.handle.shipment.exception'
start_state = 'ask'
ask = StateView('sale.handle.shipment.exception.ask',
'sale.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):
Sale = Pool().get('sale.sale')
sale = Sale(Transaction().context.get('active_id'))
moves = []
for line in sale.lines:
skips = set(line.moves_ignored)
skips.update(line.moves_recreated)
for move in line.moves:
if move.state == 'cancel' and move not in skips:
moves.append(move.id)
return {
'recreate_moves': moves,
'domain_moves': moves,
}
def transition_handle(self):
pool = Pool()
Sale = pool.get('sale.sale')
SaleLine = pool.get('sale.line')
sale = Sale(Transaction().context['active_id'])
for line in sale.lines:
moves_ignored = []
moves_recreated = []
skips = set(line.moves_ignored)
skips.update(line.moves_recreated)
for move in line.moves:
if move not in self.ask.domain_moves or move in skips:
continue
if move in self.ask.recreate_moves:
moves_recreated.append(move.id)
else:
moves_ignored.append(move.id)
SaleLine.write([line], {
'moves_ignored': [('add', moves_ignored)],
'moves_recreated': [('add', moves_recreated)],
})
Sale.process([sale])
return 'end'
class HandleInvoiceExceptionAsk(ModelView):
'Handle Invoice Exception'
__name__ = 'sale.handle.invoice.exception.ask'
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')
class HandleInvoiceException(Wizard):
'Handle Invoice Exception'
__name__ = 'sale.handle.invoice.exception'
start_state = 'ask'
ask = StateView('sale.handle.invoice.exception.ask',
'sale.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):
Sale = Pool().get('sale.sale')
sale = Sale(Transaction().context['active_id'])
skips = set(sale.invoices_ignored)
skips.update(sale.invoices_recreated)
invoices = []
for invoice in sale.invoices:
if invoice.state == 'cancel' and invoice not in skips:
invoices.append(invoice.id)
return {
'recreate_invoices': invoices,
'domain_invoices': invoices,
}
def transition_handle(self):
Sale = Pool().get('sale.sale')
sale = Sale(Transaction().context['active_id'])
skips = set(sale.invoices_ignored)
skips.update(sale.invoices_recreated)
invoices_ignored = []
invoices_recreated = []
for invoice in sale.invoices:
if invoice not in self.ask.domain_invoices or invoice in skips:
continue
if invoice in self.ask.recreate_invoices:
invoices_recreated.append(invoice.id)
else:
invoices_ignored.append(invoice.id)
Sale.write([sale], {
'invoices_ignored': [('add', invoices_ignored)],
'invoices_recreated': [('add', invoices_recreated)],
})
Sale.process([sale])
return 'end'
class ReturnSaleStart(ModelView):
'Return Sale'
__name__ = 'sale.return_sale.start'
class ReturnSale(Wizard):
'Return Sale'
__name__ = 'sale.return_sale'
start = StateView('sale.return_sale.start',
'sale.return_sale_start_view_form', [
Button('Cancel', 'end', 'tryton-cancel'),
Button('Return', 'return_', 'tryton-ok', default=True),
])
return_ = StateAction('sale.act_sale_form')
def do_return_(self, action):
Sale = Pool().get('sale.sale')
sales = Sale.browse(Transaction().context['active_ids'])
return_sales = Sale.copy(sales)
for sale in return_sales:
for line in sale.lines:
line.quantity *= -1
line.save()
data = {'res_id': [s.id for s in return_sales]}
if len(return_sales) == 1:
action['views'].reverse()
return action, data
|