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
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# 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 osv import osv, fields
from tools.translate import _
import netsvc
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import decimal_precision as dp
import logging
import tools
import time
from os import path
KIT_COMPOSITION_TYPE = [('theoretical', 'Theoretical'),
('real', 'Real'),
]
KIT_STATE = [('draft', 'Draft'),
('in_production', 'In Production'),
('completed', 'Completed'),
('done', 'Closed'),
]
class composition_kit(osv.osv):
'''
kit composition class, representing both theoretical composition and actual ones
'''
_name = 'composition.kit'
def get_default_expiry_date(self, cr, uid, ids, context=None):
'''
default value for kits
'''
return '9999-01-01'
def _compute_expiry_date(self, cr, uid, ids, context=None):
'''
compute the expiry date of real composition.kit based on items
'''
# date tools object
date_obj = self.pool.get('date.tools')
db_date_format = date_obj.get_db_date_format(cr, uid, context=context)
date_format = date_obj.get_date_format(cr, uid, context=context)
for obj in self.browse(cr, uid, ids, context=context):
# if no expiry date from items (no perishable products or no expiry date entered), the default value is '9999-01-01'
expiry_date = False
# computation of expiry date makes sense only for real type
if obj.composition_type != 'real':
raise osv.except_osv(_('Warning !'), _('Computation of expiry date is only available for Composition List.'))
for item in obj.composition_item_ids:
if item.item_exp:
if not expiry_date or datetime.strptime(item.item_exp, db_date_format) < datetime.strptime(expiry_date, db_date_format):
expiry_date = item.item_exp
if not expiry_date:
expiry_date = self.get_default_expiry_date(cr, uid, ids, context=context)
return expiry_date
def modify_expiry_date(self, cr, uid, ids, context=None):
'''
open modify expiry date wizard
'''
# basic check
if context is None:
context = {}
# data
name = _("Modify Expiry Date")
model = 'modify.expiry.date'
step = 'default'
wiz_obj = self.pool.get('wizard')
# get the date
data = self.read(cr, uid, ids, ['composition_exp'], context=context)[0]
date = data['composition_exp']
# open the selected wizard
res = wiz_obj.open_wizard(cr, uid, ids, name=name, model=model, step=step, context=dict(context,
kit_id=ids[0],
date=date))
return res
def mark_as_completed(self, cr, uid, ids, context=None):
'''
button function
set the state to 'completed'
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
for obj in self.browse(cr, uid, ids, context=context):
if not len(obj.composition_item_ids):
raise osv.except_osv(_('Warning !'), _('Kit Composition cannot be empty.'))
if not obj.active:
raise osv.except_osv(_('Warning !'), _('Cannot complete inactive kit.'))
for item in obj.composition_item_ids:
if item.item_qty <= 0:
raise osv.except_osv(_('Warning !'), _('Kit Items must have a quantity greater than 0.0.'))
self.write(cr, uid, ids, {'state': 'completed'}, context=context)
return True
def mark_as_inactive(self, cr, uid, ids, context=None):
'''
button function
set the active flag to False
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
for obj in self.browse(cr, uid, ids, context=context):
if obj.composition_type != 'theoretical':
raise osv.except_osv(_('Warning !'), _('Only theoretical kit can manipulate "active" field.'))
self.write(cr, uid, ids, {'active': False}, context=context)
return True
def mark_as_active(self, cr, uid, ids, context=None):
'''
button function
set the active flag to False
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
for obj in self.browse(cr, uid, ids, context=context):
if obj.composition_type != 'theoretical':
raise osv.except_osv(_('Warning !'), _('Only theoretical kit can manipulate "active" field.'))
self.write(cr, uid, ids, {'active': True}, context=context)
return True
def close_kit(self, cr, uid, ids, context=None):
'''
button function
set the state to 'done'
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
self.write(cr, uid, ids, {'state': 'done'}, context=context)
return True
def reset_to_version(self, cr, uid, ids, context=None):
'''
open confirmation wizard
'''
# data
name = _("Reset Items to Version Reference. Are you sure?")
model = 'confirm'
step = 'default'
question = 'The item list of current composition list will be reset to reference list from the selected Version. Are you sure ?'
clazz = 'composition.kit'
func = 'do_reset_to_version'
args = [ids]
kwargs = {}
# to reset to version
for obj in self.browse(cr, uid, ids, context=context):
# must be a real kit
if obj.composition_type != 'real':
raise osv.except_osv(_('Warning !'), _('Only composition lists can be reset to a version.'))
# a version must have been selected
if not obj.composition_version_id:
raise osv.except_osv(_('Warning !'), _('The composition list is not linked to any version.'))
wiz_obj = self.pool.get('wizard')
# open the selected wizard
res = wiz_obj.open_wizard(cr, uid, ids, name=name, model=model, step=step, context=dict(context, question=question,
callback={'clazz': clazz,
'func': func,
'args': args,
'kwargs': kwargs}))
return res
def do_reset_to_version(self, cr, uid, ids, context=None):
'''
remove all items and create one item for each item from the referenced version
'''
# objects
item_obj = self.pool.get('composition.item')
# unlink all composition items corresponding to selected kits
item_ids = item_obj.search(cr, uid, [('item_kit_id', 'in', ids)], context=context)
item_obj.unlink(cr, uid, item_ids, context=context)
for obj in self.browse(cr, uid, ids, context=context):
# copy all items from the version
for item_v in obj.composition_version_id.composition_item_ids:
values = {'item_module': item_v.item_module,
'item_product_id': item_v.item_product_id.id,
'item_qty': item_v.item_qty,
'item_uom_id': item_v.item_uom_id.id,
'item_lot': item_v.item_lot,
'item_exp': item_v.item_exp,
'item_kit_id': obj.id,
'item_description': item_v.item_description,
}
item_obj.create(cr, uid, values, context=context)
# we display the composition list view form
return {'name':_("Kit Composition List"),
'view_mode': 'form,tree',
'view_type': 'form',
'res_model': 'composition.kit',
'res_id': obj.id,
'type': 'ir.actions.act_window',
'target': 'dummy',
'domain': [('composition_type', '=', 'real')],
'context': {'composition_type':'real'},
}
def _generate_item_mirror_objects(self, cr, uid, ids, wizard_data, context=None):
"""
Generate memory objects as mirror for kit items, which can be modified (batch number policy needs modification,
we therefore cannot link items directly).
"""
if context is None:
context = {}
# objects
mirror_obj = self.pool.get('substitute.item.mirror')
# returned list, list of created ids
result = []
for obj in self.browse(cr, uid, ids, context=context):
for item in obj.composition_item_ids:
# create a mirror object which can be later selected and modified in the many2many field
batch_management = item.item_product_id.batch_management
perishable = item.item_product_id.perishable
values = {'wizard_id': wizard_data['res_id'],
'item_id_mirror': item.id,
'kit_id_mirror': item.item_kit_id.id,
'module_substitute_item': item.item_module,
'product_id_substitute_item': item.item_product_id.id,
'qty_substitute_item': item.item_qty,
'uom_id_substitute_item': item.item_uom_id.id,
'lot_mirror': item.item_lot,
'exp_substitute_item': item.item_exp,
'hidden_batch_management_mandatory': batch_management,
'hidden_perishable_mandatory': perishable,
}
id = mirror_obj.create(cr, uid, values, context=context)
result.append(id)
return result
def substitute_items(self, cr, uid, ids, context=None):
'''
substitute lines from the composition kit with created new lines
'''
# we need the context for the wizard switch
if context is None:
context = {}
# data
name = _("Substitute Kit Items")
model = 'substitute'
step = 'substitute'
wiz_obj = self.pool.get('wizard')
# open the selected wizard
res = wiz_obj.open_wizard(cr, uid, ids, name=name, model=model, step=step, context=dict(context, kit_id=ids[0]))
# write wizard id back in the wizard object, cannot use ID in the wizard form... openERP bug ?
self.pool.get(model).write(cr, uid, [res['res_id']], {'wizard_id': res['res_id']}, context=res['context'])
# generate mirrors item objects
self._generate_item_mirror_objects(cr, uid, ids, wizard_data=res, context=res['context'])
return res
def do_substitute(self, cr, uid, ids, context=None):
'''
call the modify expiry date window for possible modification of expiry date
'''
res = self.modify_expiry_date(cr, uid, ids, context=context)
return res
def de_kitting(self, cr, uid, ids, context=None):
'''
explode the kit, preselecting all mirror items
'''
# we need the context for the wizard switch
if context is None:
context = {}
# data
name = _("De-Kitting")
model = 'substitute'
step = 'de_kitting'
wiz_obj = self.pool.get('wizard')
# open the selected wizard
res = wiz_obj.open_wizard(cr, uid, ids, name=name, model=model, step=step, context=dict(context, kit_id=ids[0]))
# write wizard id back in the wizard object, cannot use ID in the wizard form... openERP bug ?
self.pool.get(model).write(cr, uid, [res['res_id']], {'wizard_id': res['res_id']}, context=context)
# generate mirrors item objects
data = self._generate_item_mirror_objects(cr, uid, ids, wizard_data=res, context=context)
# fill all elements into the many2many field
self.pool.get(model).write(cr, uid, [res['res_id']], {'composition_item_ids': [(6,0,data)]}, context=context)
return res
def _vals_get(self, cr, uid, ids, fields, arg, context=None):
'''
multi fields function method
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
result = {}
# date tools object
date_obj = self.pool.get('date.tools')
db_date_format = date_obj.get_db_date_format(cr, uid, context=context)
date_format = date_obj.get_date_format(cr, uid, context=context)
for obj in self.browse(cr, uid, ids, context=context):
result[obj.id] = {}
for f in fields:
result[obj.id].update({f:False})
# composition version
if obj.composition_type == 'theoretical':
result[obj.id].update({'composition_version': obj.composition_version_txt})
elif obj.composition_type == 'real':
result[obj.id].update({'composition_version': obj.composition_version_id and obj.composition_version_id.composition_version_txt or ''})
# composition_combined_ref_lot: mix between both fields reference and batch number which are exclusive fields
if obj.composition_expiry_check:
result[obj.id].update({'composition_combined_ref_lot': obj.composition_lot_id.name,
'composition_exp': obj.composition_lot_id.life_date})
else:
result[obj.id].update({'composition_combined_ref_lot': obj.composition_reference,
'composition_exp': obj.composition_ref_exp})
# name - ex: ITC - 01/01/2012
date = datetime.strptime(obj.composition_creation_date, db_date_format)
result[obj.id].update({'name': result[obj.id]['composition_version'] + ' - ' + date.strftime(date_format)})
# mandatory nomenclature levels
result[obj.id].update({'nomen_manda_0': obj.composition_product_id.nomen_manda_0.id})
result[obj.id].update({'nomen_manda_1': obj.composition_product_id.nomen_manda_1.id})
result[obj.id].update({'nomen_manda_2': obj.composition_product_id.nomen_manda_2.id})
result[obj.id].update({'nomen_manda_3': obj.composition_product_id.nomen_manda_3.id})
result[obj.id].update({'nomen_sub_0': obj.composition_product_id.nomen_sub_0.id})
result[obj.id].update({'nomen_sub_1': obj.composition_product_id.nomen_sub_1.id})
result[obj.id].update({'nomen_sub_2': obj.composition_product_id.nomen_sub_2.id})
result[obj.id].update({'nomen_sub_3': obj.composition_product_id.nomen_sub_3.id})
result[obj.id].update({'nomen_sub_4': obj.composition_product_id.nomen_sub_4.id})
result[obj.id].update({'nomen_sub_5': obj.composition_product_id.nomen_sub_5.id})
return result
def copy(self, cr, uid, id, default=None, context=None):
'''
change version name. add (copy)
- theoretical kit can be copied. version -> version (copy)
- real kit with batch number cannot be copied.
- real kit without batch but with reference can be copied. reference -> reference (copy)
'''
if default is None:
default = {}
# state
default.update(state='draft')
# original reference
data = self.read(cr, uid, id, ['composition_version_txt', 'composition_type', 'composition_reference', 'composition_lot_id'], context=context)
if data['composition_type'] == 'theoretical':
version = data['composition_version_txt']
default.update(composition_version_txt='%s (copy)'%version, composition_creation_date=time.strftime('%Y-%m-%d'))
elif data['composition_type'] == 'real' and data['composition_reference'] and not data['composition_lot_id']:
reference = data['composition_reference']
default.update(composition_reference='%s (copy)'%reference, composition_creation_date=time.strftime('%Y-%m-%d'))
else:
raise osv.except_osv(_('Warning !'), _('Kit Composition List with Batch Number cannot be copied!'))
return super(composition_kit, self).copy(cr, uid, id, default, context=context)
def unlink(self, cr, uid, ids, context=None):
'''
cannot delete composition kit not draft
'''
# Some verifications
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 Kits not in 'draft' state."))
return super(composition_kit, self).unlink(cr, uid, ids, context=context)
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 not context.get('composition_type', False) and not context.get('wizard_composition_type', False):
# view search not from a menu -> picking process wizard, we are looking for composition list - by default the theoretical search view is displayed
view = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'kit', 'view_composition_kit_real_filter')
if view:
view_id = view[1]
# second level flag for wizards
elif context.get('wizard_composition_type', False) == 'theoretical':
view = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'kit', 'view_composition_kit_theoretical_filter')
if view:
view_id = view[1]
# call super
result = super(composition_kit, self).fields_view_get(cr, uid, view_id, view_type, context=context, toolbar=toolbar, submenu=submenu)
# columns depending on type - fields from one2many field
if view_type == 'form' and context.get('composition_type', False) == 'theoretical':
# fields to be modified
list = ['<field name="item_lot"', '<field name="item_exp"']
replace_text = result['fields']['composition_item_ids']['views']['tree']['arch']
replace_text = reduce(lambda x, y: x.replace(y, y + ' invisible="True" '), [replace_text] + list)
result['fields']['composition_item_ids']['views']['tree']['arch'] = replace_text
list = ['<field name="composition_exp"', '<field name="composition_combined_ref_lot"']
# columns from kit composition tree - if we display from theoretical menu or diplay the search view of version_id from real_filter
if view_type == 'tree':
if context.get('wizard_composition_type', False) == 'theoretical' or (context.get('composition_type', False) == 'theoretical' and not context.get('wizard_composition_type', False)):
replace_text = result['arch']
replace_text = reduce(lambda x, y: x.replace(y, y + ' invisible="True" '), [replace_text] + list)
result['arch'] = replace_text
return result
def name_get(self, cr, uid, ids, context=None):
'''
override displayed name
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# date tools object
date_obj = self.pool.get('date.tools')
db_date_format = date_obj.get_db_date_format(cr, uid, context=context)
date_format = date_obj.get_date_format(cr, uid, context=context)
# result
res = []
for obj in self.browse(cr, uid, ids, context=context):
if obj.composition_type == 'theoretical':
date = datetime.strptime(obj.composition_creation_date, db_date_format)
name = obj.composition_version + ' - ' + date.strftime(date_format)
else:
name = obj.composition_combined_ref_lot
res += [(obj.id, name)]
return res
def on_change_product_id(self, cr, uid, ids, product_id, context=None):
'''
when the product is changed, lot checks are updated - mandatory workaround for attrs use
'''
# product object
prod_obj = self.pool.get('product.product')
res = {'value': {'composition_batch_check': False,
'composition_expiry_check': False,
'composition_lot_id': False,
'composition_exp': False,
'composition_reference': False,
'composition_ref_exp': False,
'composition_version_id': False,
'composition_version_txt': False}}
if not product_id:
return res
data = prod_obj.read(cr, uid, [product_id], ['perishable', 'batch_management'], context=context)[0]
res['value']['composition_batch_check'] = data['batch_management']
res['value']['composition_expiry_check'] = data['perishable']
return res
def on_change_lot_id(self, cr, uid, ids, lot_id, context=None):
'''
when the lot is changed, expiry date is updated, so the field is modified before the save happens
'''
# product object
lot_obj = self.pool.get('stock.production.lot')
res = {'value': {'composition_exp': False,
'composition_ref_exp': False}}
if not lot_id:
return res
data = lot_obj.read(cr, uid, [lot_id], ['life_date'], context=context)[0]
res['value']['composition_exp'] = data['life_date']
return res
def _get_composition_kit_from_product_ids(self, cr, uid, ids, context=None):
'''
ids represents the ids of product.product objects for which values have changed
return the list of ids of composition.kit objects which need to get their fields updated
self is product.product object
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
kit_obj = self.pool.get('composition.kit')
result = kit_obj.search(cr, uid, [('composition_product_id', 'in', ids)], context=context)
return result
def _get_composition_kit_from_lot_ids(self, cr, uid, ids, context=None):
'''
ids represents the ids of stock.production.lot objects for which values have changed
return the list of ids of composition.kit objects which need to get their fields updated
self is stock.production.lot object
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
kit_obj = self.pool.get('composition.kit')
result = kit_obj.search(cr, uid, [('composition_lot_id', 'in', ids)], context=context)
return result
def onChangeSearchNomenclature(self, cr, uid, ids, position, type, nomen_manda_0, nomen_manda_1, nomen_manda_2, nomen_manda_3, num=True, context=None):
prod_obj = self.pool.get('product.product')
return prod_obj.onChangeSearchNomenclature(cr, uid, ids, position, type, nomen_manda_0, nomen_manda_1, nomen_manda_2, nomen_manda_3, num=num, context=context)
def _get_nomen_s(self, cr, uid, ids, fields, *a, **b):
prod_obj = self.pool.get('product.template')
return prod_obj._get_nomen_s(cr, uid, ids, fields, *a, **b)
def _search_nomen_s(self, cr, uid, obj, name, args, context=None):
prod_obj = self.pool.get('product.template')
return prod_obj._search_nomen_s(cr, uid, obj, name, args, context=context)
def _set_expiry_date(self, cr, uid, ids, field, value, arg, context=None):
"""
if the kit is linked to a batch management product, we update the expiry date for the correponding batch number
else we udpate the composition_ref_exp field
"""
if not value or field != 'composition_exp':
return False
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# objects
lot_obj = self.pool.get('stock.production.lot')
# date tools object
date_obj = self.pool.get('date.tools')
db_date_format = date_obj.get_db_date_format(cr, uid, context=context)
date_format = date_obj.get_date_format(cr, uid, context=context)
for obj in self.browse(cr, uid, ids, context=context):
if obj.composition_expiry_check:
# a lot is linked, we update its expiry date
lot_obj.write(cr, uid, [obj.composition_lot_id.id], {'life_date': value}, context=context)
lot_name = obj.composition_lot_id.name
prod_name = obj.composition_product_id.name
exp_obj = datetime.strptime(value, db_date_format)
lot_obj.log(cr, uid, obj.composition_lot_id.id, _('Expiry Date of Batch Number %s for product %s has been updated to %s.'%(lot_name,prod_name,exp_obj.strftime(date_format))))
else:
# not lot because the product is not batch managment, we have a reference instead, we write in composition_ref_exp
self.write(cr, uid, ids, {'composition_ref_exp': value}, context=context)
return True
_columns = {'composition_type': fields.selection(KIT_COMPOSITION_TYPE, string='Composition Type', readonly=True, required=True),
'composition_description': fields.text(string='Composition Description'),
'composition_product_id': fields.many2one('product.product', string='Product', required=True, domain=[('type', '=', 'product'), ('subtype', '=', 'kit')]),
'composition_version_txt': fields.char(string='Version', size=1024),
'composition_version_id': fields.many2one('composition.kit', string='Version'),
'composition_creation_date': fields.date(string='Creation Date', required=True),
'composition_reference': fields.char(string='Reference', size=1024),
'composition_lot_id': fields.many2one('stock.production.lot', string='Batch Nb'),
'composition_ref_exp': fields.date(string='Expiry Date for Kit with reference', readonly=True),
# 'composition_kit_creation_id': fields.many2one('kit.creation', string='Kitting Order', readonly=True),
'composition_item_ids': fields.one2many('composition.item', 'item_kit_id', string='Items'),
'active': fields.boolean('Active', readonly=True),
'state': fields.selection(KIT_STATE, string='State', readonly=True, required=True),
# related
'composition_batch_check': fields.related('composition_product_id', 'batch_management', type='boolean', string='Batch Number Mandatory', readonly=True, store=False),
# expiry is always true if batch_check is true. we therefore use expry_check for now in the code
'composition_expiry_check': fields.related('composition_product_id', 'perishable', type='boolean', string='Expiry Date Mandatory', readonly=True, store=False),
# functions
'name': fields.function(_vals_get, method=True, type='char', size=1024, string='Name', multi='get_vals',
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),}),
'composition_version': fields.function(_vals_get, method=True, type='char', size=1024, string='Version', multi='get_vals',
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_version_txt', 'composition_version_id'], 10),}),
'composition_exp': fields.function(_vals_get, fnct_inv=_set_expiry_date, method=True, type='date', size=1024, string='Expiry Date', multi='get_vals', readonly=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_ref_exp', 'composition_lot_id'], 10),
'stock.production.lot': (_get_composition_kit_from_lot_ids, ['life_date'], 10)}),
'composition_combined_ref_lot': fields.function(_vals_get, method=True, type='char', size=1024, string='Ref/Batch Nb', multi='get_vals',
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_lot_id', 'composition_reference'], 10),}),
# nomenclature
'nomen_manda_0': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Main Type', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_manda_0', 'nomen_manda_1', 'nomen_manda_2', 'nomen_manda_3'], 10),}),
'nomen_manda_1': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Group', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_manda_0', 'nomen_manda_1', 'nomen_manda_2', 'nomen_manda_3'], 10),}),
'nomen_manda_2': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Family', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_manda_0', 'nomen_manda_1', 'nomen_manda_2', 'nomen_manda_3'], 10),}),
'nomen_manda_3': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Root', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_manda_0', 'nomen_manda_1', 'nomen_manda_2', 'nomen_manda_3'], 10),}),
'nomen_manda_0_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Main Type', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_manda_1_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Group', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_manda_2_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Family', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_manda_3_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Root', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_sub_0': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 1', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_sub_0', 'nomen_sub_1', 'nomen_sub_2', 'nomen_sub_3', 'nomen_sub_4', 'nomen_sub_5'], 10),}),
'nomen_sub_1': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 2', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_sub_0', 'nomen_sub_1', 'nomen_sub_2', 'nomen_sub_3', 'nomen_sub_4', 'nomen_sub_5'], 10),}),
'nomen_sub_2': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 3', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_sub_0', 'nomen_sub_1', 'nomen_sub_2', 'nomen_sub_3', 'nomen_sub_4', 'nomen_sub_5'], 10),}),
'nomen_sub_3': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 4', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_sub_0', 'nomen_sub_1', 'nomen_sub_2', 'nomen_sub_3', 'nomen_sub_4', 'nomen_sub_5'], 10),}),
'nomen_sub_4': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 5', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_sub_0', 'nomen_sub_1', 'nomen_sub_2', 'nomen_sub_3', 'nomen_sub_4', 'nomen_sub_5'], 10),}),
'nomen_sub_5': fields.function(_vals_get, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 6', multi='get_vals', readonly=True, select=True,
store= {'composition.kit': (lambda self, cr, uid, ids, c=None: ids, ['composition_product_id'], 10),
'product.template': (_get_composition_kit_from_product_ids, ['nomen_sub_0', 'nomen_sub_1', 'nomen_sub_2', 'nomen_sub_3', 'nomen_sub_4', 'nomen_sub_5'], 10),}),
'nomen_sub_0_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 1', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_sub_1_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 2', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_sub_2_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 3', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_sub_3_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 4', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_sub_4_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 5', fnct_search=_search_nomen_s, multi="nom_s"),
'nomen_sub_5_s': fields.function(_get_nomen_s, method=True, type='many2one', relation='product.nomenclature', string='Sub Class 6', fnct_search=_search_nomen_s, multi="nom_s"),
}
_defaults = {'composition_creation_date': lambda *a: time.strftime('%Y-%m-%d'),
'composition_type': lambda s, cr, uid, c: c.get('composition_type', False),
'composition_product_id': lambda s, cr, uid, c: c.get('composition_product_id', False),
'composition_lot_id': lambda s, cr, uid, c: c.get('composition_lot_id', False),
'composition_exp': lambda s, cr, uid, c: c.get('composition_exp', False),
'composition_batch_check': lambda s, cr, uid, c: c.get('composition_batch_check', False),
'composition_expiry_check': lambda s, cr, uid, c: c.get('composition_expiry_check', False),
'active': True,
'state': 'draft',
}
_order = 'composition_creation_date desc'
def _composition_kit_constraint(self, cr, uid, ids, context=None):
'''
constraint on kit composition - two kits
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
for obj in self.browse(cr, uid, ids, context=context):
# global
if obj.composition_product_id.type != 'product' or obj.composition_product_id.subtype != 'kit':
raise osv.except_osv(_('Warning !'), _('Only Kit products can be used for kits.'))
# theoretical constraints
if obj.composition_type == 'theoretical':
search_ids = self.search(cr, uid, [('id', '!=', obj.id),
('composition_product_id', '=', obj.composition_product_id.id),
('composition_version_txt', '=ilike', obj.composition_version_txt),
('composition_creation_date', '=', obj.composition_creation_date)], context=context)
if search_ids:
#print self.read(cr, uid, ids, ['composition_product_id', 'composition_version_txt', 'composition_creation_date'], context=context)
raise osv.except_osv(_('Warning !'), _('The dataset (Product - Version - Creation Date) must be unique.'))
# constraint on lot_id/reference/expiry date - forbidden for theoretical
if obj.composition_reference or obj.composition_lot_id or obj.composition_exp or obj.composition_ref_exp:
raise osv.except_osv(_('Warning !'), _('Composition Reference / Batch Number / Expiry date is not available for Theoretical Kit.'))
# constraint on version_id - forbidden for theoretical
if obj.composition_version_id:
raise osv.except_osv(_('Warning !'), _('Composition Version Object is not available for Theoretical Kit.'))
# real constraints
if obj.composition_type == 'real':
# constraint on lot_id/reference - mandatory for real kit
if obj.composition_batch_check or obj.composition_expiry_check:
if obj.composition_reference:
raise osv.except_osv(_('Warning !'), _('Composition List with Batch Management Product does not allow Reference.'))
if not obj.composition_lot_id:
raise osv.except_osv(_('Warning !'), _('Composition List with Batch Management Product needs Batch Number.'))
if obj.composition_ref_exp:
raise osv.except_osv(_('Warning !'), _('Composition List with Batch Management Product does not allow Reference based Expiry Date.'))
else:
if not obj.composition_reference:
raise osv.except_osv(_('Warning !'), _('Composition List without Batch Management Product needs Reference.'))
if obj.composition_lot_id:
raise osv.except_osv(_('Warning !'), _('Composition List without Batch Management Product does not allow Batch Number.'))
# real composition must always be active
if not obj.active:
raise osv.except_osv(_('Warning !'), _('Composition List cannot be inactive.'))
# check that the selected version corresponds to the selected product
if obj.composition_version_id and obj.composition_version_id.composition_product_id.id != obj.composition_product_id.id:
raise osv.except_osv(_('Warning !'), _('Selected Version is for a different product.'))
return True
_constraints = [(_composition_kit_constraint, 'Constraint error on Composition Kit.', []),
]
_sql_constraints = [('unique_composition_kit_real_ref', "unique(composition_product_id,composition_reference)", 'Kit Composition List Reference must be unique for a given product.'),
('unique_composition_kit_real_lot', "unique(composition_lot_id)", 'Batch Number can only be used by one Kit Composition List.'),
]
composition_kit()
class composition_item(osv.osv):
'''
kit composition items representing kit parts
'''
_name = 'composition.item'
def create(self, cr, uid, vals, context=None):
'''
force writing of expired_date which is readonly for batch management products
'''
# objects
prod_obj = self.pool.get('product.product')
prodlot_obj = self.pool.get('stock.production.lot')
if 'item_product_id' in vals:
if vals['item_product_id']:
product_id = vals['item_product_id']
data = prod_obj.read(cr, uid, [product_id], ['perishable', 'batch_management'], context=context)[0]
management = data['batch_management']
perishable = data['perishable']
# if management and we have a lot_id, we fill the expiry date
if management and vals.get('item_lot'):
prodlot_id = vals.get('item_lot')
prod_ids = prodlot_obj.search(cr, uid, [('name', '=', prodlot_id),
('type', '=', 'standard'),
('product_id', '=', product_id)], context=context)
# if it exists, we set the date
if prod_ids:
prodlot_id = prod_ids[0]
data = prodlot_obj.read(cr, uid, [prodlot_id], ['life_date'], context=context)
expired_date = data[0]['life_date']
vals.update({'item_exp': expired_date})
elif perishable:
# nothing special here
pass
else:
# not perishable nor management, exp and lot are False
vals.update(item_lot=False, item_exp=False)
else:
# product is False, exp and lot are set to False
vals.update(item_lot=False, item_exp=False)
return super(composition_item, self).create(cr, uid, vals, context=context)
def write(self, cr, uid, ids, vals, context=None):
'''
force writing of expired_date which is readonly for batch management products
'''
# objects
prod_obj = self.pool.get('product.product')
prodlot_obj = self.pool.get('stock.production.lot')
if 'item_product_id' in vals:
if vals['item_product_id']:
product_id = vals['item_product_id']
data = prod_obj.read(cr, uid, [product_id], ['perishable', 'batch_management'], context=context)[0]
management = data['batch_management']
perishable = data['perishable']
# if management and we have a lot_id, we fill the expiry date
if management and vals.get('item_lot'):
prodlot_id = vals.get('item_lot')
prod_ids = prodlot_obj.search(cr, uid, [('name', '=', prodlot_id),
('type', '=', 'standard'),
('product_id', '=', product_id)], context=context)
# if it exists, we set the date
if prod_ids:
prodlot_id = prod_ids[0]
data = prodlot_obj.read(cr, uid, [prodlot_id], ['life_date'], context=context)
expired_date = data[0]['life_date']
vals.update({'item_exp': expired_date})
elif perishable:
# nothing special here
pass
else:
# not perishable nor management, exp and lot are False
vals.update(item_lot=False, item_exp=False)
else:
# product is False, exp and lot are set to False
vals.update(item_lot=False, item_exp=False)
return super(composition_item, self).write(cr, uid, ids, vals, context=context)
def on_product_change(self, cr, uid, ids, product_id, context=None):
'''
product is changed, we update the UoM
'''
# objects
prod_obj = self.pool.get('product.product')
result = {'value': {'item_uom_id': False,
'item_qty': 0.0,
'hidden_perishable_mandatory': False,
'hidden_batch_management_mandatory': False,
'item_exp': False,
'item_lot': False,
}}
if product_id:
product = prod_obj.browse(cr, uid, product_id, context=context)
result['value']['item_uom_id'] = product.uom_po_id.id
result['value']['hidden_perishable_mandatory'] = product.perishable
result['value']['hidden_batch_management_mandatory'] = product.batch_management
return result
def on_lot_change(self, cr, uid, ids, product_id, prodlot_id, context=None):
'''
if lot exists in the system the date is filled in
prodlot_id is the NAME of the production lot
'''
# objects
prod_obj = self.pool.get('product.product')
prodlot_obj = self.pool.get('stock.production.lot')
# result
result = {'value': {}}
if product_id:
data = prod_obj.read(cr, uid, [product_id], ['perishable', 'batch_management'], context=context)[0]
management = data['batch_management']
perishable = data['perishable']
if management and prodlot_id:
prod_ids = prodlot_obj.search(cr, uid, [('name', '=', prodlot_id),
('type', '=', 'standard'),
('product_id', '=', product_id)], context=context)
# if it exists, we set the date
if prod_ids:
prodlot_id = prod_ids[0]
result['value'].update(item_exp=prodlot_obj.browse(cr, uid, prodlot_id, context=context).life_date)
return result
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(composition_item, self).fields_view_get(cr, uid, view_id, view_type, context=context, toolbar=toolbar, submenu=submenu)
# columns depending on type
if view_type == 'tree' and context.get('composition_type', False) == 'theoretical':
# fields to be modified
list = ['<field name="item_lot"', '<field name="item_exp"']
replace_text = result['arch']
replace_text = reduce(lambda x, y: x.replace(y, y+ ' invisible="True" '), [replace_text] + list)
result['arch'] = replace_text
return result
def _vals_get(self, cr, uid, ids, fields, arg, context=None):
'''
multi fields function method
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
result = {}
for obj in self.browse(cr, uid, ids, context=context):
result[obj.id] = {}
# name
result[obj.id].update({'name': obj.item_product_id.name})
# version
result[obj.id].update({'item_kit_version': obj.item_kit_id.composition_version})
# type
result[obj.id].update({'item_kit_type': obj.item_kit_id.composition_type})
# state
result[obj.id].update({'state': obj.item_kit_id.state})
# batch management
result[obj.id].update({'hidden_batch_management_mandatory': obj.item_product_id.batch_management})
# perishable
result[obj.id].update({'hidden_perishable_mandatory': obj.item_product_id.perishable})
return result
def name_get(self, cr, uid, ids, context=None):
'''
override displayed name
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# date tools object
date_obj = self.pool.get('date.tools')
date_format = date_obj.get_date_format(cr, uid, context=context)
# result
res = []
for obj in self.browse(cr, uid, ids, context=context):
name = obj.item_product_id.name
res += [(obj.id, name)]
return res
def _get_composition_item_ids(self, cr, uid, ids, context=None):
'''
ids represents the ids of composition.kit objects for which values have changed
return the list of ids of composition.item objects which need to get their fields updated
self is an composition.kit object
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
item_obj = self.pool.get('composition.item')
result = item_obj.search(cr, uid, [('item_kit_id', 'in', ids)], context=context)
return result
_columns = {'item_module': fields.char(string='Module', size=1024),
'item_product_id': fields.many2one('product.product', string='Product', required=True),
'item_qty': fields.float(string='Qty', digits_compute=dp.get_precision('Product UoM'), required=True),
'item_uom_id': fields.many2one('product.uom', string='UoM', required=True),
'item_lot': fields.char(string='Batch Nb', size=1024),
'item_exp': fields.date(string='Expiry Date'),
'item_kit_id': fields.many2one('composition.kit', string='Kit', ondelete='cascade', required=True, readonly=True),
'item_description': fields.text(string='Item Description'),
'item_stock_move_id': fields.many2one('stock.move', string='Kitting Order Stock Move', readonly=True, help='This field represents the stock move corresponding to this item for Kit production.'),
# functions
'name': fields.function(_vals_get, method=True, type='char', size=1024, string='Name', multi='get_vals',
store= {'composition.item': (lambda self, cr, uid, ids, c=None: ids, ['item_product_id'], 10),}),
'item_kit_version': fields.function(_vals_get, method=True, type='char', size=1024, string='Kit Version', multi='get_vals',
store= {'composition.item': (lambda self, cr, uid, ids, c=None: ids, ['item_kit_id'], 10),
'composition.kit': (_get_composition_item_ids, ['composition_version_txt', 'composition_version_id'], 10)}),
'item_kit_type': fields.function(_vals_get, method=True, type='char', size=1024, string='Kit Type', multi='get_vals',
store= {'composition.item': (lambda self, cr, uid, ids, c=None: ids, ['item_kit_id'], 10),
'composition.kit': (_get_composition_item_ids, ['composition_type'], 10)}),
'state': fields.function(_vals_get, method=True, type='selection', selection=KIT_STATE, string='State', readonly=True, multi='get_vals',
store= {'composition.item': (lambda self, cr, uid, ids, c=None: ids, ['item_kit_id'], 10),
'composition.kit': (_get_composition_item_ids, ['state'], 10)}),
'hidden_perishable_mandatory': fields.function(_vals_get, method=True, type='boolean', string='Exp', multi='get_vals', store=False, readonly=True),
'hidden_batch_management_mandatory': fields.function(_vals_get, method=True, type='boolean', string='B.Num', multi='get_vals', store=False, readonly=True),
}
_defaults = {'hidden_batch_management_mandatory': False,
'hidden_perishable_mandatory': False}
def _composition_item_constraint(self, cr, uid, ids, context=None):
'''
constraint on item composition
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
for obj in self.browse(cr, uid, ids, context=context):
if not obj.hidden_perishable_mandatory:
# no lot or date management product
if obj.item_lot:
# not perishable nor batch management - no item_lot nor item_exp
raise osv.except_osv(_('Warning !'), _('Only Batch Number Mandatory Product can specify Batch Number.'))
if obj.item_exp:
# not perishable nor batch management - no item_lot nor item_exp
raise osv.except_osv(_('Warning !'), _('Only Batch Number Mandatory or Expiry Date Mandatory can specify Expiry Date.'))
return True
_constraints = [(_composition_item_constraint, 'Constraint error on Composition Item.', []),]
composition_item()
class product_product(osv.osv):
'''
add a constraint - a product of subtype 'kit' cannot be perishable only, should be batch management or nothing
'''
_inherit = 'product.product'
def _kit_product_constraints(self, cr, uid, ids, context=None):
'''
constraint on product
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
for obj in self.browse(cr, uid, ids, context=context):
# kit
if obj.type == 'product' and obj.subtype == 'kit':
if obj.perishable and not obj.batch_management:
raise osv.except_osv(_('Warning !'), _('The Kit product cannot be Expiry Date Mandatory only.'))
return True
_constraints = [(_kit_product_constraints, 'Constraint error on Kit Product.', []),
]
product_product()
class product_nomenclature(osv.osv):
'''
decorator over
def _getNumberOfProducts(self, cr, uid, ids, field_name, arg, context=None):
'''
_inherit = 'product.nomenclature'
def _getNumberOfProducts(self, cr, uid, ids, field_name, arg, context=None):
'''
check if we are concerned with composition kit, if we do, we return the number of concerned kit, not product
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
if context.get('composition_type', False):
composition_type = context.get('composition_type')
res = {}
for nomen in self.browse(cr, uid, ids, context=context):
name = ''
if nomen.type == 'mandatory':
name = 'nomen_manda_%s'%nomen.level
if nomen.type == 'optional':
name = 'nomen_sub_%s'%nomen.sub_level
kit_ids = self.pool.get('composition.kit').search(cr, uid, [('composition_type', '=', composition_type), (name, '=', nomen.id)], context=context)
if not kit_ids:
res[nomen.id] = 0
else:
res[nomen.id] = len(kit_ids)
return res
else:
return super(product_nomenclature, self)._getNumberOfProducts(cr, uid, ids, field_name, arg, context=context)
_columns = {'number_of_products': fields.function(_getNumberOfProducts, type='integer', method=True, store=False, string='Number of Products', readonly=True),
}
product_nomenclature()
class stock_move(osv.osv):
'''
add the new method self.create_composition_list
'''
_inherit= 'stock.move'
def create_composition_list(self, cr, uid, ids, context=None):
'''
return the form view of composition_list (real) with corresponding values from the context
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
obj = self.browse(cr, uid, ids[0], context=context)
composition_type = 'real'
composition_product_id = obj.product_id.id
composition_lot_id = obj.prodlot_id and obj.prodlot_id.id or False
composition_exp = obj.expired_date
composition_batch_check = obj.product_id.batch_management
composition_expiry_check = obj.product_id.perishable
return {'name': 'Kit Composition List',
'view_id': False,
'view_type': 'form',
'view_mode': 'form,tree',
'res_model': 'composition.kit',
'res_id': False,
'type': 'ir.actions.act_window',
'nodestroy': False,
'target': False,
'domain': "[('composition_type', '=', 'real')]",
'context': dict(context,
composition_type=composition_type,
composition_product_id=composition_product_id,
composition_lot_id=composition_lot_id,
composition_exp=composition_exp, # set so we do not need to wait the save to see the expiry date
composition_batch_check=composition_batch_check,
composition_expiry_check=composition_expiry_check,
)
}
def _do_partial_hook(self, cr, uid, ids, context, *args, **kwargs):
'''
hook to update defaults data
'''
# variable parameters
move = kwargs.get('move')
assert move, 'missing move'
partial_datas = kwargs.get('partial_datas')
assert partial_datas, 'missing partial_datas'
# calling super method
defaults = super(stock_move, self)._do_partial_hook(cr, uid, ids, context, *args, **kwargs)
assert defaults is not None
kit_id = partial_datas.get('move%s'%(move.id), False).get('composition_list_id')
if kit_id:
defaults.update({'composition_list_id': kit_id})
return defaults
_columns = {'composition_list_id': fields.many2one('composition.kit', string='Kit', readonly=True)}
stock_move()
class stock_location(osv.osv):
'''
add a new reservation method, taking production lot into account
'''
_inherit = 'stock.location'
def compute_availability(self, cr, uid, ids, consider_child_locations, product_id, uom_id, context=None):
'''
call stock computation function
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# objects
loc_obj = self.pool.get('stock.location')
# do we want the child location
stock_context = dict(context, compute_child=consider_child_locations)
# we check for the available qty (in:done, out: assigned, done)
res = loc_obj._product_reserve_lot(cr, uid, ids, product_id, uom_id, context=stock_context, lock=True)
#print res
return res
def _product_reserve_lot(self, cr, uid, ids, product_id, uom_id, context=None, lock=False):
"""
refactoring of original reserver method, taking production lot into account
returning the original list-tuple structure + the total qty in each location
"""
result = []
amount = 0.0
if context is None:
context = {}
# objects
pool_uom = self.pool.get('product.uom')
# location ids depends on the compute_child parameter from the context
if context.get('compute_child', True):
location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)], context=context)
else:
location_ids = ids
# fefo list of lot
fefo_list = []
# data structure
data = {'fefo': fefo_list, 'total': 0.0}
for id in location_ids:
# set up default value
data.setdefault(id, {}).setdefault('total', 0.0)
# lock the database if needed
if lock:
try:
# Must lock with a separate select query because FOR UPDATE can't be used with
# aggregation/group by's (when individual rows aren't identifiable).
# We use a SAVEPOINT to be able to rollback this part of the transaction without
# failing the whole transaction in case the LOCK cannot be acquired.
cr.execute("SAVEPOINT stock_location_product_reserve")
cr.execute("""SELECT id FROM stock_move
WHERE product_id=%s AND
(
(location_dest_id=%s AND
location_id<>%s AND
state='done')
OR
(location_id=%s AND
location_dest_id<>%s AND
state in ('done', 'assigned'))
)
FOR UPDATE of stock_move NOWAIT""", (product_id, id, id, id, id), log_exceptions=False)
except Exception:
# Here it's likely that the FOR UPDATE NOWAIT failed to get the LOCK,
# so we ROLLBACK to the SAVEPOINT to restore the transaction to its earlier
# state, we return False as if the products were not available, and log it:
cr.execute("ROLLBACK TO stock_location_product_reserve_lot")
logger = logging.getLogger('stock.location')
logger.warn("Failed attempt to reserve product %s, likely due to another transaction already in progress. Next attempt is likely to work. Detailed error available at DEBUG level.", product_id)
logger.debug("Trace of the failed product reservation attempt: ", exc_info=True)
return False
# SQL request is FEFO by default
# TODO merge different UOM directly in SQL statement
# example in class stock_report_prodlots_virtual(osv.osv): in report_stock_virtual.py
# class report_stock_inventory(osv.osv): in specific_rules.py
cr.execute("""
SELECT subs.product_uom, subs.prodlot_id, subs.expired_date, sum(subs.product_qty) AS product_qty FROM
(SELECT product_uom, prodlot_id, expired_date, sum(product_qty) AS product_qty
FROM stock_move
WHERE location_dest_id=%s AND
location_id<>%s AND
product_id=%s AND
state='done'
GROUP BY product_uom, prodlot_id, expired_date
UNION
SELECT product_uom, prodlot_id, expired_date, -sum(product_qty) AS product_qty
FROM stock_move
WHERE location_id=%s AND
location_dest_id<>%s AND
product_id=%s AND
state in ('done', 'assigned')
GROUP BY product_uom, prodlot_id, expired_date) as subs
GROUP BY product_uom, prodlot_id, expired_date
ORDER BY prodlot_id asc, expired_date asc
""",
(id, id, product_id, id, id, product_id))
results = cr.dictfetchall()
# merge results according to uom if needed
for r in results:
# consolidates the uom
amount = pool_uom._compute_qty(cr, uid, r['product_uom'], r['product_qty'], uom_id)
# total for all locations
total = data.setdefault('total', 0.0)
total += amount
data.update({'total': total})
# fill the data structure, total value for location
loc_tot = data.setdefault(id, {}).setdefault('total', 0.0)
loc_tot += amount
data.setdefault(id, {}).update({'total': loc_tot})
# production lot
lot_tot = data.setdefault(id, {}).setdefault(r['prodlot_id'], {}).setdefault('total', 0.0)
lot_tot += amount
data.setdefault(id, {}).setdefault(r['prodlot_id'], {}).update({'total': lot_tot, 'date': r['expired_date']})
# update the fefo list - will be sorted when all location has been treated - we can test only the last one, thanks to ORDER BY sql request
# only positive amount are taken into account
if r['prodlot_id']:
# FEFO logic is only meaningful if a production lot is associated
if fefo_list and fefo_list[-1]['location_id'] == id and fefo_list[-1]['prodlot_id'] == r['prodlot_id']:
# simply update the qty
if lot_tot > 0:
fefo_list[-1].update({'qty': lot_tot})
else:
fefo_list.pop(-1)
elif lot_tot > 0:
# append a new dic
fefo_list.append({'location_id': id,
'uom_id': uom_id,
'expired_date': r['expired_date'],
'prodlot_id': r['prodlot_id'],
'product_id': product_id,
'qty': lot_tot})
# global FEFO sorting
data['fefo'] = sorted(fefo_list, cmp=lambda x, y: cmp(x.get('expired_date'), y.get('expired_date')), reverse=False)
return data
stock_location()
class stock_picking(osv.osv):
'''
treat the composition list
'''
_inherit = 'stock.picking'
def _do_partial_hook(self, cr, uid, ids, context, *args, **kwargs):
'''
hook to update defaults data
'''
# variable parameters
move = kwargs.get('move')
assert move, 'missing move'
partial_datas = kwargs.get('partial_datas')
assert partial_datas, 'missing partial_datas'
# calling super method
defaults = super(stock_picking, self)._do_partial_hook(cr, uid, ids, context, *args, **kwargs)
kit_id = partial_datas.get('move%s'%(move.id), False).get('composition_list_id')
if kit_id:
defaults.update({'composition_list_id': kit_id})
return defaults
stock_picking()
class purchase_order_line(osv.osv):
'''
add theoretical de-kitting capabilities
'''
_inherit = 'purchase.order.line'
def de_kitting(self, cr, uid, ids, context=None):
'''
open theoretical kit selection
'''
if context is None:
context = {}
# data
name = _("Replacement Items Selection")
model = 'kit.selection'
step = 'default'
wiz_obj = self.pool.get('wizard')
# this purchase order line replacement function can only be used when the po is in state ('confirmed', 'Validated'),
for obj in self.browse(cr, uid, ids, context=context):
if obj.po_state_stored != 'confirmed':
raise osv.except_osv(_('Warning !'), _('Purchase order line kit replacement with components function is only available for Validated state.'))
# open the selected wizard
data = self.read(cr, uid, ids, ['product_id'], context=context)[0]
product_id = data['product_id'][0]
res = wiz_obj.open_wizard(cr, uid, ids, name=name, model=model, step=step, context=dict(context,
product_id=product_id))
return res
def _vals_get(self, cr, uid, ids, fields, arg, context=None):
'''
multi fields function method
'''
# Some verifications
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
# objects
kit_obj = self.pool.get('composition.kit')
result = {}
for obj in self.browse(cr, uid, ids, context=context):
result[obj.id] = {'kit_pol_check': False}
# we want the possibility to explose the kit within the purchase order
# - the product is a kit AND
# - at least one theoretical kit exists for this product - is displayed anyway, because the user can now add products not from the theoretical template
product = obj.product_id
if product.type == 'product' and product.subtype == 'kit':
result[obj.id].update({'kit_pol_check': True})
# kit_ids = kit_obj.search(cr, uid, [('composition_type', '=', 'theoretical'), ('state', '=', 'completed'), ('composition_product_id', '=', product.id)], context=context)
# if kit_ids:
# result[obj.id].update({'kit_pol_check': True})
return result
_columns = {'kit_pol_check' : fields.function(_vals_get, method=True, string='Kit Mem Check', type='boolean', readonly=True, multi='get_vals_kit'),
}
purchase_order_line()
|