~avanzosc-manufactuaring-team/avanzosc/manufacturing-6.0

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
# -*- encoding: utf-8 -*-
##############################################################################
#
#    Copyright (c) 2011 Ting & Avanzosc (http://www.openerpsite.com) All Rights Reserved.
#
#    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
from dateutil.relativedelta import relativedelta

from osv import osv, fields
from tools.translate import _
import netsvc
import time
import decimal_precision as dp
from dateutil.relativedelta import *
from datetime import datetime

class mrp_fixed_cost(osv.osv):
    _name = 'mrp.fixed.cost'
    _description = 'MRP fixed costs'
    _columns = {
                'name': fields.char('Description', size = 256),
                'amount': fields.float('Amount'),
                'estimated': fields.float('Estimated amount'),
                'production_id': fields.many2one('mrp.production','Bom'),
                'created': fields.boolean ('created')
                }
    _defaults = {
                 'created': False
                 }

mrp_fixed_cost()


class mrp_production_operation(osv.osv):
    _name = 'mrp.production.operation'
    _description = 'Production Operation'

    def _calculate_time(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        operation = self.pool.get('mrp.production.operation').browse(cr, uid, ids)[0]
        if operation:
            if operation.semi_prod_qty:
                cycle = (operation.semi_prod_qty/operation.capacity_per_cycle)
            else:
                cycle = (operation.production_id.product_qty/operation.capacity_per_cycle)
            res[operation.id] = {
                    'cycle': cycle,
                    'hour': float(((operation.time_cycle * cycle) + operation.time_start + operation.time_stop) / operation.time_efficiency)
            }
        return res
    
    _columns = {
            'name': fields.char('Name', size = 64, required= True),
            'sequence': fields.integer('Sequence', size = 64, required= True),
            'descript': fields.text('Description', size= 64),    
            'product_id': fields.many2one('product.product', 'Semi-Finished Product'),
            'semi_prod_qty': fields.float('Product Qty'),
            'semi_prod_uom': fields.many2one('product.uom', 'Product UOM'),
            'semi_prod_qty_fact': fields.float('Quantity Factor'),
            'operation_id': fields.many2one('mrp.operation', 'Operation', required=True),
            'location_id': fields.many2one('stock.location', 'Operation Location', required= True, domain=[('usage','in',('internal', 'supplier'))]),
            'workcenter_id': fields.many2one('mrp.workcenter', 'Work Center', required=True),
            'production_id': fields.many2one('mrp.production', 'Work Order', required=True),
            'capacity_per_cycle': fields.float('Capacity per Cycle'),
            'time_efficiency' : fields.float('Efficiency factor', required=True),
            'time_cycle': fields.float('Time for 1 cycle (hour)', help="Time in hours for doing one cycle of the material."),
            'time_start': fields.float('Time before prod.', help="Time in hours for the setup for the material."),
            'time_stop': fields.float('Time after prod.', help="Time in hours for the cleaning."),
            'costs_hour': fields.float('Cost per hour', help="Specify Cost of Work Center per hour when using this material."),
            'costs_cycle': fields.float('Cost per cycle', help="Specify Cost of Work Center per cycle when using this material."),
            'cycle': fields.function(_calculate_time, string='Nº Cycles', method=True, type='float',
                store={'mrp.production.operation': (lambda self, cr, uid, ids, c={}: ids, None, 20)}, multi="All"),
            'hour': fields.function(_calculate_time, string='Nº Hour', method=True, type='float',
                store={'mrp.production.operation': (lambda self, cr, uid, ids, c={}: ids, None, 20)}, multi="All"),
            'final_products_ids': fields.one2many('mrp.production.final.product', 'mrp_production_operation_id', 'Final products'),        
            'components_used_ids': fields.one2many('mrp.production.product.line', 'mrp_production_operation_id', 'Components used'),
            'type':fields.selection([('fixed','Fixed'),('variable','Variable')],'Type'),
            'by_quantity':fields.boolean('By Quantity'),
            'by_unit':fields.boolean('By Unit'),
            'merma_percentage': fields.float('% Merma'),
      
    }

    _defaults = {
            'sequence': lambda *a: 1,
            'semi_prod_qty_fact': lambda *a: 1,
            'time_efficiency': lambda *a: 0,
            'cycle': lambda *a: 1.0,
            'hour': lambda *a: 0.0,
            'type': lambda *a: 'fixed',
    }

    def default_get(self, cr, uid, fields, context=None):
        if context is None:
            context = {}
        res = super(mrp_production_operation, self).default_get(cr, uid, fields, context)
        if 'name' in context.keys():
            production_id = self.pool.get('mrp.production').search(cr, uid, [('name', '=', context['name'])])
            if production_id:
                res.update({'production_id': production_id})
        return res

    def wc_onchange(self, cr, uid, ids, workcenter_id, operation_id):
        value = {}
        if workcenter_id:
            wc = self.pool.get('mrp.workcenter').browse(cr, uid, workcenter_id)
            op = self.pool.get('mrp.operation').browse(cr, uid, operation_id)
            value['location_id'] = wc.location_id.id
            value['capacity_per_cycle'] = wc.capacity_per_cycle
            value['time_efficiency'] = wc.time_efficiency
            value['time_cycle'] = wc.time_cycle
            value['time_start'] = wc.time_start
            value['time_stop'] = wc.time_stop
            value['costs_hour'] = wc.costs_hour
            value['costs_cycle'] = wc.costs_cycle
            value['name'] = '%s -> %s' % (op.name, wc.name)
        return {'value': value}

    def prod_onchange(self, cr, uid, ids, product_id):
        value = {}
        warning = {}
        if product_id:
            prod = self.pool.get('product.product').browse(cr, uid, product_id)
            if prod.default_location.usage != 'production':
                value.update({
                    'product_id': self.browse(cr, uid, ids[0]).product_id.id,
                })
                warning = {
                    'title': _("Wrong Product"),
                    'message': _("This is not a valid product. Please, select a product with 'production' location type."),
                }
            else:
                value.update({
                    'semi_prod_qty_fact': 1,
                    'semi_prod_uom': prod.product_tmpl_id.uom_id.id or False,
                })
        return {'value': value, 'warning': warning}

    def cycle_onchange(self, cr, uid, ids, time_cycle, costs_hour):
        value = {}
        costh = costs_hour * time_cycle
        value['costs_cycle'] = costh
        return {'value':value}
    
mrp_production_operation()


class mrp_production_product_line(osv.osv):
    _description = 'Production Scheduled Product'
    _inherit = 'mrp.production.product.line'

    _columns = {'mrp_production_operation_id': fields.many2one('mrp.production.operation', 'Consumed On'),
                'location_id': fields.related('product_id', 'default_location', type='many2one', relation='stock.location', string='Default Location'),
                'consuming_amount':fields.boolean('QTY Fixed'),
                # Precio de compra para componente
                'cost_price': fields.float(_('Cost Price'), digits_compute=dp.get_precision('Purchase Price')),
                # Precio standard
                'standard_price': fields.float(_('Standard Price'), digits_compute=dp.get_precision('Purchase Price')),
                # Estimado PUC
                'estimated_puc': fields.float(_('Estimated PLP'), digits_compute=dp.get_precision('Purchase Price')),
                }           

    _default = {
        'product_qty': lambda *a: 1,
    }

    def prod_onchange(self, cr, uid, ids, product_id):
        value = {}
        if product_id:
            prod = self.pool.get('product.product').browse(cr, uid, product_id)
            value['name'] = prod.name
            value['product_qty'] = 1
            value['product_uom'] = prod.product_tmpl_id.uom_id.id or False
            value['location_id'] = prod.default_location.id
        return {'value': value}

    def default_get(self, cr, uid, fields, context=None):
        if context is None:
            context = {}
        if 'production_id' in context.keys():
            return {'production_id': context['production_id']}
        if 'name' in context.keys():
            production_id = self.pool.get('mrp.production').search(cr, uid, [('name', '=', context['name'])])
            return {'production_id': production_id}
        return {}
mrp_production_product_line()


class mrp_production_final_product(osv.osv):
    _name = 'mrp.production.final.product'
    _description = 'Production Scheduled Final Product'

    _columns = {
        'name': fields.char('Name', size = 64, required = True),
        'product_id': fields.many2one('product.product', 'Product', required = True),
        'product_qty': fields.float('Product Qty', required = True),
        'product_uom': fields.many2one('product.uom', 'Product UOM', required=True, help="UoM (Unit of Measure) is the unit of measurement for the inventory control"),
        'mrp_production_operation_id': fields.many2one('mrp.production.operation', 'Produced On'),
        'location_id': fields.related('product_id', 'default_location', type='many2one', relation='stock.location', string='Default Location'),
        'production_id': fields.many2one('mrp.production', 'Final Product'),
    }

    def prod_onchange(self, cr, uid, ids, product_id):
        value = {}
        if product_id:
            prod = self.pool.get('product.product').browse(cr, uid, product_id)
            value['name'] = prod.name
            value['product_qty'] = 1
            value['product_uom'] = prod.product_tmpl_id.uom_id.id or False
            value['location_id'] = prod.default_location.id
        return {'value': value}

    def default_get(self, cr, uid, fields, context=None):
        if context is None:
            context = {}
        if 'production_id' in context.keys():
            return {'production_id': context['production_id']}
        if 'name' in context.keys():
            production_id = self.pool.get('mrp.production').search(cr, uid, [('name', '=', context['name'])])
            return {'production_id': production_id}
        return {}

mrp_production_final_product()


class mrp_production_users(osv.osv):
    _name = 'mrp.production.users'

    def delete_it(self, cr, uid, ids, context = None):
        self.unlink(cr, uid, ids, context = context)
        return False

    _columns = {
            'name': fields.many2one('res.users', 'User'),
            'op': fields.many2one('mrp.production.operation','Operation'),
            'prod': fields.many2one('mrp.production','Production'),
            'percent': fields.float('% Estimated'),
            'est_time':fields.float('Time Estimated'),
        }

    _default = {
        'percent': 0
     }

    def name_get(self, cr, uid, ids, context=None):
        if not ids:
            return []
        result = []
        for line in self.browse(cr, uid, ids, context=context):
            if line.name:
                result.append((line.id, (line.name.name or '')))
            else:
                result.append((line.id, line.name))
        return result

mrp_production_users()


class mrp_production(osv.osv):
    
    def _calc_product_uos_qty(self, cr, uid, ids, prop, arg, context=None):
        product_obj = self.pool.get('product.product')
        res = {}     
        for production in self.browse(cr, uid, ids, context=context):
            if production.product_id and production.product_qty:
                product = product_obj.browse(cr,uid,production.product_id.id)
                if product.uos_coeff:
                    res[production.id] = production.product_qty * product.uos_coeff
  
        return res    
    
    _inherit = "mrp.production"
    _columns = {
            'bom_id': fields.many2one('mrp.bom', 'Bill of Material', readonly=True, states={'draft': [('readonly', False)]}, domain=[('bom_id','=',False)]),
            'routing_id': fields.many2one('mrp.routing', 'Routing', on_delete='set null', readonly=True, help="The list of operations (list of work centers) to produce the finished product. The routing is mainly used to compute work center costs during operations and to plan future loads on work centers based on production plannification."),
            'production_operation_ids': fields.one2many('mrp.production.operation', 'production_id', 'Production Operations', readonly=True, states={'draft':[('readonly',False)]}),
            'product_lines': fields.one2many('mrp.production.product.line', 'production_id', 'Scheduled goods', readonly=True, states={'draft':[('readonly',False)]}),
            'production_final_product_ids': fields.one2many('mrp.production.final.product', 'production_id', 'Production Final Products', readonly=True, states={'draft':[('readonly',False)]}),
            'user_ops': fields.one2many('mrp.production.users', 'prod', 'Users asignments', readonly=True, states={'draft':[('readonly',False)]}),
            'product_def_loc': fields.many2one('stock.location', 'Default Location', required=True, readonly=True, states={'draft':[('readonly',False)]}, help='Default real location of the product'),
            'location_src_id': fields.many2one('stock.location', 'Raw Materials Location', required=False,),
            'location_dest_id': fields.many2one('stock.location', 'Finished Products Location', required=False,),
            'fixed_costs':fields.one2many('mrp.fixed.cost','production_id','Fixed costs'),
            'company_id': fields.many2one('res.company', 'Company'),
            'sale_order_id':fields.many2one('sale.order', 'Sale Order', readonly=True),
            'sale_order_line_id':fields.many2one('sale.order.line', 'Sale Order Line', readonly=True),
            'partner_id': fields.related('sale_order_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'),
            'picking_ids': fields.one2many('stock.picking', 'production_id', 'Albaranes', domain=[('type','=','internal')]),
            'move_ids': fields.one2many('stock.move', 'production_id', 'Albaranes', domain=[('type','=','internal')]),
            'out_picking_ids': fields.one2many('stock.picking', 'production_id', 'Albaranes', domain=[('type','=','out')]),
            'out_move_ids': fields.one2many('stock.move', 'production_id', 'Albaranes', domain=[('type','=','out')]),
            # Precio de compra para cabecera de lista de materiales
            'mat_cost_price': fields.float(_('Mat.Cost Price'), digits_compute=dp.get_precision('Purchase Price'), readonly=True),
            # Precio de compra para cabecera de lista de materiales
            'mat_standard_price': fields.float(_('Mat.Standard Price'), digits_compute=dp.get_precision('Purchase Price'), readonly=True),
            # Precio de compra para cabecera de lista de materiales
            'mat_estimated_puc': fields.float(_('Mat.Estimated PLP'), digits_compute=dp.get_precision('Purchase Price'), readonly=True),
            'product_uos_qty': fields.function(_calc_product_uos_qty, type='float', method=True, string='Product Uos Qty', digits_compute= dp.get_precision('Purchase Price')),
            'notes': fields.text('Notes'),
            'real_product_qty': fields.float('Real Product Qty', digits_compute=dp.get_precision('Product UoM')),
            'with_generate_bysumqty': fields.boolean('With Module Generate By Sum QTY'),
            'with_advanced_operations': fields.boolean('With Module Advanced Operations'),
            'with_analytic_control': fields.boolean('With Module Analytic Control'),
            'with_manufacturing_cost': fields.boolean('With Module Manufacturing Cost'),
            'move_created_ids': fields.one2many('stock.move', 'production_id', 'Products to Produce', domain=[('state','not in', ('done', 'cancel')),('picking_id','=',False)], states={'done':[('readonly',True)]}),
            'move_created_ids2': fields.one2many('stock.move', 'production_id', 'Produced Products', domain=[('state','in', ('done', 'cancel')),('picking_id','=',False)]),
            'products_to_return_ids': fields.one2many('stock.move', 'production_id2', 'Products to return'),
    }
    
    _defaults = {  
         'company_id': lambda self, cr, uid, context: self.pool.get('res.company')._company_default_get(cr, uid, 'mrp.routing', context=context)
     }
    
    def write(self, cr, uid, ids, vals, context=None):
        res = {}
        if ids:
            if ids[0] != False:
                if 'bom_id' in vals:
                    for order in self.browse(cr, uid, ids):            
                        if vals['bom_id']:
                            bom_id = self.pool.get('mrp.bom').browse(cr, uid, vals['bom_id'])
                            vals.update({'routing_id': bom_id.routing_id.id})
                        else:
                            del vals['bom_id']
                        res = super(mrp_production, self).write(cr, uid, ids, vals, context)
                else:
                        res = super(mrp_production, self).write(cr, uid, ids, vals, context)
    
        return res
    
    def action_production_end(self, cr, uid, ids):
        account_line_obj = self.pool.get('account.analytic.line')
        prodlot_obj = self.pool.get('stock.production.lot')
        move_obj = self.pool.get('stock.move')
        picking_obj = self.pool.get('stock.picking')
        product_obj = self.pool.get('product.product')
        
        res = super(mrp_production, self).action_production_end(cr, uid, ids)
        
        if ids:
            for production in self.browse(cr,uid,ids):
                stock_move_ids = move_obj.search(cr, uid,[('production_id', '=', production.id),
                                                          ('product_id','=',production.product_id.id),
                                                          ('type','=', 'internal')])                     
                move_id = 0
                picking_id = 0
                if stock_move_ids:
                    for stock_move in move_obj.browse(cr,uid,stock_move_ids):
                        if stock_move.picking_id:
                            if stock_move.picking_id.internal_type == 'output':
                                picking_id = stock_move.picking_id.id
                                move_id = stock_move.id
                   
                if production.state == 'done' and production.product_id.track_production == True:                                    
                    if move_id > 0:
                        move = move_obj.browse(cr,uid,move_id)
                        # Calculo los costes de la producción
                        total_price = 0
                        account_line_ids = account_line_obj.search(cr, uid,[('ref','=', production.name)])
                        for account_line in account_line_obj.browse(cr,uid,account_line_ids):
                            total_price = total_price + account_line.amount
                        total_price = total_price * (-1)
                        # Genero el lote
                        name = time.strftime("%Y-%m-%d") + ' - ' + production.name
                        if total_price > 0 and production.real_product_qty > 0:
                            unit_cost = total_price / production.real_product_qty
                        else:
                            unit_cost = 0
                        prodlot_id = prodlot_obj.create(cr, uid, {'name': name,
                                                                  'product_id': production.product_id.id,
                                                                  'active': True,
                                                                  'total_cost': total_price,
                                                                  'unit_cost': unit_cost})
                        move_obj.write(cr, uid, [move_id], {'prodlot_id': prodlot_id})  
                        #
                        ### Modifico datos del lote creado
                        if move.product_id.years_which_expires:
                            prodlot = prodlot_obj.browse(cr,uid,prodlot_id)
                            my_date = str(prodlot.date)
                            my_year = int(my_date[0:4]) + stock_move.product_id.years_which_expires
                            my_date = str(my_year) + my_date[4:19]
                            prodlot_obj.write(cr, uid, [prodlot.id], {'expiration_date': datetime.strptime(my_date, '%Y-%m-%d %H:%M:%S')})    
                        #
                        ### Modifico el movimiento de produccion a maquinas para el producto a finalizar                            
                        if production.move_created_ids2:
                            for line in production.move_created_ids2:
                                if line.product_id.id == production.product_id.id and not line.prodlot_id:
                                    move_obj.write(cr, uid, [line.id], {'prodlot_id': prodlot_id})                          
                #
                # Confirmo el albarán de salida
                if picking_id > 0:
                    picking = picking_obj.browse(cr,uid,picking_id)               
                    if picking.state == 'confirmed':
                        picking_obj.force_assign(cr, uid, [picking.id], [])
                   
                #
                ### Calculo el precio medio del producto  
                total_price = 0
                account_line_ids = account_line_obj.search(cr, uid,[('ref','=', production.name)])
                for account_line in account_line_obj.browse(cr,uid,account_line_ids):
                    total_price = total_price + account_line.amount
                total_price = total_price * (-1)                

                product = product_obj.browse(cr,uid,production.product_id.id)
                standard_price = 0
                standard_price = product.qty_available * product.standard_price
                standard_price = standard_price + total_price
                w_imp = product.qty_available + production.real_product_qty
                if standard_price > 0 and w_imp > 0 :
                    standard_price = standard_price / w_imp
                else:
                    standard_price = 0
                if total_price > 0 and production.real_product_qty > 0:
                    last_manufacturing_cost = total_price / production.real_product_qty
                else:
                    last_manufacturing_cost = 0
                manufacturing_end_date = time.strftime("%Y-%m-%d")
                product_obj.write(cr, uid, [product.id], {'standard_price': standard_price,
                                                          'last_manufacturing_cost': last_manufacturing_cost,
                                                          'last_manufacturing_end_date': manufacturing_end_date})
            

        return res

    def create(self, cr, uid, vals, context={}):
        if 'bom_id' in vals:
            if not 'product_def_loc' in vals:
                prod = self.pool.get('product.product').browse(cr, uid, vals['product_id'])
                vals.update({'product_def_loc': prod.default_location.id})
            if vals['bom_id']:
                bom_id = self.pool.get('mrp.bom').browse(cr, uid, vals['bom_id'])
                vals.update({'routing_id': bom_id.routing_id.id})
            else:
                del vals['bom_id']
            res = super(mrp_production, self).create(cr, uid, vals, context)
        else:
            res = super(mrp_production, self).create(cr, uid, vals, context)
        return res

    def onchange_bom(self, cr, uid, ids, bom_id, context=None):
        val = {}
        if bom_id:
            bom = self.pool.get('mrp.bom').browse(cr, uid, bom_id)
            val = {
                'routing_id': bom.routing_id.id
            }
        return {'value': val}

    def product_qty_change_inh(self, cr, uid, ids, product_id, product_qty, context=None):
        product_obj = self.pool.get('product.product')
        val = {}
        if product_qty:
            if product_id:
                product = product_obj.browse(cr,uid,product_id)
                val = {'product_uos_qty': product_qty * product.uos_coeff
                     }
        return {'value': val}

    def product_id_change_inh(self, cr, uid, ids, product_id, context=None):
        value = super(mrp_production, self).product_id_change(cr, uid, ids, product_id, context=None)
        val = value['value']
        if product_id:
            prod = self.pool.get('product.product').browse(cr, uid, product_id)
            if prod.uos_id:
                val['product_def_loc'] = prod.default_location.id
                val['product_uos'] = prod.uos_id.id
            else:
                val['product_def_loc'] = prod.default_location.id
                val['product_uos'] = False
        return {'value': val}

    def do_full_move_consume(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        objs = self.pool.get('mrp.production').browse(cr, uid, ids)
        con_prod = []
        for obj in objs:
            for prod in obj.move_lines:
                con_prod.append(prod.id)
        for prod_id in con_prod:
            move_obj = self.pool.get('stock.move')
            line = self.pool.get('stock.move').browse(cr, uid, prod_id)
            prod_qty = line.product_qty
            prod_loc = line.location_id
            move_obj.action_consume(cr, uid, [prod_id], prod_qty, prod_loc.id, context=context)
        return True

    def do_full_produce(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        objs = self.pool.get('mrp.production').browse(cr, uid, ids)
        con_prod = []
        for obj in objs:
            for prod in obj.move_created_ids:
                con_prod.append(prod.id)
        for prod_id in con_prod:
            move_obj = self.pool.get('stock.move')
            line = self.pool.get('stock.move').browse(cr, uid, prod_id)
            prod_qty = line.product_qty
            prod_loc = line.location_id
            move_obj.action_consume(cr, uid, [prod_id], prod_qty, prod_loc.id, context=context)
        return True

    def action_button_confirm(self, cr, uid, ids, *args):
        picking_obj = self.pool.get('stock.picking')
        mrp_production_operation_obj = self.pool.get('mrp.production.operation')
        mrp_production_operation_real_obj = self.pool.get('mrp.production.operation.real')
        move_obj = self.pool.get('stock.move')
        wf_service = netsvc.LocalService("workflow")
        for id in ids:
            wf_service.trg_validate(uid, 'mrp.production', id, 'button_confirm', cr)
            
            picking_ids = picking_obj.search(cr, uid, [('production_id', '=', id)])
            if picking_ids:
                for picking in picking_obj.browse(cr,uid,picking_ids):
                    for move in picking.move_lines:
                        if not move.production_id:
                            move_obj.write(cr, uid, [move.id], {'production_id': picking.production_id.id})
                            
            production = self.browse(cr,uid,id)
            
            if production.real_operation_ids:
                for operation in production.real_operation_ids:
                    mrp_production_operation_ids = mrp_production_operation_obj.search(cr, uid, [('production_id', '=', operation.production_id.id),
                                                                                                 ('sequence','=',operation.sequence)])
                    mrp_production_operation = mrp_production_operation_obj.browse(cr,uid,mrp_production_operation_ids[0])
                    mrp_production_operation_real_obj.write(cr, uid, [operation.id], {'qty': mrp_production_operation.semi_prod_qty})  
            
        return True

    def action_compute(self, cr, uid, ids, properties=[]):
        """ Computes bills of material of a product.
        @param properties: List containing dictionaries of properties.
        @return: No. of products.
        """
        results = []
        operation_obj = self.pool.get('mrp.bom.operations.product')
        bom_obj = self.pool.get('mrp.bom')
        prod_line_obj = self.pool.get('mrp.production.product.line')
        operation_line_obj = self.pool.get('mrp.production.operation')
        user_obj = self.pool.get('mrp.production.users')
        final_product_obj = self.pool.get('mrp.production.final.product')
        product_obj = self.pool.get('product.product')
        for production in self.browse(cr, uid, ids):
            mat_cost_price = 0
            mat_standard_price = 0
            mat_estimated_puc = 0
            prod_line_obj.unlink(cr, uid, prod_line_obj.search(cr, uid, [('production_id', '=', production.id)]))
            operation_line_obj.unlink(cr, uid, operation_line_obj.search(cr, uid, [('production_id', '=', production.id)]))
            final_product_obj.unlink(cr, uid, final_product_obj.search(cr, uid, [('production_id', '=', production.id)]))

            bom_point = production.bom_id
            bom_id = production.bom_id.id
            if not bom_point:
                bom_id = bom_obj._bom_find(cr, uid, production.product_id.id, production.product_uom.id, properties)
                if bom_id:
                    bom_point = bom_obj.browse(cr, uid, bom_id)
                    routing_id = bom_point.routing_id.id or False
                    self.write(cr, uid, [production.id], {'bom_id': bom_id, 'routing_id': routing_id})

            if not bom_id:
                raise osv.except_osv(_('Error'), _("Couldn't find bill of material for product"))

            factor = production.product_qty * production.product_uom.factor / bom_point.product_uom.factor
            res = bom_obj._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, properties)
            fix_obj = self.pool.get('mrp.fixed.cost')
            for del_it in production.fixed_costs:
                context = {'borrar': True}
                fix_obj.unlink(cr, uid, del_it.id, context=context)
            for aux in bom_point.fixed_costs:
                values = {
                          'name': aux.name,
                          'amount': aux.amount,
                          'production_id': production.id,
                          'estimated': aux.amount
                          }
                fix_obj.create(cr, uid, values)
            for user in user_obj.search(cr, uid, [('prod', '=', production.id)]):
                user_obj.unlink(cr, uid, user)
            for line in res:
                line['production_id'] = production.id
                line_products = line['products']
                del line['products']
                line_finals = line['finals']
                del line['finals']
                calc_qty = (production.product_qty * line['semi_prod_qty']) / bom_point.product_qty   
                line['semi_prod_qty'] = calc_qty
                operation_id = operation_line_obj.create(cr, uid, line)
                       
                for component in line_products:
                    component['mrp_production_operation_id'] = operation_id
                    component['production_id'] = production.id

                    if component['consuming_amount'] == True:
                        calc_qty = (production.product_qty * component['product_qty']) / bom_point.product_qty   
                    else:
                        if component['by_unit'] == True:
                            calc_qty = production.product_qty * component['product_qty']             
                        else:
                            calc_qty = (production.product_qty * component['product_qty']) / bom_point.product_qty   
                    component['product_qty'] = calc_qty
                    product = product_obj.browse(cr,uid, component['product_id'])
                    cost_price = product.standard_price * calc_qty
                    standard_price = product.standard_cost * calc_qty
                    estimated_puc = product.last_purchase_price * calc_qty
                    component['cost_price'] = cost_price
                    component['standard_price'] = standard_price
                    component['estimated_puc'] = estimated_puc
                    mat_cost_price = mat_cost_price + cost_price
                    mat_standard_price = mat_standard_price + standard_price
                    mat_estimated_puc = mat_estimated_puc + estimated_puc
                    prod_line_obj.create(cr, uid, component)              
                
                for final_prod in line_finals:
                    final_prod['mrp_production_operation_id'] = operation_id
                    final_prod['production_id'] = production.id
                    calc_qty = (production.product_qty * final_prod['product_qty']) / bom_point.product_qty  
                    final_prod['product_qty'] = calc_qty
                    final_product_obj.create(cr, uid, final_prod)
                self.create_operator(cr, uid, operation_line_obj.browse(cr, uid, operation_id))
                
            self.write(cr,uid,[production.id], {'mat_cost_price': mat_cost_price,
                                                'mat_standard_price': mat_standard_price,
                                                'mat_estimated_puc': mat_estimated_puc})
            
        if ids:
            for production in self.browse(cr, uid, ids):
                if production.production_operation_ids:
                    for operation in production.production_operation_ids:
                        if operation.merma_percentage > 0:
                            merma = (operation.semi_prod_qty * operation.merma_percentage) / 100
                            quantity = operation.semi_prod_qty + merma
                            operation_line_obj.write(cr, uid, [operation.id], {'semi_prod_qty': quantity})

                if production.product_lines:
                    for product in production.product_lines:
                        if product.mrp_production_operation_id:
                            if product.mrp_production_operation_id.merma_percentage > 0:
                                merma = (product.product_qty * product.mrp_production_operation_id.merma_percentage) / 100
                                quantity = product.product_qty + merma
                                prod_line_obj.write(cr, uid, [product.id], {'product_qty': quantity}) 
        
        return len(results)

    def action_confirm(self, cr, uid, ids):
        """ Confirms production order.
        @return: Newly generated picking Id.
        """
        res_final_ids = []
        picking_id = False
        proc_ids = []
        move_obj = self.pool.get('stock.move')
        proc_obj = self.pool.get('procurement.order')
        wf_service = netsvc.LocalService("workflow")
        for production in self.browse(cr, uid, ids):
            if not production.product_lines:
                self.action_compute(cr, uid, [production.id])
                production = self.browse(cr, uid, [production.id])[0]
            pick_type = 'internal'
            moves = []

            for i in range(len(production.production_operation_ids)):
                move_id = False
                next_operation = False
                semi_product_id = False
                newdate = production.date_planned
                operation = production.production_operation_ids[i]
                if i < len(production.production_operation_ids) - 1:
                    next_operation = production.production_operation_ids[i + 1]

                for line in operation.final_products_ids:
                    if not line.product_id.default_location:
                        raise osv.except_osv(_('Product Default Location'), _('All final products must have a default location !'))
                for line in operation.components_used_ids:
                    if not line.product_id.default_location:
                        raise osv.except_osv(_('Product Default Location'), _('All components must have a default location !'))
                if not production.product_id.default_location:
                    raise osv.except_osv(_('Product Default Location'), _('All final products must have a default location !'))
                if (next_operation) and (next_operation.location_id.usage == 'supplier') and (not next_operation.location_id.address_id):
                        raise osv.except_osv(_('External Operation'), _('External operation location must be set !'))
                if (i == 0) and (operation.location_id.usage == 'supplier'):
                    picking_id = self.create_picking(cr, uid, 'out', 'one', production, operation)
                    self.pool.get('stock.picking').write(cr, uid, [picking_id], {'production_id': production.id})
                    self.create_purchase(cr, uid, operation)
                    for line in operation.components_used_ids:

                        move_id = move_obj.create(cr, uid, {
                            'name': 'PROD:' + production.name + '/' + operation.name,
                            'product_id': line.product_id.id,
                            'product_qty': line.product_qty,
                            'product_uom': line.product_uom.id,
                            'bom_prop': line.product_qty / production.product_qty,
                            'product_uos_qty': False,
                            'product_uos': False,
                            'date': newdate,
                            'location_id': operation.location_id.id or False,
                            'location_dest_id': line.product_id.product_tmpl_id.property_stock_production.id,
                            'state': 'waiting',
                            'company_id': production.company_id.id,
                            'operation_id': operation.id or False,
                            'production_id': production.id
                        })
                        moves.append(move_id)
                        move_new_id = move_obj.create(cr, uid, {
                            'name': 'PROD:' + production.name + '/' + operation.name,
                            'date': production.date_planned,
                            'product_id': line.product_id.id,
                            'picking_id': picking_id,
                            'product_qty': line.product_qty,
                            'bom_prop': line.product_qty / production.product_qty,
                            'product_uom': line.product_uom.id,
                            'product_uos_qty': False,
                            'product_uos': False,
                            'location_id': line.product_id.default_location.id,
                            'location_dest_id': operation.location_id.id,
                            'state': 'confirmed',
                            'company_id': production.company_id.id,
                            'move_dest_id': move_id,
                            'production_id': production.id
                        })
                        proc_id = proc_obj.create(cr, uid, {
                            'name': (production.origin or '').split(':')[0] + ':' + production.name + '/' + operation.name,
                            'origin': (production.origin or '').split(':')[0] + ':' + production.name + '/' + operation.name,
                            'date_planned': newdate,
                            'product_id': line.product_id.id,
                            'product_qty': line.product_qty,
                            'product_uom': line.product_uom.id,
                            'product_uos_qty': line.product_uos and production.product_qty or False,
                            'product_uos': line.product_uos and production.product_uos.id or False,
                            'location_id': line.product_id.default_location.id,
                            'procure_method': line.product_id.procure_method,
                            'move_id': move_new_id,
                            'company_id': production.company_id.id,
                        })
                        wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
                        proc_ids.append(proc_id)
                        
                    data = move_obj.create(cr, uid, {
                            'name': 'PROD:' + production.name + '/' + operation.name,
                            'date': production.date_planned,
                            'product_id': production.product_id.id,
                            'product_qty': production.product_qty,
                            'bom_prop': line.product_qty / production.product_qty,
                            'product_uom': production.product_id.uom_id.id,
                            'product_uos_qty': False,
                            'product_uos': False,
                            'date': newdate,
                            'location_id': production.product_id.property_stock_production.id,
                            'location_dest_id': operation.location_id.id,
                            'state': 'waiting',
                            'company_id': production.company_id.id,
                            'operation_id': operation.id,
                            'production_id': production.id
                    })
                    res_final_ids.append(data)
                    wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
                if (next_operation) and (next_operation.location_id.usage == 'supplier'):
                    picking_id = self.create_picking(cr, uid, 'out', 'one', production, next_operation)
                    self.pool.get('stock.picking').write(cr, uid, [picking_id], {'production_id': production.id})
                    self.create_purchase(cr, uid, next_operation)
                    for line in next_operation.components_used_ids:
                        move_new_id = move_obj.create(cr, uid, {
                            'name': 'PROD:' + production.name + '/' + operation.name,
                            'date': production.date_planned,
                            'product_id': line.product_id.id,
                            'picking_id': picking_id,
                            'product_qty': line.product_qty,
                            'bom_prop': line.product_qty / production.product_qty,
                            'product_uom': line.product_uom.id,
                            'product_uos_qty': False,
                            'product_uos': False,
                            'location_id': line.product_id.default_location.id,
                            'location_dest_id': next_operation.location_id.id,
                            'state': 'confirmed',
                            'company_id': production.company_id.id,
                            'production_id': production.id
                        })
                        proc_id = proc_obj.create(cr, uid, {
                            'name': (production.origin or '').split(':')[0] + ':' + production.name + '/' + next_operation.name,
                            'origin': (production.origin or '').split(':')[0] + ':' + production.name + '/' + next_operation.name,
                            'date_planned': newdate,
                            'product_id': line.product_id.id,
                            'product_qty': line.product_qty,
                            'product_uom': line.product_uom.id,
                            'product_uos_qty': line.product_uos and production.product_qty or False,
                            'product_uos': line.product_uos and production.product_uos.id or False,
                            'location_id': line.product_id.default_location.id,
                            'procure_method': line.product_id.procure_method,
                            'move_id': move_new_id,
                            'company_id': production.company_id.id,
                        })
                        wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
                        proc_ids.append(proc_id)
                    move_new_id = move_obj.create(cr, uid, {
                        'name': 'PROD:' + production.name + '/' + next_operation.name,
                        'date': production.date_planned,
                        'picking_id': picking_id,
                        'product_id': operation.product_id.id,
                        'product_qty': operation.semi_prod_qty,
                        'product_uom': operation.semi_prod_uom.id,
                        'product_uos_qty': False,
                        'product_uos': False,
                        'date': newdate,
                        'location_id': operation.location_id.id,
                        'location_dest_id': next_operation.location_id.id,
                        'state': 'waiting',
                        'company_id': production.company_id.id,
                        'production_id': production.id
                    })
                    data = move_obj.create(cr, uid, {
                            'name': 'PROD:' + production.name + '/' + operation.name,
                            'date': production.date_planned,
                            'product_id': operation.product_id.id,
                            'product_qty': operation.semi_prod_qty,
                            'bom_prop': line.product_qty / production.product_qty,
                            'product_uom': operation.semi_prod_uom.id,
                            'product_uos_qty': False,
                            'product_uos': False,
                            'date': newdate,
                            'location_id': operation.product_id.product_tmpl_id.property_stock_production.id,
                            'location_dest_id': operation.location_id.id,
                            'move_dest_id': move_new_id,
                            'state': 'waiting',
                            'company_id': production.company_id.id,
                            'operation_id': operation.id,
                            'production_id': production.id
                    })
                    res_final_ids.append(data)
                    wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
                elif (next_operation) and (next_operation.location_id.usage == 'internal'):
                    if not operation.product_id:
                        raise osv.except_osv(_('Semi-elaborated Product'), _('A semi-elaborated product is missing in the %s operation !') %(operation.name))
                    semi_product_id = move_obj.create(cr, uid, {
                        'name': 'PROD:' + production.name + '/'+ operation.name,
                        'product_id': operation.product_id.id,
                        'product_qty': operation.semi_prod_qty,
                        'bom_prop': operation.semi_prod_qty / production.product_qty,
                        'product_uom': operation.semi_prod_uom.id,
                        'product_uos_qty': False,
                        'product_uos': False,
                        'date': newdate,
                        'location_id': next_operation.location_id.id or False,
                        'location_dest_id': operation.product_id.product_tmpl_id.property_stock_production.id,
                        'state': 'waiting',
                        'company_id': production.company_id.id,
                        'operation_id': next_operation.id or False,
                        'production_id': production.id
                    })
                    moves.append(semi_product_id)
                    if not operation.location_id.usage == 'supplier':
                        data = move_obj.create(cr, uid, {
                            'name': 'PROD:' + production.name + '/' + operation.name,
                            'date': production.date_planned,
                            'product_id': operation.product_id.id,
                            'product_qty': operation.semi_prod_qty,
                            'bom_prop': operation.semi_prod_qty / production.product_qty,
                            'product_uom': operation.semi_prod_uom.id,
                            'product_uos_qty': False,
                            'product_uos': False,
                            'date': newdate,
                            'location_id': operation.product_id.product_tmpl_id.property_stock_production.id,
                            'location_dest_id': next_operation.location_id.id,
                            'move_dest_id': semi_product_id,
                            'state': 'waiting',
                            'company_id': production.company_id.id,
                            'operation_id': operation.id,
                            'production_id': production.id
                        })
                        res_final_ids.append(data)
                if operation.location_id.usage == 'supplier':
                    picking_id = self.create_picking(cr, uid, 'in', 'direct', production, operation)
                    self.pool.get('stock.picking').write(cr, uid, [picking_id], {'production_id': production.id})
                    product = operation.product_id or production.product_id
                    if operation.semi_prod_qty > 0:
                        product_qty = operation.semi_prod_qty
                    else:
                        product_qty = production.product_qty
                    location_dest_id = (next_operation and next_operation.location_id and next_operation.location_id.id ) or (production.product_id and production.product_id.default_location and production.product_id.default_location.id)
                    company_id = production.company_id.id 
                    move_new_id = move_obj.create(cr, uid, {
                        'name': 'PROD:' + production.name + '/' + operation.name,
                        'date': production.date_planned,
                        'picking_id': picking_id,
                        'product_id': product.id,
                        'product_qty': product_qty,
                        'product_uom': product.uom_id.id,
                        'product_uos_qty': False,
                        'product_uos': False,
                        'date': newdate,
                        'location_id': operation.location_id.id,
                        'location_dest_id': location_dest_id,
                        'move_dest_id': semi_product_id,
                        'state': 'draft',
                        'company_id': company_id,
                        'production_id': production.id
                    })
                    wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
                else:
                    if operation.components_used_ids:
                        picking_id = self.create_picking(cr, uid, pick_type, 'direct', production, operation, 'input')
                        self.pool.get('stock.picking').write(cr, uid, [picking_id], {'production_id': production.id,
                                                                                     'move_type': 'one'})
                    for line in operation.components_used_ids:
                        move_new_id = False
                        if line.product_id.type in ('product', 'consu'):
                            if line.product_qty > 0 and operation.semi_prod_qty > 0:
                                qty = line.product_qty / operation.semi_prod_qty
                            else:
                                qty = 0
                            move_id = move_obj.create(cr, uid, {
                                'name':'PROD:' + production.name + '/'+ operation.name,
                                'date': production.date_planned,
                                'product_id': line.product_id.id,
                                'product_qty': line.product_qty,
                                'bom_prop': qty,
                                'product_uom': line.product_uom.id,
                                'product_uos_qty': line.product_uos and line.product_uos_qty or False,
                                'product_uos': line.product_uos and line.product_uos.id or False,
                                'location_id': operation.location_id.id,
                                'location_dest_id': line.product_id.product_tmpl_id.property_stock_production.id,
                                'state': 'confirmed',
                                'company_id': production.company_id.id,
                                'operation_id': operation.id,
                                'production_id': production.id
                            })
                            moves.append(move_id)
                            move_new_id = move_obj.create(cr, uid, {
                                'name':'PROD:' + production.name + '/' + operation.name,
                                'date': production.date_planned,
                                'product_id': line.product_id.id,
                                'picking_id': picking_id,
                                'product_qty': line.product_qty,
                                'bom_prop': qty,
                                'product_uom': line.product_uom.id,
                                'product_uos_qty': line.product_uos and line.product_uos_qty or False,
                                'product_uos': line.product_uos and line.product_uos.id or False,
                                'location_id': line.product_id.default_location.id,
                                'location_dest_id': operation.location_id.id,
                                'move_dest_id': move_id,
                                'state': 'confirmed',
                                'company_id': production.company_id.id,
                                'production_id': production.id
                            })
                        wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
                        ##TODO: Create procurements for each consumed product
                        proc_id = proc_obj.create(cr, uid, {
                            'name': (production.origin or '').split(':')[0] + ':' + production.name + '/' + operation.name,
                            'origin': (production.origin or '').split(':')[0] + ':' + production.name + '/' + operation.name,
                            'date_planned': newdate,
                            'product_id': line.product_id.id,
                            'product_qty': line.product_qty,
                            'product_uom': line.product_uom.id,
                            'product_uos_qty': line.product_uos and production.product_qty or False,
                            'product_uos': line.product_uos and production.product_uos.id or False,
                            'location_id': line.product_id.default_location.id,
                            'procure_method': line.product_id.procure_method,
                            'move_id': move_new_id,
                            'company_id': production.company_id.id,
                        })
                        wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
                        proc_ids.append(proc_id)

                    if operation.final_products_ids:
                        picking_id = self.create_picking(cr, uid, pick_type, 'direct', production, operation, 'output')
                        self.pool.get('stock.picking').write(cr, uid, [picking_id], {'production_id': production.id})
                    for line in operation.final_products_ids:
                        move_new_id = move_obj.create(cr, uid, {
                                'name': 'PROD:' + production.name + '/' + operation.name,
                                'date': production.date_planned,
                                'product_id': line.product_id.id,
                                'picking_id': picking_id,
                                'product_qty': line.product_qty,
                                'bom_prop': line.product_qty / production.product_qty,
                                'product_uom': line.product_uom.id,
                                'product_uos_qty': False,
                                'product_uos': False,
                                'location_id': operation.location_id.id,
                                'location_dest_id': line.product_id.default_location.id,
                                'state': 'confirmed',
                                'company_id': production.company_id.id,
                                'production_id': production.id
                            })
                        data = move_obj.create(cr, uid, {
                            'name': 'PROD:' + production.name + '/' + operation.name,
                            'date': production.date_planned,
                            'product_id': line.product_id.id,
                            'product_qty': line.product_qty,
                            'bom_prop': line.product_qty / production.product_qty,
                            'product_uom': line.product_uom.id,
                            'product_uos_qty': False,
                            'product_uos': False,
                            'location_id': line.product_id.product_tmpl_id.property_stock_production.id,
                            'location_dest_id': operation.location_id.id,
                            'state': 'waiting',
                            'company_id': production.company_id.id,
                            'operation_id': operation.id,
                            'production_id': production.id
                        })
                        res_final_ids.append(data)
                        wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
                     # 
                     ### AQUI SE CREABA EL ALBARAN INTERNO DE SALIDA
                     #
                    if not next_operation:
#                        if not operation.final_products_ids:
#                            picking_id = self.create_picking(cr, uid, pick_type, 'direct', production, operation, 'output')
#                            print '*** create picking6: ' + str(picking_id)
#                            self.pool.get('stock.picking').write(cr, uid, [picking_id], {'production_id': production.id})
#                        move_new_id = move_obj.create(cr, uid, {
#                                'name': 'PROD:' + production.name + '/' + operation.name,
#                                'date': production.date_planned,
#                                'picking_id': picking_id,
#                                'product_id': production.product_id.id,
#                                'product_qty': production.product_qty,
#                                'product_uom': production.product_uom.id,
#                                'product_uos_qty': production.product_uos and production.product_uos_qty or False,
#                                'product_uos': production.product_uos and production.product_uos.id or False,
#                                'location_id': operation.location_id.id,
#                                'location_dest_id': production.product_id.default_location.id,
#                                'state': 'confirmed',
#                                'company_id': production.company_id.id,
#                                'production_id': production.id
#                            })
#                        wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
                        product_bom = move_obj.create(cr, uid, {
                            'name': 'PROD:' + production.name + '/'+ operation.name,
                            'date': production.date_planned,
                            'product_id': production.product_id.id,
                            'product_qty': production.product_qty,
                            'product_uom': production.product_uom.id,
                            'product_uos_qty': production.product_uos and production.product_uos_qty or False,
                            'product_uos': production.product_uos and production.product_uos.id or False,
                            'location_id': production.product_id.product_tmpl_id.property_stock_production.id,
                            'location_dest_id': operation.location_id.id,
                            'state': 'waiting',
                            'company_id': production.company_id.id,
                            'operation_id': operation.id,
                            'production_id': production.id
                        }) 
                        res_final_ids.append(product_bom)
                self.write(cr, uid, [production.id], {'move_created_ids': [(6, 0, res_final_ids)]})

            self.write(cr, uid, [production.id], {'picking_id': picking_id, 'move_lines': [(6, 0, moves)], 'state':'confirmed'})
            message = _("Manufacturing order '%s' is scheduled for the %s.") % (
                production.name,
                datetime.strptime(production.date_planned,'%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y'),
            )
            self.log(cr, uid, production.id, message)

        return {'move_lines': moves, 'move_created_ids': res_final_ids}

    def create_picking(self, cr, uid, pick_type, move_type, production, operation, internal_type=False):
        pick_obj = self.pool.get('stock.picking')
        seq_obj = self.pool.get('ir.sequence')
        pick_name = seq_obj.get(cr, uid, 'stock.picking.' + pick_type)
        picking_id = pick_obj.create(cr, uid, {
            'name': pick_name,
            'origin': (production.origin or '').split(':')[0] + ':' + production.name + '/' + operation.name,
            'type': pick_type,
            'move_type': move_type,
            'address_id': operation.location_id.address_id.id,
            'internal_type': internal_type,
            'state': 'confirmed',
            'company_id': production.company_id.id,
        })
        return picking_id

    def create_purchase(self, cr, uid, next_operation):
        po_obj = self.pool.get('purchase.order')
        po_lines_obj = self.pool.get('purchase.order.line')
        notes = ''
        if (next_operation):
            if (not next_operation.location_id.address_id):
                        raise osv.except_osv(_('External Operation'), _('External operation location must be set on operation!'))
            elif (not next_operation.location_id.address_id.partner_id):
                        raise osv.except_osv(_('External Operation'), _('Partner must be set on external location on operation !'))

        notes += _('Products delivered:') + '\n\n'
        for prod in next_operation.components_used_ids:
            notes += (prod.name or '') + ' ' + str(prod.product_qty) + ' ' + prod.product_uom.name + '\n'
        notes += ((next_operation.product_id and next_operation.product_id.name) or '') + ' ' + str(next_operation.semi_prod_qty or 0) + ' ' + ((next_operation.semi_prod_uom and next_operation.semi_prod_uom.name) or '')

        po_id = po_obj.create(cr, uid, {
            'origin': next_operation.production_id.name + '/' + next_operation.name,
            'partner_id': next_operation.location_id.address_id.partner_id.id,
            'partner_address_id': next_operation.location_id.address_id.partner_id.address[0].id,
            'location_id': next_operation.location_id.id,
            'pricelist_id': next_operation.location_id.address_id.partner_id.property_product_pricelist_purchase.id,
            'notes': notes,
            'state': 'draft',
        })

        if not next_operation.workcenter_id.product_id:
            raise osv.except_osv(_('User error'), _('There is no product assigned for the external Work Center!'))

        seller_delay = 0
        if next_operation.workcenter_id.product_id.seller_ids:
            for s in next_operation.workcenter_id.product_id.seller_ids:
                if s.name.id == next_operation.location_id.address_id.partner_id:
                    seller_delay = s.delay

        po_lines_obj.create(cr, uid, {
            'name': next_operation.workcenter_id.product_id.name,
            'product_id': next_operation.workcenter_id.product_id.id,
            'product_uom': next_operation.workcenter_id.product_id.uom_id.id,
            'product_qty': next_operation.semi_prod_qty,
            'price_unit': next_operation.workcenter_id.product_id.standard_price,
            'date_planned': (datetime.now() + relativedelta(days=int(seller_delay) or 0.0)).strftime('%Y-%m-%d %H:%M:%S'),
            'order_id': po_id,
        })
        return True

    def create_operator(self, cr, uid, operation):
        user_obj = self.pool.get('mrp.production.users')
        for user in operation.workcenter_id.user_ids:
            user_obj.create(cr, uid, {
                'name': user.id,
                'op': operation.id,
                'prod': operation.production_id.id,
                'percent': 100,
            })
        return True
    
    def production_get_picking_type(self, cr, uid, picking, context=None):
        picking_type = picking.type
        for move in picking.move_lines:
            if picking.type == 'in' and move.product_id.cost_method == 'average':
                picking_type = 'in'
                break
            else:
                picking_type = 'out'
        return picking_type
    
    def onchange_product_lines(self, cr, uid, ids, product_lines, product_qty, context=None):
        res={}
        w_cost_price = 0
        w_standard_price = 0
        w_estimated_puc = 0
        for product_line in product_lines:
            line = product_line[2]
            if line:
                if line.get('cost_price'):
                    w_cost_price = w_cost_price + line.get('cost_price')
                if line.get('standard_price'):
                    w_standard_price = w_standard_price + line.get('standard_price')
                if line.get('estimated_puc'):
                    w_estimated_puc = w_estimated_puc + line.get('estimated_puc')
                    
        res = {'mat_cost_price': w_cost_price,
               'mat_standard_price': w_standard_price,
               'mat_estimated_puc': w_estimated_puc,
               }

        return {'value': res}  
    
    def test_production_done(self, cr, uid, ids):
        """ Tests whether production is done or not.
        @return: True or False
        """
        res = True
#        for production in self.browse(cr, uid, ids):
#            if production.move_lines:
#                res = False
#            if production.move_created_ids:
#                for line in production.move_created_ids:
#                    if line.product_id.id != production.product_id.id:
#                        res = False
        return res

    
mrp_production()