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
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2011 MSF, TeMPO Consulting
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta, relativedelta
from order_types import ORDER_PRIORITY, ORDER_CATEGORY
from osv import osv, fields
from osv.orm import browse_record, browse_null
from tools.translate import _
from lxml import etree
import decimal_precision as dp
import netsvc
import pooler
import time
# xml parser
from lxml import etree
from purchase_override import PURCHASE_ORDER_STATE_SELECTION
class tender(osv.osv):
'''
tender class
'''
_name = 'tender'
_description = 'Tender'
def copy(self, cr, uid, id, default=None, context=None, done_list=[], local=False):
if not default:
default = {}
default['internal_state'] = 'draft' # UF-733: Reset the internal_state
if not 'sale_order_id' in default:
default['sale_order_id'] = False
return super(osv.osv, self).copy(cr, uid, id, default, context=context)
def unlink(self, cr, uid, ids, context=None):
'''
cannot delete tender not draft
'''
# Objects
t_line_obj = self.pool.get('tender.line')
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
for obj in self.browse(cr, uid, ids, context=context):
if obj.state != 'draft':
raise osv.except_osv(_('Warning !'), _("Cannot delete Tenders not in 'draft' state."))
if obj.sale_order_id:
obj_name = obj.sale_order_id.procurement_request and _('an Internal Request') or _('a Field Order')
raise osv.except_osv(_('Warning !'), _("This tender is linked to %s, so you cannot delete it. Please cancel it instead.") % obj_name)
for line in obj.tender_line_ids:
t_line_obj.fake_unlink(cr, uid, [line.id], context=context)
return super(tender, self).unlink(cr, uid, ids, context=context)
def _vals_get(self, cr, uid, ids, fields, arg, context=None):
'''
return function values
'''
result = {}
for obj in self.browse(cr, uid, ids, context=context):
result[obj.id] = {'rfq_name_list': '',
}
rfq_names = []
for rfq in obj.rfq_ids:
rfq_names.append(rfq.name)
# generate string
rfq_names.sort()
result[obj.id]['rfq_name_list'] = ','.join(rfq_names)
return result
def _is_tender_from_fo(self, cr, uid, ids, field_name, args, context=None):
res = {}
for tender in self.browse(cr, uid, ids, context=context):
retour = False
ids_proc = self.pool.get('procurement.order').search(cr,uid,[('tender_id','=',tender.id)])
ids_sol = self.pool.get('sale.order.line').search(cr,uid,[('procurement_id','in',ids_proc),('order_id.procurement_request','=',False)])
if ids_sol:
retour = True
res[tender.id] = retour
return res
_columns = {'name': fields.char('Tender Reference', size=64, required=True, select=True, readonly=True),
'sale_order_id': fields.many2one('sale.order', string="Sale Order", readonly=True),
'state': fields.selection([('draft', 'Draft'),('comparison', 'Comparison'), ('done', 'Closed'), ('cancel', 'Cancelled'),], string="State", readonly=True),
'supplier_ids': fields.many2many('res.partner', 'tender_supplier_rel', 'tender_id', 'supplier_id', string="Suppliers", domain="[('id', '!=', company_id)]",
states={'draft':[('readonly',False)]}, readonly=True,
context={'search_default_supplier': 1,}),
'location_id': fields.many2one('stock.location', 'Location', required=True, states={'draft':[('readonly',False)]}, readonly=True, domain=[('usage', '=', 'internal')]),
'company_id': fields.many2one('res.company','Company',required=True, states={'draft':[('readonly',False)]}, readonly=True),
'rfq_ids': fields.one2many('purchase.order', 'tender_id', string="RfQs", readonly=True),
'priority': fields.selection(ORDER_PRIORITY, string='Tender Priority', states={'draft':[('readonly',False)],}, readonly=True,),
'categ': fields.selection(ORDER_CATEGORY, string='Tender Category', required=True, states={'draft':[('readonly',False)],}, readonly=True),
'creator': fields.many2one('res.users', string="Creator", readonly=True, required=True,),
'warehouse_id': fields.many2one('stock.warehouse', string="Warehouse", required=True, states={'draft':[('readonly',False)],}, readonly=True),
'creation_date': fields.date(string="Creation Date", readonly=True, states={'draft':[('readonly',False)]}),
'details': fields.char(size=30, string="Details", states={'draft':[('readonly',False)],}, readonly=True),
'requested_date': fields.date(string="Requested Date", required=True, states={'draft':[('readonly',False)],}, readonly=True),
'notes': fields.text('Notes'),
'internal_state': fields.selection([('draft', 'Draft'),('updated', 'Rfq Updated'), ], string="Internal State", readonly=True),
'rfq_name_list': fields.function(_vals_get, method=True, string='RfQs Ref', type='char', readonly=True, store=False, multi='get_vals',),
'product_id': fields.related('tender_line_ids', 'product_id', type='many2one', relation='product.product', string='Product'),
'delivery_address': fields.many2one('res.partner.address', string='Delivery address', required=True),
'tender_from_fo': fields.function(_is_tender_from_fo, method=True, type='boolean', string='Is tender from FO ?',),
}
_defaults = {'categ': 'other',
'state': 'draft',
'internal_state': 'draft',
'company_id': lambda obj, cr, uid, context: obj.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id,
'creator': lambda obj, cr, uid, context: uid,
'creation_date': lambda *a: time.strftime('%Y-%m-%d'),
'requested_date': lambda *a: time.strftime('%Y-%m-%d'),
'priority': 'normal',
'warehouse_id': lambda obj, cr, uid, context: len(obj.pool.get('stock.warehouse').search(cr, uid, [])) and obj.pool.get('stock.warehouse').search(cr, uid, [])[0],
}
_order = 'name desc'
def _check_restriction_line(self, cr, uid, ids, context=None):
'''
Check if there is no restrictive products in lines
'''
if isinstance(ids, (int, long)):
ids = [ids]
line_obj = self.pool.get('tender.line')
res = True
for tender in self.browse(cr, uid, ids, context=context):
res = res and line_obj._check_restriction_line(cr, uid, [x.id for x in tender.tender_line_ids if x.line_state != 'cancel'], context=context)
return res
def default_get(self, cr, uid, fields, context=None):
'''
Set default data
'''
# Object declaration
partner_obj = self.pool.get('res.partner')
user_obj = self.pool.get('res.users')
res = super(tender, self).default_get(cr, uid, fields, context=context)
# Get the delivery address
company = user_obj.browse(cr, uid, uid, context=context).company_id
res['delivery_address'] = partner_obj.address_get(cr, uid, company.partner_id.id, ['delivery'])['delivery']
return res
def _check_tender_from_fo(self, cr, uid, ids, context=None):
if not context:
context = {}
retour = True
for tender in self.browse(cr, uid, ids, context=context):
if not tender.tender_from_fo:
return retour
for sup in tender.supplier_ids:
if sup.partner_type == 'internal' :
retour = False
return retour
_constraints = [
(_check_tender_from_fo, 'You cannot choose an internal supplier for this tender', []),
]
def create(self, cr, uid, vals, context=None):
'''
Set the reference of the tender at this time
'''
if not vals.get('name', False):
vals.update({'name': self.pool.get('ir.sequence').get(cr, uid, 'tender')})
return super(tender, self).create(cr, uid, vals, context=context)
def _check_service(self, cr, uid, ids, vals, context=None):
'''
Avoid the saving of a Tender with non service products on Service Tender
'''
if isinstance(ids, (int, long)):
ids = [ids]
categ = {'transport': _('Transport'),
'service': _('Service')}
if context is None:
context = {}
if context.get('import_in_progress'):
return True
for tender in self.browse(cr, uid, ids, context=context):
for line in tender.tender_line_ids:
if line.line_state == 'cancel':
continue
if vals.get('categ', tender.categ) == 'transport' and line.product_id and (line.product_id.type not in ('service', 'service_recep') or not line.product_id.transport_ok):
raise osv.except_osv(_('Error'), _('The product [%s]%s is not a \'Transport\' product. You can have only \'Transport\' products on a \'Transport\' tender. Please remove this line.') % (line.product_id.default_code, line.product_id.name))
return False
elif vals.get('categ', tender.categ) == 'service' and line.product_id and line.product_id.type not in ('service', 'service_recep'):
raise osv.except_osv(_('Error'), _('The product [%s] %s is not a \'Service\' product. You can have only \'Service\' products on a \'Service\' tender. Please remove this line.') % (line.product_id.default_code, line.product_id.name))
return False
return True
def write(self, cr, uid, ids, vals, context=None):
"""
Check consistency between lines and categ of tender
"""
self._check_service(cr, uid, ids, vals, context=context)
return super(tender, self).write(cr, uid, ids, vals, context=context)
def onchange_categ(self, cr, uid, ids, categ, context=None):
""" Check that the categ is compatible with the product
@param categ: Changed value of categ.
@return: Dictionary of values.
"""
if isinstance(ids, (int, long)):
ids = [ids]
message = {}
if ids and categ in ['service', 'transport']:
# Avoid selection of non-service producs on Service Tender
category = categ=='service' and 'service_recep' or 'transport'
transport_cat = ''
if category == 'transport':
transport_cat = 'OR p.transport_ok = False'
cr.execute('''SELECT p.default_code AS default_code, t.name AS name
FROM tender_line l
LEFT JOIN product_product p ON l.product_id = p.id
LEFT JOIN product_template pt ON p.product_tmpl_id = pt.id
LEFT JOIN tender t ON l.tender_id = t.id
WHERE (pt.type != 'service_recep' %s) AND t.id in (%s) LIMIT 1''' % (transport_cat, ','.join(str(x) for x in ids)))
res = cr.fetchall()
if res:
cat_name = categ=='service' and 'Service' or 'Transport'
message.update({'title': _('Warning'),
'message': _('The product [%s] %s is not a \'%s\' product. You can have only \'%s\' products on a \'%s\' tender. Please remove this line before saving.') % (res[0][0], res[0][1], cat_name, cat_name, cat_name)})
return {'warning': message}
def onchange_warehouse(self, cr, uid, ids, warehouse_id, context=None):
'''
on_change function for the warehouse
'''
result = {'value':{},}
if warehouse_id:
input_loc_id = self.pool.get('stock.warehouse').browse(cr, uid, warehouse_id, context=context).lot_input_id.id
result['value'].update(location_id=input_loc_id)
return result
def wkf_generate_rfq(self, cr, uid, ids, context=None):
'''
generate the rfqs for each specified supplier
'''
if context is None:
context = {}
po_obj = self.pool.get('purchase.order')
pol_obj = self.pool.get('purchase.order.line')
partner_obj = self.pool.get('res.partner')
pricelist_obj = self.pool.get('product.pricelist')
obj_data = self.pool.get('ir.model.data')
# no suppliers -> raise error
for tender in self.browse(cr, uid, ids, context=context):
# check some supplier have been selected
if not tender.supplier_ids:
raise osv.except_osv(_('Warning !'), _('You must select at least one supplier!'))
#utp-315: check that the suppliers are not inactive (I use a SQL request because the inactive partner are ignored with the browse)
sql = """
select tsr.supplier_id, rp.name, rp.active
from tender_supplier_rel tsr
left join res_partner rp
on tsr.supplier_id = rp.id
where tsr.tender_id=%s
and rp.active=False
"""
cr.execute(sql, (ids[0],))
inactive_supplier_ids = cr.dictfetchall()
if any(inactive_supplier_ids):
raise osv.except_osv(_('Warning !'), _("You can't have inactive supplier! Please remove: %s"
) % ' ,'.join([partner['name'] for partner in inactive_supplier_ids]))
# check some products have been selected
tender_line_ids = self.pool.get('tender.line').search(cr, uid, [('tender_id', '=', tender.id), ('line_state', '!=', 'cancel')], context=context)
if not tender_line_ids:
raise osv.except_osv(_('Warning !'), _('You must select at least one product!'))
for supplier in tender.supplier_ids:
# create a purchase order for each supplier
address_id = partner_obj.address_get(cr, uid, [supplier.id], ['default'])['default']
if not address_id:
raise osv.except_osv(_('Warning !'), _('The supplier "%s" has no address defined!')%(supplier.name,))
pricelist_id = supplier.property_product_pricelist_purchase.id
values = {'origin': tender.sale_order_id and tender.sale_order_id.name + ';' + tender.name or tender.name,
'rfq_ok': True,
'partner_id': supplier.id,
'partner_address_id': address_id,
'location_id': tender.location_id.id,
'pricelist_id': pricelist_id,
'company_id': tender.company_id.id,
'fiscal_position': supplier.property_account_position and supplier.property_account_position.id or False,
'tender_id': tender.id,
'warehouse_id': tender.warehouse_id.id,
'categ': tender.categ,
'priority': tender.priority,
'details': tender.details,
'delivery_requested_date': tender.requested_date,
'rfq_delivery_address': tender.delivery_address and tender.delivery_address.id or False,
}
# create the rfq - dic is udpated for default partner_address_id at purchase.order level
po_id = po_obj.create(cr, uid, values, context=dict(context, partner_id=supplier.id, rfq_ok=True))
for line in tender.tender_line_ids:
if line.line_state == 'cancel':
continue
if line.qty <= 0.00:
raise osv.except_osv(_('Error !'), _('You cannot generate RfQs for an line with a null quantity.'))
if line.product_id.id == obj_data.get_object_reference(cr, uid,'msf_doc_import', 'product_tbd')[1]:
raise osv.except_osv(_('Warning !'), _('You can\'t have "To Be Defined" for the product. Please select an existing product.'))
# create an order line for each tender line
price = pricelist_obj.price_get(cr, uid, [pricelist_id], line.product_id.id, line.qty, supplier.id, {'uom': line.product_uom.id})[pricelist_id]
newdate = datetime.strptime(line.date_planned, '%Y-%m-%d')
#newdate = (newdate - relativedelta(days=tender.company_id.po_lead)) - relativedelta(days=int(supplier.default_delay)) # requested by Magali uf-489
values = {'name': line.product_id.partner_ref,
'product_qty': line.qty,
'product_id': line.product_id.id,
'product_uom': line.product_uom.id,
'price_unit': 0.0, # was price variable - uf-607
'date_planned': newdate.strftime('%Y-%m-%d'),
'notes': line.product_id.description_purchase,
'order_id': po_id,
'tender_line_id': line.id,
}
# create purchase order line
pol_id = pol_obj.create(cr, uid, values, context=context)
message = "Request for Quotation '%s' has been created."%po_obj.browse(cr, uid, po_id, context=context).name
# create the log message
self.pool.get('res.log').create(cr, uid,
{'name': message,
'res_model': po_obj._name,
'secondary': False,
'res_id': po_id,
'domain': [('rfq_ok', '=', True)],
}, context={'rfq_ok': True})
self.write(cr, uid, ids, {'state':'comparison'}, context=context)
return True
def wkf_action_done(self, cr, uid, ids, context=None):
'''
tender is done
'''
# done all related rfqs
wf_service = netsvc.LocalService("workflow")
sol_obj = self.pool.get('sale.order.line')
proc_obj = self.pool.get('procurement.order')
date_tools = self.pool.get('date.tools')
fields_tools = self.pool.get('fields.tools')
db_date_format = date_tools.get_db_date_format(cr, uid, context=context)
for tender in self.browse(cr, uid, ids, context=context):
rfq_list = []
for rfq in tender.rfq_ids:
if rfq.state not in ('rfq_updated', 'cancel',):
rfq_list.append(rfq.id)
else:
wf_service.trg_validate(uid, 'purchase.order', rfq.id, 'rfq_done', cr)
# if some rfq have wrong state, we display a message
if rfq_list:
raise osv.except_osv(_('Warning !'), _("Generated RfQs must be Updated or Cancelled."))
# integrity check, all lines must have purchase_order_line_id
if not all([line.purchase_order_line_id.id for line in tender.tender_line_ids if line.line_state != 'cancel']):
raise osv.except_osv(_('Error !'), _('All tender lines must have been compared!'))
if tender.sale_order_id:
# Update procurement order
for line in tender.tender_line_ids:
if line.line_state == 'cancel':
proc_id = line.sale_order_line_id and line.sale_order_line_id.procurement_id and line.sale_order_line_id.procurement_id.id
if proc_id:
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_cancel', cr)
continue
vals = {'product_id': line.product_id.id,
'product_uom': line.product_uom.id,
'product_uos': line.product_uom.id,
'product_qty': line.qty,
'price_unit': line.price_unit,
'product_uos_qty': line.qty}
if line.sale_order_line_id and line.sale_order_line_id.procurement_id:
proc_id = line.sale_order_line_id.procurement_id.id
proc_obj.write(cr, uid, [proc_id], vals, context=context)
else: # Create procurement order to add the lines in a PO
create_vals = vals.copy()
prep_lt = fields_tools.get_field_from_company(cr, uid, object='sale.order', field='preparation_lead_time', context=context)
rts = datetime.strptime(tender.sale_order_id.ready_to_ship_date, db_date_format)
rts = rts - relativedelta(days=prep_lt or 0)
rts = rts.strftime(db_date_format)
create_vals.update({'procure_method': 'make_to_order',
'is_tender': True,
'tender_id': tender.id,
'tender_line_id': line.id,
'price_unit': line.price_unit,
'date_planned': rts,
'origin': tender.sale_order_id.name,
'supplier': line.purchase_order_line_id.order_id.partner_id.id,
'name': '[%s] %s' % (line.product_id.default_code, line.product_id.name),
'location_id': tender.sale_order_id.warehouse_id.lot_stock_id.id,
'po_cft': 'cft',
})
proc_id = proc_obj.create(cr, uid, create_vals, context=context)
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_check', cr)
# update product supplierinfo and pricelist
self.update_supplier_info(cr, uid, ids, context=context, integrity_test=False,)
# change tender state
self.write(cr, uid, ids, {'state':'done'}, context=context)
return True
def tender_integrity(self, cr, uid, tender, context=None):
'''
check the state of corresponding RfQs
'''
po_obj = self.pool.get('purchase.order')
# no rfq in done state
rfq_ids = po_obj.search(cr, uid, [('tender_id', '=', tender.id),
('state', 'in', ('done',)),], context=context)
if rfq_ids:
raise osv.except_osv(_('Error !'), _("Some RfQ are already Closed. Integrity failure."))
# all rfqs must have been treated
rfq_ids = po_obj.search(cr, uid, [('tender_id', '=', tender.id),
('state', 'in', ('draft', 'rfq_sent',)),], context=context)
if rfq_ids:
raise osv.except_osv(_('Warning !'), _("Generated RfQs must be Updated or Cancelled."))
# at least one rfq must be updated and not canceled
rfq_ids = po_obj.search(cr, uid, [('tender_id', '=', tender.id),
('state', 'in', ('rfq_updated',)),], context=context)
if not rfq_ids:
raise osv.except_osv(_('Warning !'), _("At least one RfQ must be in state Updated."))
return rfq_ids
def compare_rfqs(self, cr, uid, ids, context=None):
'''
compare rfqs button
'''
if len(ids) > 1:
raise osv.except_osv(_('Warning !'), _('Cannot compare rfqs of more than one tender at a time!'))
po_obj = self.pool.get('purchase.order')
wiz_obj = self.pool.get('wizard.compare.rfq')
for tender in self.browse(cr, uid, ids, context=context):
# check if corresponding rfqs are in the good state
rfq_ids = self.tender_integrity(cr, uid, tender, context=context)
# gather the product_id -> supplier_id relationship to display it back in the compare wizard
suppliers = {}
for line in tender.tender_line_ids:
if line.product_id and line.supplier_id and line.line_state != 'cancel':
suppliers.update({line.product_id.id:line.supplier_id.id,})
# rfq corresponding to this tender with done state (has been updated and not canceled)
# the list of rfq which will be compared
c = dict(context, active_ids=rfq_ids, tender_id=tender.id, end_wizard=False, suppliers=suppliers,)
# open the wizard
action = wiz_obj.start_compare_rfq(cr, uid, ids, context=c)
return action
def update_supplier_info(self, cr, uid, ids, context=None, *args, **kwargs):
'''
update the supplier info of corresponding products
'''
info_obj = self.pool.get('product.supplierinfo')
pricelist_info_obj = self.pool.get('pricelist.partnerinfo')
# integrity check flag
integrity_test = kwargs.get('integrity_test', False)
for tender in self.browse(cr, uid, ids, context=context):
# flag if at least one update
updated = tender.tender_line_ids and False or True
# check if corresponding rfqs are in the good state
if integrity_test:
self.tender_integrity(cr, uid, tender, context=context)
for line in tender.tender_line_ids:
if line.line_state == 'cancel':
continue
# if a supplier has been selected
if line.purchase_order_line_id:
# set the flag
updated = True
# get the product
product = line.product_id
# find the corresponding suppinfo with sequence -99
info_99_list = info_obj.search(cr, uid, [('product_id', '=', product.product_tmpl_id.id),
('sequence', '=', -99),], context=context)
if info_99_list:
# we drop it
info_obj.unlink(cr, uid, info_99_list, context=context)
# create the new one
values = {'name': line.supplier_id.id,
'product_name': False,
'product_code': False,
'sequence' : -99,
#'product_uom': line.product_uom.id,
#'min_qty': 0.0,
#'qty': function
'product_id' : product.product_tmpl_id.id,
'delay' : int(line.supplier_id.default_delay),
#'pricelist_ids': created just after
#'company_id': default value
}
new_info_id = info_obj.create(cr, uid, values, context=context)
# price lists creation - 'pricelist.partnerinfo
values = {'suppinfo_id': new_info_id,
'min_quantity': 1.00,
'price': line.price_unit,
'uom_id': line.product_uom.id,
'currency_id': line.purchase_order_line_id.currency_id.id,
'valid_till': line.purchase_order_id.valid_till,
'purchase_order_line_id': line.purchase_order_line_id.id,
'comment': 'RfQ original quantity for price : %s' % line.qty,
}
new_pricelist_id = pricelist_info_obj.create(cr, uid, values, context=context)
# warn the user if no update has been performed
if not updated:
raise osv.except_osv(_('Warning !'), _('No information available for update!'))
return True
def done(self, cr, uid, ids, context=None):
'''
method to perform checks before call to workflow
'''
po_obj = self.pool.get('purchase.order')
wf_service = netsvc.LocalService("workflow")
for tender in self.browse(cr, uid, ids, context=context):
# check if corresponding rfqs are in the good state
self.tender_integrity(cr, uid, tender, context=context)
wf_service.trg_validate(uid, 'tender', tender.id, 'button_done', cr)
# trigger all related rfqs
rfq_ids = po_obj.search(cr, uid, [('tender_id', '=', tender.id),], context=context)
for rfq_id in rfq_ids:
wf_service.trg_validate(uid, 'purchase.order', rfq_id, 'rfq_done', cr)
return True
def create_po(self, cr, uid, ids, context=None):
'''
create a po from the updated RfQs
'''
if isinstance(ids, (int, long)):
ids = [ids]
partner_obj = self.pool.get('res.partner')
po_obj = self.pool.get('purchase.order')
wf_service = netsvc.LocalService("workflow")
for tender in self.browse(cr, uid, ids, context=context):
# check if corresponding rfqs are in the good state
self.tender_integrity(cr, uid, tender, context=context)
# integrity check, all lines must have purchase_order_line_id
if not all([line.purchase_order_line_id.id for line in tender.tender_line_ids if line.line_state != 'cancel']):
raise osv.except_osv(_('Error !'), _('All tender lines must have been compared!'))
data = {}
for line in tender.tender_line_ids:
if line.line_state == 'cancel':
continue
data.setdefault(line.supplier_id.id, {}) \
.setdefault('order_line', []).append((0,0,{'name': line.product_id.partner_ref,
'product_qty': line.qty,
'product_id': line.product_id.id,
'product_uom': line.product_uom.id,
'change_price_manually': 'True',
'price_unit': line.price_unit,
'date_planned': line.date_planned,
'move_dest_id': False,
'notes': line.product_id.description_purchase,
}))
# fill data corresponding to po creation
address_id = partner_obj.address_get(cr, uid, [line.supplier_id.id], ['default'])['default']
pricelist = line.supplier_id.property_product_pricelist_purchase.id,
if line.currency_id:
price_ids = self.pool.get('product.pricelist').search(cr, uid, [('type', '=', 'purchase'), ('currency_id', '=', line.currency_id.id)], context=context)
if price_ids:
pricelist = price_ids[0]
po_values = {'origin': (tender.sale_order_id and tender.sale_order_id.name or "") + '; ' + tender.name,
'partner_id': line.supplier_id.id,
'partner_address_id': address_id,
'location_id': tender.location_id.id,
'pricelist_id': pricelist,
'company_id': tender.company_id.id,
'fiscal_position': line.supplier_id.property_account_position and line.supplier_id.property_account_position.id or False,
'categ': tender.categ,
'priority': tender.priority,
'origin_tender_id': tender.id,
#'tender_id': tender.id, # not for now, because tender_id is the flag for a po to be considered as RfQ
'warehouse_id': tender.warehouse_id.id,
'details': tender.details,
'delivery_requested_date': tender.requested_date,
'dest_address_id': tender.delivery_address.id,
}
data[line.supplier_id.id].update(po_values)
# create the pos, one for each selected supplier
for po_data in data.values():
po_id = po_obj.create(cr, uid, po_data, context=context)
po = po_obj.browse(cr, uid, po_id, context=context)
po_obj.log(cr, uid, po_id, 'The Purchase order %s for supplier %s has been created.'%(po.name, po.partner_id.name))
#UF-802: the PO created must be in draft state, and not validated!
#wf_service.trg_validate(uid, 'purchase.order', po_id, 'purchase_confirm', cr)
# when the po is generated, the tender is done - no more modification or comparison
self.done(cr, uid, [tender.id], context=context)
return po_id
def cancel_tender(self, cr, uid, ids, context=None):
'''
Ask the user if he wants to re-source all lines
'''
wiz_obj = self.pool.get('tender.cancel.wizard')
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
tender = self.read(cr, uid, ids[0], ['state'], context=context)
wiz_id = wiz_obj.create(cr, uid, {'tender_id': tender['id'], 'not_draft': tender['state'] != 'draft'}, context=context)
return {'type': 'ir.actions.act_window',
'res_model': 'tender.cancel.wizard',
'res_id': wiz_id,
'view_mode': 'form',
'view_type': 'form',
'target': 'new',
'context': context}
def wkf_action_cancel(self, cr, uid, ids, context=None):
'''
cancel all corresponding rfqs
'''
if context is None:
context = {}
po_obj = self.pool.get('purchase.order')
t_line_obj = self.pool.get('tender.line')
wf_service = netsvc.LocalService("workflow")
# set state
self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
for tender in self.browse(cr, uid, ids, context=context):
# trigger all related rfqs
rfq_ids = po_obj.search(cr, uid, [('tender_id', '=', tender.id),], context=context)
for rfq_id in rfq_ids:
wf_service.trg_validate(uid, 'purchase.order', rfq_id, 'purchase_cancel', cr)
for line in tender.tender_line_ids:
t_line_obj.cancel_sourcing(cr, uid, [line.id], context=context)
return True
def set_manually_done(self, cr, uid, ids, all_doc=True, context=None):
'''
Set the tender and all related documents to done state
'''
if isinstance(ids, (int, long)):
ids = [ids]
wf_service = netsvc.LocalService("workflow")
for tender in self.browse(cr, uid, ids, context=context):
line_updated = False
if tender.state not in ('done', 'cancel'):
for line in tender.tender_line_ids:
if line.purchase_order_line_id:
line_updated = True
# Cancel or done all RfQ related to the tender
for rfq in tender.rfq_ids:
if rfq.state not in ('done', 'cancel'):
if rfq.state == 'draft' or not line_updated:
wf_service.trg_validate(uid, 'purchase.order', rfq.id, 'purchase_cancel', cr)
else:
wf_service.trg_validate(uid, 'purchase.order', rfq.id, 'rfq_sent', cr)
if not rfq.valid_till:
self.pool.get('purchase.order').write(cr, uid, [rfq.id], {'valid_till': time.strftime('%Y-%m-%d')}, context=context)
wf_service.trg_validate(uid, 'purchase.order', rfq.id, 'rfq_updated', cr)
if all_doc:
if tender.state == 'draft' or not tender.tender_line_ids or not line_updated:
#Â Call the cancel method of the tender
wf_service.trg_validate(uid, 'tender', tender.id, 'tender_cancel', cr)
else:
#Â Call the cancel method of the tender
wf_service.trg_validate(uid, 'tender', tender.id, 'button_done', cr)
return True
tender()
class tender_line(osv.osv):
'''
tender lines
'''
_name = 'tender.line'
_description= 'Tender Line'
_SELECTION_TENDER_STATE = [('draft', 'Draft'),('comparison', 'Comparison'), ('done', 'Closed'),]
def on_product_change(self, cr, uid, id, product_id, uom_id, product_qty, context=None):
'''
product is changed, we update the UoM
'''
if not context:
context = {}
prod_obj = self.pool.get('product.product')
result = {'value': {}}
if product_id:
# Test the compatibility of the product with a tender
result, test = prod_obj._on_change_restriction_error(cr, uid, product_id, field_name='product_id', values=result, vals={'constraints': ['external', 'esc', 'internal']}, context=context)
if test:
return result
product = prod_obj.browse(cr, uid, product_id, context=context)
result['value']['product_uom'] = product.uom_id.id
result['value']['text_error'] = False
result['value']['to_correct_ok'] = False
res_qty = self.onchange_uom_qty(cr, uid, id, uom_id or result.get('value', {}).get('product_uom',False), product_qty)
result['value']['qty'] = res_qty.get('value', {}).get('qty', product_qty)
if uom_id:
result['value']['product_uom'] = uom_id
return result
def onchange_uom_qty(self, cr, uid, ids, uom_id, qty):
'''
Check round of qty according to the UoM
'''
res = {}
if qty:
res = self.pool.get('product.uom')._change_round_up_qty(cr, uid, uom_id, qty, 'qty', result=res)
return res
def _get_total_price(self, cr, uid, ids, field_name, arg, context=None):
'''
return the total price
'''
result = {}
for line in self.browse(cr, uid, ids, context=context):
result[line.id] = {}
if line.price_unit and line.qty:
result[line.id]['total_price'] = line.price_unit * line.qty
else:
result[line.id]['total_price'] = 0.0
result[line.id]['func_currency_id'] = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
if line.purchase_order_line_id:
result[line.id]['currency_id'] = line.purchase_order_line_id.order_id.pricelist_id.currency_id.id
else:
result[line.id]['currency_id'] = result[line.id]['func_currency_id']
result[line.id]['func_total_price'] = self.pool.get('res.currency').compute(cr, uid, result[line.id]['currency_id'],
result[line.id]['func_currency_id'],
result[line.id]['total_price'],
round=True, context=context)
return result
def name_get(self, cr, user, ids, context=None):
result = self.browse(cr, user, ids, context=context)
res = []
for rs in result:
code = rs.product_id and rs.product_id.name or ''
res += [(rs.id, code)]
return res
_columns = {'product_id': fields.many2one('product.product', string="Product", required=True),
'qty': fields.float(string="Qty", required=True),
'tender_id': fields.many2one('tender', string="Tender", required=True, ondelete='cascade'),
'purchase_order_line_id': fields.many2one('purchase.order.line', string="Related RfQ line", readonly=True),
'sale_order_line_id': fields.many2one('sale.order.line', string="Sale Order Line"),
'product_uom': fields.many2one('product.uom', 'Product UOM', required=True),
'date_planned': fields.related('tender_id', 'requested_date', type='date', string='Requested Date', store=False,),
# functions
'supplier_id': fields.related('purchase_order_line_id', 'order_id', 'partner_id', type='many2one', relation='res.partner', string="Supplier", readonly=True),
'price_unit': fields.related('purchase_order_line_id', 'price_unit', type="float", string="Price unit", digits_compute=dp.get_precision('Purchase Price Computation'), readonly=True), # same precision as related field!
'total_price': fields.function(_get_total_price, method=True, type='float', string="Total Price", digits_compute=dp.get_precision('Purchase Price'), multi='total'),
'currency_id': fields.function(_get_total_price, method=True, type='many2one', relation='res.currency', string='Cur.', multi='total'),
'func_total_price': fields.function(_get_total_price, method=True, type='float', string="Func. Total Price", digits_compute=dp.get_precision('Purchase Price'), multi='total'),
'func_currency_id': fields.function(_get_total_price, method=True, type='many2one', relation='res.currency', string='Func. Cur.', multi='total'),
'purchase_order_id': fields.related('purchase_order_line_id', 'order_id', type='many2one', relation='purchase.order', string="Related RfQ", readonly=True,),
'purchase_order_line_number': fields.related('purchase_order_line_id', 'line_number', type="char", string="Related Line Number", readonly=True,),
'state': fields.related('tender_id', 'state', type="selection", selection=_SELECTION_TENDER_STATE, string="State",),
'line_state': fields.selection([('draft','Draft'), ('cancel', 'Canceled'), ('done', 'Done')], string='State', readonly=True),
'comment': fields.char(size=128, string='Comment'),
'has_to_be_resourced': fields.boolean(string='Has to be resourced'),
'created_by_rfq': fields.boolean(string='Created by RfQ'),
}
_defaults = {'qty': lambda *a: 1.0,
'state': lambda *a: 'draft',
'line_state': lambda *a: 'draft',
}
def _check_restriction_line(self, cr, uid, ids, context=None):
'''
Check if there is no restrictive products in lines
'''
if isinstance(ids, (int, long)):
ids = [ids]
for line in self.browse(cr, uid, ids, context=context):
if line.tender_id and line.product_id:
if not self.pool.get('product.product')._get_restriction_error(cr, uid, line.product_id.id, vals={'constraints': ['external']}, context=context):
return False
return True
_sql_constraints = [
# ('product_qty_check', 'CHECK( qty > 0 )', 'Product Quantity must be greater than zero.'),
]
def copy(self, cr, uid, id, default=None, context=None):
if default is None:
default = {}
if not 'created_by_rf' in default:
default['created_by_rfq'] = False
return super(tender_line, self).copy(cr, uid, id, default, context=context)
def cancel_sourcing(self,cr, uid, ids, context=None):
'''
Cancel the line and re-source the FO line
'''
# Objects
sol_obj = self.pool.get('sale.order.line')
uom_obj = self.pool.get('product.uom')
tender_obj = self.pool.get('tender')
# Variables
wf_service = netsvc.LocalService("workflow")
to_remove = []
to_cancel = []
sol_ids = {}
sol_to_update = {}
so_to_update = set()
tender_to_update = set()
for line in self.browse(cr, uid, ids, context=context):
tender_to_update.add(line.tender_id.id)
if line.sale_order_line_id:
so_to_update.add(line.sale_order_line_id.order_id.id)
to_cancel.append(line.id)
# Get the ID and the product qty of the FO line to re-source
diff_qty = uom_obj._compute_qty(cr, uid, line.product_uom.id, line.qty, line.sale_order_line_id.product_uom.id)
if line.has_to_be_resourced:
sol_ids.update({line.sale_order_line_id.id: diff_qty})
sol_to_update.setdefault(line.sale_order_line_id.id, 0.00)
sol_to_update[line.sale_order_line_id.id] += diff_qty
elif line.tender_id.state == 'draft':
to_remove.append(line.id)
else:
to_cancel.append(line.id)
if to_cancel:
self.write(cr, uid, to_cancel, {'line_state': 'cancel'}, context=context)
if sol_ids:
for sol in sol_ids:
sol_obj.add_resource_line(cr, uid, sol, False, sol_ids[sol], context=context)
# Update sale order lines
for sol in sol_to_update:
sol_obj.update_or_cancel_line(cr, uid, sol, sol_to_update[sol], context=context)
# Update the FO state
for so in so_to_update:
wf_service.trg_write(uid, 'sale.order', so, cr)
# UF-733: if all tender lines have been compared (have PO Line id), then set the tender to be ready
# for proceeding to other actions (create PO, Done etc)
for tender in tender_obj.browse(cr, uid, list(tender_to_update), context=context):
if tender.internal_state == 'draft':
flag = True
for line in tender.tender_line_ids:
if line.line_state != 'cancel' and not line.purchase_order_line_id:
flag = False
if flag:
tender_obj.write(cr, uid, [tender.id], {'internal_state': 'updated'})
if context.get('fake_unlink'):
return to_remove
return True
def fake_unlink(self, cr, uid, ids, context=None):
'''
Cancel the line if it is linked to a FO line
'''
to_remove = self.cancel_sourcing(cr, uid, ids, context=dict(context, fake_unlink=True))
return self.unlink(cr, uid, to_remove, context=context)
def ask_unlink(self, cr, uid, ids, context=None):
'''
Ask user if he wants to re-source the needs
'''
# Objects
wiz_obj = self.pool.get('tender.line.cancel.wizard')
# Variables
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
tender_id = False
for line in self.browse(cr, uid, ids, context=context):
tender_id = line.tender_id.id
if line.sale_order_line_id:
wiz_id = wiz_obj.create(cr, uid, {'tender_line_id': line.id}, context=context)
return {'type': 'ir.actions.act_window',
'res_model': 'tender.line.cancel.wizard',
'view_type': 'form',
'view_mode': 'form',
'res_id': wiz_id,
'target': 'new',
'context': context}
self.fake_unlink(cr, uid, ids, context=context)
return {'type': 'ir.actions.act_window',
'res_model': 'tender',
'view_type': 'form',
'view_mode': 'form,tree',
'res_id': tender_id,
'target': 'crush',
'context': context}
tender_line()
class tender2(osv.osv):
'''
tender class
'''
_inherit = 'tender'
_columns = {'tender_line_ids': fields.one2many('tender.line', 'tender_id', string="Tender lines", states={'draft':[('readonly',False)]}, readonly=True),
}
def copy(self, cr, uid, id, default=None, context=None):
'''
reset the name to get new sequence number
the copy method is here because upwards it goes in infinite loop
'''
line_obj = self.pool.get('tender.line')
if default is None:
default = {}
default.update(name=self.pool.get('ir.sequence').get(cr, uid, 'tender'),
rfq_ids=[],
sale_order_line_id=False,)
result = super(tender2, self).copy(cr, uid, id, default, context)
return result
def copy_data(self, cr, uid, id, default=None, context=None):
'''
reset the tender line
'''
result = super(tender, self).copy_data(cr, uid, id, default=default, context=context)
# reset the tender line
for line in result['tender_line_ids']:
line[2].update(sale_order_line_id=False,
purchase_order_line_id=False,
line_state='draft',)
return result
tender2()
class procurement_order(osv.osv):
'''
tender capabilities
'''
_inherit = 'procurement.order'
def _is_tender_rfq(self, cr, uid, ids, field_name, arg, context=None):
'''
tell if the corresponding sale order line is tender/rfq sourcing or not
'''
result = {}
for proc in self.browse(cr, uid, ids, context=context):
result[proc.id] = {'is_tender': False, 'is_rfq': False}
for line in proc.sale_order_line_ids:
result[proc.id]['is_tender'] = line.po_cft == 'cft'
result[proc.id]['is_rfq'] = line.po_cft == 'rfq'
return result
_columns = {'is_tender': fields.function(_is_tender_rfq, method=True, type='boolean', string='Is Tender', readonly=True, multi='tender_rfq'),
'is_rfq': fields.function(_is_tender_rfq, method=True, type='boolean', string='Is RfQ', readonly=True, multi='tender_rfq'),
'sale_order_line_ids': fields.one2many('sale.order.line', 'procurement_id', string="Sale Order Lines"),
'tender_id': fields.many2one('tender', string='Tender', readonly=True),
'tender_line_id': fields.many2one('tender.line', string='Tender line', readonly=True),
'is_tender_done': fields.boolean(string="Tender Closed"),
'rfq_id': fields.many2one('purchase.order', string='RfQ', readonly=True),
'rfq_line_id': fields.many2one('purchase.order.line', string='RfQ line', readonly=True),
'is_rfq_done': fields.boolean(string="RfQ Closed"),
'state': fields.selection([('draft','Draft'),
('confirmed','Confirmed'),
('exception','Exception'),
('running','Converted'),
('cancel','Cancelled'),
('ready','Ready'),
('done','Closed'),
('tender', 'Tender'),
('rfq', 'Request for Quotation'),
('waiting','Waiting'),], 'State', required=True,
help='When a procurement is created the state is set to \'Draft\'.\n If the procurement is confirmed, the state is set to \'Confirmed\'.\
\nAfter confirming the state is set to \'Running\'.\n If any exception arises in the order then the state is set to \'Exception\'.\n Once the exception is removed the state becomes \'Ready\'.\n It is in \'Waiting\'. state when the procurement is waiting for another one to finish.'),
'price_unit': fields.float('Unit Price from Tender', digits_compute=dp.get_precision('Purchase Price Computation')),
}
_defaults = {
'is_tender_done': False,
'is_rfq_done': False,
}
def wkf_action_rfq_create(self, cr, uid, ids, context=None):
'''
creation of rfq from procurement workflow
'''
rfq_obj = self.pool.get('purchase.order')
rfq_line_obj = self.pool.get('purchase.order.line')
partner_obj = self.pool.get('res.partner')
if not context:
context = {}
# find the corresponding sale order id for rfq
for proc in self.browse(cr, uid, ids, context=context):
if proc.rfq_id:
return proc.rfq_id
sale_order = False
sale_order_line = False
for sol in proc.sale_order_line_ids:
sale_order = sol.order_id
sale_order_line = sol
break
# find the rfq
rfq_id = False
# UTP-934: If source rfq to different supplier, different rfq must be created, and cannot be using the same rfq
rfq_ids = rfq_obj.search(cr, uid, [('sale_order_id', '=', sale_order.id),('partner_id', '=', proc.supplier.id), ('state', '=', 'draft'), ('rfq_ok', '=', True),], context=context)
if rfq_ids:
rfq_id = rfq_ids[0]
# create if not found
if not rfq_id:
supplier = proc.supplier
company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
pricelist_id = supplier.property_product_pricelist_purchase.id
address_id = partner_obj.address_get(cr, uid, [supplier.id], ['default'])['default']
if not address_id:
raise osv.except_osv(_('Warning !'), _('The supplier "%s" has no address defined!')%(supplier.name,))
context['rfq_ok'] = True
rfq_id = rfq_obj.create(cr, uid, {'sale_order_id': sale_order.id,
'categ': sale_order.categ,
'priority': sale_order.priority,
'fiscal_position': supplier.property_account_position and supplier.property_account_position.id or False,
'rfq_delivery_address': partner_obj.address_get(cr, uid, company.partner_id.id, ['delivery'])['delivery'],
'warehouse_id': sale_order.shop_id.warehouse_id.id,
'location_id': proc.location_id.id,
'partner_id': supplier.id,
'partner_address_id': address_id,
'pricelist_id': pricelist_id,
'rfq_ok': True,
'from_procurement': True,
'order_type': sale_order.order_type,
'origin': sale_order.name,}, context=context)
# add a line to the RfQ
rfq_line_id = rfq_line_obj.create(cr, uid, {'product_id': proc.product_id.id,
'comment': sale_order_line.comment,
'name': sale_order_line.name,
'price_unit': 0.00,
'product_qty': proc.product_qty,
'origin': sale_order.name,
'order_id': rfq_id,
'sale_order_line_id': sale_order_line.id,
'location_id': proc.location_id.id,
'product_uom': proc.product_uom.id,
'procurement_id': proc.id,
#'date_planned': proc.date_planned, # function at line level
}, context=context)
self.write(cr, uid, ids, {'rfq_id': rfq_id, 'rfq_line_id': rfq_line_id}, context=context)
# log message concerning RfQ creation
rfq_obj.log(cr, uid, rfq_id, "The Request for Quotation '%s' has been created and must be completed before purchase order creation."%rfq_obj.browse(cr, uid, rfq_id, context=context).name, context={'rfq_ok': 1})
# state of procurement is Tender
self.write(cr, uid, ids, {'state': 'rfq'}, context=context)
return rfq_id
def wkf_action_tender_create(self, cr, uid, ids, context=None):
'''
creation of tender from procurement workflow
'''
tender_obj = self.pool.get('tender')
tender_line_obj = self.pool.get('tender.line')
# find the corresponding sale order id for tender
for proc in self.browse(cr, uid, ids, context=context):
if proc.tender_id:
return proc.tender_id
sale_order = False
sale_order_line = False
for sol in proc.sale_order_line_ids:
sale_order = sol.order_id
sale_order_line = sol
# find the tender
tender_id = False
tender_ids = tender_obj.search(cr, uid, [('sale_order_id', '=', sale_order.id),('state', '=', 'draft'),], context=context)
if tender_ids:
tender_id = tender_ids[0]
# create if not found
if not tender_id:
tender_id = tender_obj.create(cr, uid, {'sale_order_id': sale_order.id,
'location_id': proc.location_id.id,
'categ': sale_order.categ,
'priority': sale_order.priority,
'warehouse_id': sale_order.shop_id.warehouse_id.id,
'requested_date': proc.date_planned,
}, context=context)
# add a line to the tender
tender_line_id = tender_line_obj.create(cr, uid, {'product_id': proc.product_id.id,
'comment': sale_order_line.comment,
'qty': proc.product_qty,
'tender_id': tender_id,
'sale_order_line_id': sale_order_line.id,
'location_id': proc.location_id.id,
'product_uom': proc.product_uom.id,
#'date_planned': proc.date_planned, # function at line level
}, context=context)
self.write(cr, uid, ids, {'tender_id': tender_id, 'tender_line_id': tender_line_id}, context=context)
# log message concerning tender creation
tender_obj.log(cr, uid, tender_id, "The tender '%s' has been created and must be completed before purchase order creation."%tender_obj.browse(cr, uid, tender_id, context=context).name)
# state of procurement is Tender
self.write(cr, uid, ids, {'state': 'tender'}, context=context)
return tender_id
def wkf_action_tender_done(self, cr, uid, ids, context=None):
'''
set is_tender_done value
'''
self.write(cr, uid, ids, {'is_tender_done': True, 'state': 'exception',}, context=context)
return True
def wkf_action_rfq_done(self, cr, uid, ids, context=None):
'''
set is_rfq_done value
'''
self.write(cr, uid, ids, {'is_rfq_done': True, 'state': 'exception',}, context=context)
return True
def action_po_assign(self, cr, uid, ids, context=None):
'''
- convert the created rfq by the tender to a po
- add message at po creation during on_order workflow
'''
po_obj = self.pool.get('purchase.order')
sol_obj = self.pool.get('sale.order.line')
# If the line has been created by a confirmed PO, doesn't create a new PO
sol_ids = sol_obj.search(cr, uid, [('procurement_id', 'in', ids), ('created_by_po', '!=', False)], context=context)
if sol_ids:
return sol_obj.read(cr, uid, sol_ids[0], ['created_by_po'], context=context)['created_by_po'][0]
result = super(procurement_order, self).action_po_assign(cr, uid, ids, context=context)
# The quotation 'SO001' has been converted to a sales order.
if result:
# do not display a log if we come from po update backward update of so
data = self.read(cr, uid, ids, ['so_back_update_dest_po_id_procurement_order'], context=context)
if not data[0]['so_back_update_dest_po_id_procurement_order']:
po_obj.log(cr, uid, result, "The Purchase Order '%s' has been created following 'on order' sourcing."%po_obj.browse(cr, uid, result, context=context).name)
return result
def po_values_hook(self, cr, uid, ids, context=None, *args, **kwargs):
'''
data for the purchase order creation
'''
values = super(procurement_order, self).po_values_hook(cr, uid, ids, context=context, *args, **kwargs)
procurement = kwargs['procurement']
values['partner_address_id'] = self.pool.get('res.partner').address_get(cr, uid, [values['partner_id']], ['default'])['default']
# set tender link in purchase order
if procurement.tender_id:
values['origin_tender_id'] = procurement.tender_id.id
# set rfq link in purchase order
if procurement.rfq_id:
values['origin_rfq_id'] = procurement.rfq_id.id
values['date_planned'] = procurement.date_planned
if procurement.product_id:
if procurement.product_id.type == 'consu':
values['location_id'] = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'stock_override', 'stock_location_non_stockable')[1]
elif procurement.product_id.type == 'service_recep':
values['location_id'] = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'msf_config_locations', 'stock_location_service')[1]
else:
wh_ids = self.pool.get('stock.warehouse').search(cr, uid, [])
if wh_ids:
values['location_id'] = self.pool.get('stock.warehouse').browse(cr, uid, wh_ids[0]).lot_input_id.id
else:
values['location_id'] = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'msf_config_locations', 'stock_location_service')[1]
return values
procurement_order()
class purchase_order(osv.osv):
'''
add link to tender
'''
_inherit = 'purchase.order'
def _check_valid_till(self, cr, uid, ids, context=None):
""" Checks if valid till has been completed
"""
for obj in self.browse(cr, uid, ids, context=context):
if obj.state == 'rfq_updated' and not obj.valid_till:
return False
return True
_columns = {'tender_id': fields.many2one('tender', string="Tender", readonly=True),
'rfq_delivery_address': fields.many2one('res.partner.address', string='Delivery address'),
'origin_tender_id': fields.many2one('tender', string='Tender', readonly=True),
'from_procurement': fields.boolean(string='RfQ created by a procurement order'),
'rfq_ok': fields.boolean(string='Is RfQ ?'),
'state': fields.selection(PURCHASE_ORDER_STATE_SELECTION, 'State', readonly=True, help="The state of the purchase order or the quotation request. A quotation is a purchase order in a 'Draft' state. Then the order has to be confirmed by the user, the state switch to 'Confirmed'. Then the supplier must confirm the order to change the state to 'Approved'. When the purchase order is paid and received, the state becomes 'Closed'. If a cancel action occurs in the invoice or in the reception of goods, the state becomes in exception.", select=True),
'valid_till': fields.date(string='Valid Till', states={'rfq_updated': [('required', True), ('readonly', True)], 'rfq_sent':[('required',False), ('readonly', False),]}, readonly=True,),
# add readonly when state is Done
'sale_order_id': fields.many2one('sale.order', string='Link between RfQ and FO', readonly=True),
}
_defaults = {
'rfq_ok': lambda self, cr, uid, c: c.get('rfq_ok', False),
}
_constraints = [
(_check_valid_till,
'You must specify a Valid Till date.',
['valid_till']),]
def default_get(self, cr, uid, fields, context=None):
'''
Set default data
'''
# Object declaration
partner_obj = self.pool.get('res.partner')
user_obj = self.pool.get('res.users')
res = super(purchase_order, self).default_get(cr, uid, fields, context=context)
# Get the delivery address
company = user_obj.browse(cr, uid, uid, context=context).company_id
res['rfq_delivery_address'] = partner_obj.address_get(cr, uid, company.partner_id.id, ['delivery'])['delivery']
return res
def create(self, cr, uid, vals, context=None):
'''
Set the reference at this step
'''
if context is None:
context = {}
if context.get('rfq_ok', False) and not vals.get('name', False):
vals.update({'name': self.pool.get('ir.sequence').get(cr, uid, 'rfq')})
elif not vals.get('name', False):
vals.update({'name': self.pool.get('ir.sequence').get(cr, uid, 'purchase.order')})
return super(purchase_order, self).create(cr, uid, vals, context=context)
def unlink(self, cr, uid, ids, context=None):
'''
Display an error message if the PO has associated IN
'''
in_ids = self.pool.get('stock.picking').search(cr, uid, [('purchase_id', 'in', ids)], context=context)
if in_ids:
raise osv.except_osv(_('Error !'), _('Cannot delete a document if its associated ' \
'document remains open. Please delete it (associated IN) first.'))
# Copy a part of purchase_order standard unlink method to fix the bad state on error message
purchase_orders = self.read(cr, uid, ids, ['state'], context=context)
unlink_ids = []
for s in purchase_orders:
if s['state'] in ['draft','cancel']:
unlink_ids.append(s['id'])
else:
raise osv.except_osv(_('Invalid action !'), _('Cannot delete Purchase Order(s) which are in %s State!') % _(dict(PURCHASE_ORDER_STATE_SELECTION).get(s['state'])))
return super(purchase_order, self).unlink(cr, uid, ids, context=context)
def _hook_copy_name(self, cr, uid, ids, context=None, *args, **kwargs):
'''
HOOK from purchase>purchase.py for COPY function. Modification of default copy values
define which name value will be used
'''
# default values from copy function
default = kwargs.get('default', False)
# flag defining if the new object will be a rfq
is_rfq = False
# calling super function
result = super(purchase_order, self)._hook_copy_name(cr, uid, ids, context=context, *args, **kwargs)
if default.get('rfq_ok', False):
is_rfq = True
elif 'rfq_ok' not in default:
for obj in self.browse(cr, uid, ids, context=context):
# if rfq_ok is specified as default value for new object, we base our decision on this value
if obj.rfq_ok:
is_rfq = True
if is_rfq:
result.update(name=self.pool.get('ir.sequence').get(cr, uid, 'rfq'))
return result
def hook_rfq_sent_check_lines(self, cr, uid, ids, context=None):
'''
Please copy this to your module's method also.
This hook belongs to the rfq_sent method from tender_flow>tender_flow.py
- check lines after import
'''
res = True
return res
def rfq_sent(self, cr, uid, ids, context=None):
self.hook_rfq_sent_check_lines(cr, uid, ids, context=context)
for rfq in self.browse(cr, uid, ids, context=context):
wf_service = netsvc.LocalService("workflow")
wf_service.trg_validate(uid, 'purchase.order', rfq.id, 'rfq_sent', cr)
self.write(cr, uid, ids, {'date_confirm': time.strftime('%Y-%m-%d')}, context=context)
datas = {'ids': ids}
return {'type': 'ir.actions.report.xml',
'report_name': 'msf.purchase.quotation',
'datas': datas}
def check_rfq_updated(self, cr, uid, ids, context=None):
tl_obj = self.pool.get('tender.line')
line_obj = self.pool.get('purchase.order.line')
if isinstance(ids, (int, long)):
ids = [ids]
wf_service = netsvc.LocalService("workflow")
for rfq in self.browse(cr, uid, ids, context=context):
if not rfq.valid_till:
raise osv.except_osv(_('Error'), _('You must specify a Valid Till date.'))
if rfq.rfq_ok and rfq.tender_id:
for line in rfq.order_line:
if not line.tender_line_id:
tl_ids = tl_obj.search(cr, uid, [('product_id', '=', line.product_id.id), ('tender_id', '=', rfq.tender_id.id), ('line_state', '=', 'draft')], context=context)
if tl_ids:
tl_id = tl_ids[0]
else:
tl_vals = {'product_id': line.product_id.id,
'product_uom': line.product_uom.id,
'qty': line.product_qty,
'tender_id': rfq.tender_id.id,
'created_by_rfq': True}
tl_id = tl_obj.create(cr, uid, tl_vals, context=context)
line_obj.write(cr, uid, [line.id], {'tender_line_id': tl_id}, context=context)
wf_service.trg_validate(uid, 'purchase.order', rfq.id, 'rfq_updated', cr)
return {
'type': 'ir.actions.act_window',
'res_model': 'purchase.order',
'view_mode': 'form,tree,graph,calendar',
'view_type': 'form',
'target': 'crush',
'context': {'rfq_ok': True, 'search_default_draft_rfq': 1},
'domain': [('rfq_ok', '=', True)],
'res_id': rfq.id,
}
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
"""
columns for the tree
"""
if context is None:
context = {}
# the search view depends on the type we want to display
if view_type == 'search':
if context.get('rfq_ok', False):
# rfq search view
view = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'tender_flow', 'view_rfq_filter')
if view:
view_id = view[1]
if view_type == 'tree':
# the view depends on po type
if context.get('rfq_ok', False):
# rfq search view
view = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'tender_flow', 'view_rfq_tree')
if view:
view_id = view[1]
# call super
result = super(purchase_order, self).fields_view_get(cr, uid, view_id, view_type, context=context, toolbar=toolbar, submenu=submenu)
if view_type == 'form':
if context.get('rfq_ok', False):
# the title of the screen depends on po type
form = etree.fromstring(result['arch'])
fields = form.xpath('//form[@string="%s"]' % _('Purchase Order'))
for field in fields:
field.set('string', _("Request for Quotation"))
fields2 = form.xpath('//page[@string="%s"]' % _('Purchase Order'))
for field2 in fields2:
field2.set('string', _("Request for Quotation"))
result['arch'] = etree.tostring(form)
return result
def wkf_act_rfq_done(self, cr, uid, ids, context=None):
'''
Set the state to done and update the price unit in the procurement order
'''
wf_service = netsvc.LocalService("workflow")
proc_obj = self.pool.get('procurement.order')
date_tools = self.pool.get('date.tools')
fields_tools = self.pool.get('fields.tools')
db_date_format = date_tools.get_db_date_format(cr, uid, context=context)
if isinstance(ids, (int, long)):
ids = [ids]
for rfq in self.browse(cr, uid, ids, context=context):
if rfq.from_procurement:
for line in rfq.order_line:
if line.procurement_id:
self.pool.get('procurement.order').write(cr, uid, [line.procurement_id.id], {'price_unit': line.price_unit}, context=context)
elif not rfq.tender_id:
prep_lt = fields_tools.get_field_from_company(cr, uid, object='sale.order', field='preparation_lead_time', context=context)
rts = datetime.strptime(rfq.sale_order_id.ready_to_ship_date, db_date_format)
rts = rts - relativedelta(days=prep_lt or 0)
rts = rts.strftime(db_date_format)
vals = {'product_id': line.product_id.id,
'product_uom': line.product_uom.id,
'product_uos': line.product_uom.id,
'product_qty': line.product_qty,
'product_uos_qty': line.product_qty,
'price_unit': line.price_unit,
'procure_method': 'make_to_order',
'is_rfq': True,
'rfq_id': rfq.id,
'rfq_line_id': line.id,
'is_tender': False,
'tender_id': False,
'tender_line_id': False,
'date_planned': rts,
'origin': rfq.sale_order_id.name,
'supplier': rfq.partner_id.id,
'name': '[%s] %s' % (line.product_id.default_code, line.product_id.name),
'location_id': rfq.sale_order_id.warehouse_id.lot_stock_id.id,
'po_cft': 'rfq',
}
proc_id = proc_obj.create(cr, uid, vals, context=context)
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_check', cr)
return self.write(cr, uid, ids, {'state': 'done'}, context=context)
purchase_order()
class purchase_order_line(osv.osv):
'''
add a tender_id related field
'''
_inherit = 'purchase.order.line'
_columns = {'tender_id': fields.related('order_id', 'tender_id', type='many2one', relation='tender', string='Tender',),
'tender_line_id': fields.many2one('tender.line', string='Tender Line'),
'rfq_ok': fields.related('order_id', 'rfq_ok', type='boolean', string='RfQ ?'),
'sale_order_line_id': fields.many2one('sale.order.line', string='FO line', readonly=True),
}
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
"""
columns for the tree
"""
if context is None:
context = {}
# call super
result = super(purchase_order_line, self).fields_view_get(cr, uid, view_id, view_type, context=context, toolbar=toolbar, submenu=submenu)
if view_type == 'form':
if context.get('rfq_ok', False):
# the title of the screen depends on po type
form = etree.fromstring(result['arch'])
fields = form.xpath('//form[@string="%s"]' % _('Purchase Order Line'))
for field in fields:
field.set('string', _("Request for Quotation Line"))
result['arch'] = etree.tostring(form)
return result
purchase_order_line()
class sale_order_line(osv.osv):
'''
add link one2many to tender.line
'''
_inherit = 'sale.order.line'
_columns = {'tender_line_ids': fields.one2many('tender.line', 'sale_order_line_id', string="Tender Lines", readonly=True),}
def copy(self, cr, uid, ids, default, context=None):
'''
Remove tender lines linked
'''
default = default or {}
if not 'tender_line_ids' in default:
default['tender_line_ids'] = []
return super(sale_order_line, self).copy(cr, uid, ids, default, context=context)
sale_order_line()
class pricelist_partnerinfo(osv.osv):
'''
add new information from specifications
'''
def _get_line_number(self, cr, uid, ids, field_name, args, context=None):
res = {}
for price in self.browse(cr, uid, ids, context=context):
res[price.id] = 0
if price.purchase_order_line_id:
res[price.id] = price.purchase_order_line_id.line_number
return res
_inherit = 'pricelist.partnerinfo'
_columns = {'price': fields.float('Unit Price', required=True, digits_compute=dp.get_precision('Purchase Price Computation'), help="This price will be considered as a price for the supplier UoM if any or the default Unit of Measure of the product otherwise"),
'currency_id': fields.many2one('res.currency', string='Currency', required=True, domain="[('partner_currency', '=', partner_id)]"),
'valid_till': fields.date(string="Valid Till",),
'comment': fields.char(size=128, string='Comment'),
'purchase_order_id': fields.related('purchase_order_line_id', 'order_id', type='many2one', relation='purchase.order', string="Related RfQ", readonly=True,),
'purchase_order_line_id': fields.many2one('purchase.order.line', string="RfQ Line Ref",),
#'purchase_order_line_number': fields.related('purchase_order_line_id', 'line_number', type="integer", string="Related Line Number", ),
'purchase_order_line_number': fields.function(_get_line_number, method=True, type="integer", string="Related Line Number", readonly=True),
}
pricelist_partnerinfo()
class tender_line_cancel_wizard(osv.osv_memory):
_name = 'tender.line.cancel.wizard'
_columns = {
'tender_line_id': fields.many2one('tender.line', string='Tender line', required=True),
}
def just_cancel(self, cr, uid, ids, context=None):
'''
Cancel the line
'''
# Objects
line_obj = self.pool.get('tender.line')
tender_obj = self.pool.get('tender')
data_obj = self.pool.get('ir.model.data')
tender_wiz_obj = self.pool.get('tender.cancel.wizard')
# Variables
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
line_ids = []
tender_ids = set()
for wiz in self.browse(cr, uid, ids, context=context):
tender_ids.add(wiz.tender_line_id.tender_id.id)
line_ids.append(wiz.tender_line_id.id)
if context.get('has_to_be_resourced'):
line_obj.write(cr, uid, line_ids, {'has_to_be_resourced': True}, context=context)
line_obj.fake_unlink(cr, uid, line_ids, context=context)
for tender in tender_obj.browse(cr, uid, list(tender_ids), context=context):
if all(x.line_state in ('cancel', 'done') for x in tender.tender_line_ids):
wiz_id = tender_wiz_obj.create(cr, uid, {'tender_id': tender.id}, context=context)
view_id = data_obj.get_object_reference(cr, uid, 'tender_flow', 'ask_tender_cancel_wizard_form_view')[1]
return {'type': 'ir.actions.act_window',
'res_model': 'tender.cancel.wizard',
'view_type': 'form',
'view_mode': 'form',
'view_id': [view_id],
'res_id': wiz_id,
'target': 'new',
'context': context}
return {'type': 'ir.actions.act_window_close'}
def cancel_and_resource(self, cr, uid, ids, context=None):
'''
Flag the line to be re-sourced and run cancel method
'''
# Objects
if context is None:
context = {}
context['has_to_be_resourced'] = True
return self.just_cancel(cr, uid, ids, context=context)
tender_line_cancel_wizard()
class tender_cancel_wizard(osv.osv_memory):
_name = 'tender.cancel.wizard'
_columns = {
'tender_id': fields.many2one('tender', string='Tender', required=True),
'not_draft': fields.boolean(string='Tender not draft'),
}
def just_cancel(self, cr, uid, ids, context=None):
'''
Just cancel the wizard and the lines
'''
# Objects
line_obj = self.pool.get('tender.line')
# Variables
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
wf_service = netsvc.LocalService("workflow")
line_ids = []
tender_ids = []
rfq_ids = []
for wiz in self.browse(cr, uid, ids, context=context):
tender_ids.append(wiz.tender_id.id)
for line in wiz.tender_id.tender_line_ids:
line_ids.append(line.id)
for rfq in wiz.tender_id.rfq_ids:
rfq_ids.append(rfq.id)
if context.get('has_to_be_resourced'):
line_obj.write(cr, uid, line_ids, {'has_to_be_resourced': True}, context=context)
line_obj.fake_unlink(cr, uid, line_ids, context=context)
for rfq in rfq_ids:
wf_service.trg_validate(uid, 'purchase.order', rfq, 'purchase_cancel', cr)
for tender in tender_ids:
wf_service.trg_validate(uid, 'tender', tender, 'tender_cancel', cr)
return {'type': 'ir.actions.act_window_close'}
def cancel_and_resource(self, cr, uid, ids, context=None):
'''
Flag the line to be re-sourced and run cancel method
'''
# Objects
if context is None:
context = {}
context['has_to_be_resourced'] = True
return self.just_cancel(cr, uid, ids, context=context)
def close_window(self, cr, uid, ids, context=None):
'''
Just close the wizard and reload the tender
'''
return {'type': 'ir.actions.act_window_close'}
tender_cancel_wizard()
class ir_values(osv.osv):
_name = 'ir.values'
_inherit = 'ir.values'
def get(self, cr, uid, key, key2, models, meta=False, context=None, res_id_req=False, without_user=True, key2_req=True):
if context is None:
context = {}
values = super(ir_values, self).get(cr, uid, key, key2, models, meta, context, res_id_req, without_user, key2_req)
new_values = values
po_accepted_values = {'client_action_multi': ['Order Follow Up',
'action_view_purchase_order_group'],
'client_print_multi': ['Purchase Order (Merged)',
'Purchase Order',
'Allocation report',
'Order impact vs. Budget'],
'client_action_relate': ['ir_open_product_list_export_view',
'View_log_purchase.order',
'Allocation report'],
'tree_but_action': [],
'tree_but_open': []}
rfq_accepted_values = {'client_action_multi': [],
'client_print_multi': ['Request for Quotation'],
'client_action_relate': [],
'tree_but_action': [],
'tree_but_open': []}
if context.get('purchase_order', False) and 'purchase.order' in [x[0] for x in models]:
new_values = []
for v in values:
if key == 'action' and v[1] in po_accepted_values[key2] \
or v[1] == 'Purchase Order Excel Export' \
or v[1] == 'Purchase Order' \
or v[1] == 'Purchase Order (Merged)' \
or v[1] == 'Allocation report' \
or v[1] == 'Order impact vs. Budget' :
new_values.append(v)
elif context.get('request_for_quotation', False) and 'purchase.order' in [x[0] for x in models]:
new_values = []
for v in values:
if key == 'action' and v[1] in rfq_accepted_values[key2] \
or v[1] == 'Request for Quotation' \
or v[1] == 'Request For Quotation Excel Export' :
new_values.append(v)
return new_values
ir_values()
|