~eoc/openobject-addons/eoc-extra-addons-trunk

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
# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, CRM Picking Extension
#    Copyright (C) 2014  Enterprise Objects Consulting
#
#    Authors: Mariano Ruiz <mrsarm@gmail.com>
#
#    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 openerp.osv import fields, osv
from openerp.tools.translate import _

import netsvc

import time

class crm_claim(osv.osv):
    _inherit = 'crm.claim'

    _columns = {
            'picking_ids': fields.one2many('stock.picking', 'claim_id', 'Pickings'),
        }

    def write(self, cr, uid, ids, vals, context=None):
        if 'product.product' in (vals.get('ref', '') or ''):
            # Avoid edit product value in no draft state (this validations
            # cannot be done with 'readonly' attribute in reference fields
            for reg in self.browse(cr,uid,ids,context=context):
                if reg.state != 'draft' and reg.ref.id and str(reg.ref.id) not in vals['ref']:
                    raise osv.except_osv(_('Error !'),
                            _('Only in claims with "Draft" state the Product Reference field can be edited !'))
                #if vals['ref'] and not equals_ref_models(reg.ref, vals['ref']):
                #    raise osv.except_osv(_('Error !'), _('Serial Number ...!'))
        result = super(crm_claim, self).write(cr, uid, ids, vals, context=context)
        return result

    def case_open(self, cr, uid, ids, *args):
        for l in self.browse(cr, uid, ids):
            if l.ref and l.ref._model._name == 'product.product' \
              and self._auto_create_picking_in(cr, uid) and not len(l.picking_ids):
                # Create Claim Picking
                self.create_auto_picking_in(cr, uid, ids)
        res = super(crm_claim, self).case_open(cr, uid, ids, *args)
        return res

    def case_close(self, cr, uid, ids, *args):
        for l in self.browse(cr, uid, ids):
            if l.ref and l.ref._model._name == 'product.product' \
              and self._auto_create_picking_out(cr, uid) \
              and self._get_auto_picking_in(cr, uid, l):
                # Create Claim Picking
                self.create_auto_picking_out(cr, uid, ids)
        res = super(crm_claim, self).case_close(cr, uid, ids, *args)
        return res

    def case_cancel(self, cr, uid, ids, *args):
        for l in self.browse(cr, uid, ids):
            if l.ref and l.ref._model._name == 'product.product' \
              and self._auto_create_picking_out(cr, uid) \
              and self._get_auto_picking_in(cr, uid, l):
                # Create Claim Picking
                self.create_auto_picking_out(cr, uid, ids, {'claim_cancel': True})
        res = super(crm_claim, self).case_cancel(cr, uid, ids, *args)
        return res

    def _get_repair_location(self, cr, uid, claim, context={}):
        """
        Get a Repair Location to use in Picking IN created automatically.
        """
        repair_loc_id = self.pool.get('stock.location') \
                .get_default_repair_location(cr, uid, context=context)
        if not repair_loc_id:
            raise osv.except_osv(_('Error !'),
                            _('You must be define a default Repair Location !'))
        return repair_loc_id

    def _get_scrap_location(self, cr, uid, claim, context={}):
        """
        Return a default Scrap Location for any operation.
        """
        loc_scrap_id = self._get_scrap_location_from_ir_prop(cr, uid, context)
        if not loc_scrap_id:
            loc_ids = self.pool.get("stock.location").search(cr,uid,[('scrap_location','=',True)],context=context)
            if len(loc_ids):
                loc_scrap_id = loc_ids[0]
        if not loc_scrap_id:
            raise osv.except_osv(_('Error !'),
                            _('You must be define a default Scrap Location !'))
        return loc_scrap_id

    def _get_scrap_location_from_ir_prop(self, cr, uid, context={}):
        """
        Return a Scrap Location from ir.property values, or None.
        """
        property_obj = self.pool.get('ir.property')
        prop_ids = property_obj.search(cr, uid, [('name','=','stock_scrap')],context=context)
        if len(prop_ids)>0:
            return int(property_obj.read(cr,uid,prop_ids[0],['value_text'],context=context)['value_text'])
        return None

    def _get_stock_location(self, cr, uid, claim, context={}):
        """
        Return a default Stock Location for any operation.
        """
        loc_stock_id = self._get_stock_location_from_ir_prop(cr, uid, context)
        if not loc_stock_id:
            loc_ids = self.pool.get("stock.location").search(cr,uid,[
                            ('scrap_location','=',False),('repair_location','=',False),('usage','=','internal')],context=context)
            if len(loc_ids):
                loc_stock_id = loc_ids[0]
        if not loc_stock_id:
            raise osv.except_osv(_('Error !'),
                            _('You must be define a default Stock Location !'))
        return loc_stock_id

    def _get_stock_location_from_ir_prop(self, cr, uid, context={}):
        """
        Return a Stock Location from ir.property values, or None.
        """
        property_obj = self.pool.get('ir.property')
        prop_ids = property_obj.search(cr, uid, [('name','=','stock_stock')],context=context)
        if len(prop_ids)>0:
            return int(property_obj.read(cr,uid,prop_ids[0],['value_text'],context=context)['value_text'])
        return None

    def _get_auto_picking_in(self, cr, uid, claim, context={}):
        """
        Return the id of the Picking IN created automatically
        when the order was opened.
        """
        for picking in claim.picking_ids:
            if picking.origin == claim.number and picking.state == 'done':
                return picking.id
        return False

    def _prepare_order_picking_in(self, cr, uid, claim, context={}):
        """
        Return a dict with the Picking IN data to be created
        (not included moves).
        """
        seq_obj = self.pool.get('ir.sequence')
        partner = claim.partner_id
        if not claim.partner_address_id.id:
            if len(partner.address):
                address = partner.address[0]
            else:
                raise osv.except_osv(_('Error !'),
                            _('Contact field must be set if Product Reference field is set'))
        else:
            address = claim.partner_address_id
        repair_loc_id = self._get_repair_location(cr, uid, claim, context)
        now = time.strftime('%Y-%m-%d %H:%M:%S')
        picking_data = {}
        picking_data['name'] = seq_obj.get(cr, uid, 'stock.picking.in')
        picking_data['type'] = 'in'
        picking_data['claim_id'] = claim.id
        picking_data['origin'] = claim.number
        picking_data['partner_id'] = partner.id
        picking_data['address_id'] = address.id
        picking_data['location_id'] = partner.property_stock_customer.id
        picking_data['location_dest_id'] = repair_loc_id
        picking_data['date'] = now
        picking_data['min_date'] = now
        picking_data['invoice_state'] = 'none'
        picking_data['company_id'] = claim.company_id.id
        return picking_data

    def _prepare_order_moves_in(self, cr, uid, claim, picking_id, context={}):
        """
        Return a list with the moves data to be created into the Picking IN
        """
        repair_loc_id = self._get_repair_location(cr, uid, claim, context)
        now = time.strftime('%Y-%m-%d %H:%M:%S')
        move_data = {}
        move_data['picking_id'] = picking_id
        move_data['date'] = now
        move_data['date_expected'] = now
        move_data['product_qty'] = 1.0
        move_data['product_id'] = claim.ref.id
        move_data['product_uom'] = claim.ref.product_tmpl_id.uom_id.id
        move_data['name'] = self._get_move_name(cr, uid, claim, context)
        move_data['location_id'] = claim.partner_id.property_stock_customer.id
        move_data['location_dest_id'] = repair_loc_id
        move_data['company_id'] = claim.company_id.id
        return [move_data]

    def create_auto_picking_in(self, cr, uid, ids, context={}):
        """
        Create a picking automatically with a stock move from
        the partner location to repair location.

        Return a dict with the picking ids created by claim
        """
        wf_service = netsvc.LocalService("workflow")
        move_obj = self.pool.get('stock.move')
        picking_obj = self.pool.get('stock.picking')
        ctx = context.copy()
        picks = {}
        for claim in self.browse(cr, uid, ids, context):
            picks[claim.id] = []
            # Create picking
            
            if not claim.partner_id.id:
                if claim.categ_id.id and claim.categ_id.section_id.id:
                    raise osv.except_osv(_('Error !'),
                                _('Partner field must be set if Product Reference field is set'))
            else:
                picking_data = self._prepare_order_picking_in(cr, uid, claim, context)
                picking_id = picking_obj.create(cr, uid, picking_data, context=ctx)
                # Create stock move
                moves_data = self._prepare_order_moves_in(cr, uid, claim, picking_id, context)
                for move in moves_data:
                    move_obj.create(cr, uid, move, context=ctx)
                # Confirm and validate the picking
                wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
                picking_obj.action_move(cr, uid, [picking_id])
                wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_done', cr)
                #wf_service.trg_write(uid, 'stock.picking', picking_id, cr)

                picks[claim.id].append(picking_id)
        return picks

    def _prepare_order_picking_out(self, cr, uid, claim, picking_in, context={}):
        """
        Return a dict with the Picking OUT data to be created
        (not included moves).
        """
        seq_obj = self.pool.get('ir.sequence')
        now = time.strftime('%Y-%m-%d %H:%M:%S')
        picking_data = {}
        new_pick_name = seq_obj.get(cr, uid, 'stock.picking.out')
        if context.get('claim_cancel', False):
            new_pick_name += "-cancel-claim-return"
            picking_data['note'] = _("This claim was CANCELED.")
        picking_data['name'] = new_pick_name
        picking_data['type'] = 'out'
        picking_data['claim_id'] = claim.id
        picking_data['origin'] = claim.number
        picking_data['location_id'] = picking_in.location_dest_id.id
        if claim.type_action == 'discard':
            picking_data['location_dest_id'] = self._get_scrap_location(cr, uid, claim, context)
        elif claim.type_action == 'replace':
            picking_data['location_dest_id'] = self._get_stock_location(cr, uid, claim, context)
        else:
            picking_data['location_dest_id'] = picking_in.location_id.id
            picking_data['partner_id'] = picking_in.partner_id.id
            picking_data['address_id'] = picking_in.address_id.id
        picking_data['date'] = now
        picking_data['min_date'] = now
        picking_data['invoice_state'] = 'none'
        picking_data['company_id'] = claim.company_id.id
        return picking_data

    def _prepare_order_moves_out(self, cr, uid, claim, picking_id, valid_lines_in, context={}):
        """
        Return a list with the moves data to be created into the Picking OUT
        """
        now = time.strftime('%Y-%m-%d %H:%M:%S')
        moves_data = []
        for l in valid_lines_in:
            m = self.pool.get("stock.move").browse(cr, uid, l['id'], context=context)
            move_data = {}
            move_data['picking_id'] = picking_id
            move_data['date'] = now
            move_data['date_expected'] = now
            move_data['product_qty'] = l['left_qty']
            move_data['product_id'] = m.product_id.id
            move_data['product_uom'] = m.product_uom.id
            move_data['name'] = m.name
            move_data['location_id'] = m.location_dest_id.id
            if claim.type_action == 'discard':
                move_data['location_dest_id'] = self._get_scrap_location(cr, uid, claim, context)
            elif claim.type_action == 'replace':
                move_data['location_dest_id'] = self._get_stock_location(cr, uid, claim, context)
            else:
                move_data['location_dest_id'] = m.location_id.id
            move_data['company_id'] = m.company_id.id
            move_data['move_origin_return'] = m.id
            moves_data.append(move_data)
        return moves_data

    def create_auto_picking_out(self, cr, uid, ids, context={}):
        """
        Create a return picking automatically with a stock move from
        the repair location to parter location.

        Return a dict with the picking ids created by claim
        """
        wf_service = netsvc.LocalService("workflow")
        move_obj = self.pool.get('stock.move')
        picking_obj = self.pool.get('stock.picking')
        ctx = context.copy()
        picks = {}
        for claim in self.browse(cr, uid, ids, context):
            picks[claim.id] = []
            picking_in = picking_obj.browse(cr, uid, \
                                self._get_auto_picking_in(cr, uid, claim, context),\
                                context=context)
            valid_lines = self.get_no_return_history(cr, uid, ids, picking_in, context)
            if len(valid_lines):
                # Create picking
                picking_data = self._prepare_order_picking_out(cr, uid, claim, picking_in, context)
                picking_id = picking_obj.create(cr, uid, picking_data, context=ctx)
                # Create stock move
                moves_data = self._prepare_order_moves_out(cr, uid, claim, picking_id, valid_lines, context)
                for move in moves_data:
                    move_id = move_obj.create(cr, uid, move, context=ctx)
                    move_obj.write(cr, uid, move['move_origin_return'], {'move_history_ids2':[(4,move_id)]})
                # Confirm and validate the picking
                wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
                picking_obj.action_move(cr, uid, [picking_id])
                wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_done', cr)
                if context.get('claim_cancel', False):
                    # If a picking OUT to "reconcile" Picking IN on a canceled
                    # Claim, add a note
                    note = picking_obj.read(cr, uid, picking_in.id, ['note'])['note']
                    if not note or note == "":
                        note = ""
                    else:
                        note += "\n\n"
                    note += _("CANCELED CLAIM: Check return picking %s") % picking_data['name']
                    picking_obj.write(cr, uid, picking_in.id, {'note': note}, context=context)
                picks[claim.id].append(picking_id)
        return picks

    def _get_move_name(self, cr, uid, claim, context={}):
        product_name = ''
        if claim.ref.default_code:
            product_name += '[' + claim.ref.default_code + '] '
        product_name += claim.ref.name
        return product_name

    def _auto_create_picking_in(self, cr, uid, context={}):
        """
        Return ``True`` (default) if product claims without attached
        pickings must be create a return picking when is confirmed.

        If you don't want that orders are created automatically, you must be
        create a ``ir.property`` entry with "crm_claim_picking_auto" key and "False"
        text value.
        """
        property_obj = self.pool.get('ir.property')
        prop_ids = property_obj.search(cr, uid, [('name', '=', 'crm_claim_picking_auto')],context=context)
        if len(prop_ids)>0:
            return property_obj.read(cr,uid,prop_ids[0],['value_text'],context=context)['value_text']
        return True

    def _auto_create_picking_out(self, cr, uid, context={}):
        return self._auto_create_picking_in(cr, uid, context)

    def get_no_return_history(self, cr, uid, ids, pick, context={}):
        """
        Get the moves from ``pick`` not returned or partially returned.

        Extracted from ``stock.wizard.stock_return_picking.stock_return_picking.view_init`` function.

        @return: A list with the move ids, each with the quantity left to return.
        Ex: ``[{'id': 23L, 'product_qty': 3.0, 'left_qty': 1.0}]``
        """
        valid_lines = []
        return_history = self.pool.get("stock.return.picking").get_return_history(cr, uid, pick.id, context)
        for m in pick.move_lines:
            qty_left = m.product_qty * m.product_uom.factor - return_history[m.id]
            if (return_history.get(m.id) is not None) and qty_left > 0:
                    valid_lines.append({'id': m.id, 'product_qty': m.product_qty, 'left_qty': qty_left})
        return valid_lines

    def copy(self, cr, uid, _id, default={}, context=None):
        default.update({
                'picking_ids': [],
            })
        return super(crm_claim, self).copy(cr, uid, _id, default, context)

crm_claim()