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
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 TeMPO Consulting, MSF
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from osv import osv, fields
from order_types import ORDER_PRIORITY, ORDER_CATEGORY
import netsvc
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from mx.DateTime import *
from tools.translate import _
class sale_order(osv.osv):
_name = 'sale.order'
_inherit = 'sale.order'
def copy(self, cr, uid, id, default, context={}):
'''
Delete the loan_id field on the new sale.order
'''
return super(sale_order, self).copy(cr, uid, id, default={'loan_id': False}, context=context)
#@@@override sale.sale_order._invoiced
def _invoiced(self, cr, uid, ids, name, arg, context={}):
'''
Return True is the sale order is an uninvoiced order
'''
partner_obj = self.pool.get('res.partner')
partner = False
res = {}
for sale in self.browse(cr, uid, ids):
if sale.partner_id:
partner = partner_obj.browse(cr, uid, [sale.partner_id.id])[0]
if sale.state != 'draft' and (sale.order_type != 'regular' or (partner and partner.partner_type == 'internal')):
res[sale.id] = True
else:
res[sale.id] = True
for invoice in sale.invoice_ids:
if invoice.state != 'paid':
res[sale.id] = False
break
if not sale.invoice_ids:
res[sale.id] = False
return res
#@@@end
#@@@override sale.sale_order._invoiced_search
def _invoiced_search(self, cursor, user, obj, name, args, context={}):
if not len(args):
return []
clause = ''
sale_clause = ''
no_invoiced = False
for arg in args:
if arg[1] == '=':
if arg[2]:
clause += 'AND inv.state = \'paid\' OR (sale.state != \'draft\' AND (sale.order_type != \'regular\' OR part.partner_type = \'internal\'))'
else:
clause += 'AND inv.state != \'cancel\' AND sale.state != \'cancel\' AND inv.state <> \'paid\' AND sale.order_type = \'regular\''
no_invoiced = True
cursor.execute('SELECT rel.order_id ' \
'FROM sale_order_invoice_rel AS rel, account_invoice AS inv, sale_order AS sale, res_partner AS part '+ sale_clause + \
'WHERE rel.invoice_id = inv.id AND rel.order_id = sale.id AND sale.partner_id = part.id ' + clause)
res = cursor.fetchall()
if no_invoiced:
cursor.execute('SELECT sale.id ' \
'FROM sale_order AS sale, res_partner AS part ' \
'WHERE sale.id NOT IN ' \
'(SELECT rel.order_id ' \
'FROM sale_order_invoice_rel AS rel) and sale.state != \'cancel\'' \
'AND sale.partner_id = part.id ' \
'AND sale.order_type = \'regular\' AND part.partner_type != \'internal\'')
res.extend(cursor.fetchall())
if not res:
return [('id', '=', 0)]
return [('id', 'in', [x[0] for x in res])]
#@@@end
#@@@override sale.sale_order._invoiced_rate
def _invoiced_rate(self, cursor, user, ids, name, arg, context=None):
res = {}
for sale in self.browse(cursor, user, ids, context=context):
if sale.invoiced:
res[sale.id] = 100.0
continue
tot = 0.0
for invoice in sale.invoice_ids:
if invoice.state not in ('draft', 'cancel'):
tot += invoice.amount_untaxed
if tot:
res[sale.id] = min(100.0, tot * 100.0 / (sale.amount_untaxed or 1.00))
else:
res[sale.id] = 0.0
return res
#@@@end
def _get_noinvoice(self, cr, uid, ids, name, arg, context={}):
res = {}
for sale in self.browse(cr, uid, ids):
res[sale.id] = sale.order_type != 'regular' or sale.partner_id.partner_type == 'internal'
return res
_columns = {
'order_type': fields.selection([('regular', 'Regular'), ('donation_exp', 'Donation before expiry'),
('donation_st', 'Standard donation (for help)'), ('loan', 'Loan'),],
string='Order Type', required=True, readonly=True, states={'draft': [('readonly', False)]}),
'loan_id': fields.many2one('purchase.order', string='Linked loan', readonly=True),
'priority': fields.selection(ORDER_PRIORITY, string='Priority', readonly=True, states={'draft': [('readonly', False)]}),
'categ': fields.selection(ORDER_CATEGORY, string='Order category', required=True, readonly=True, states={'draft': [('readonly', False)]}),
'details': fields.char(size=30, string='Details', readonly=True, states={'draft': [('readonly', False)]}),
'invoiced': fields.function(_invoiced, method=True, string='Paid',
fnct_search=_invoiced_search, type='boolean', help="It indicates that an invoice has been paid."),
'invoiced_rate': fields.function(_invoiced_rate, method=True, string='Invoiced', type='float'),
'noinvoice': fields.function(_get_noinvoice, method=True, string="Don't create an invoice", type='boolean'),
'loan_duration': fields.integer(string='Loan duration', help='Loan duration in months', readonly=True, states={'draft': [('readonly', False)]}),
}
_defaults = {
'order_type': lambda *a: 'regular',
'priority': lambda *a: 'normal',
'categ': lambda *a: 'mixed',
'loan_duration': lambda *a: 2,
}
def action_wait(self, cr, uid, ids, *args):
'''
Checks if the invoice should be create from the sale order
or not
'''
line_obj = self.pool.get('sale.order.line')
lines = []
if isinstance(ids, (int, long)):
ids = [ids]
for order in self.browse(cr, uid, ids):
if order.partner_id.partner_type == 'internal' and order.order_type == 'regular':
self.write(cr, uid, [order.id], {'order_policy': 'manual'})
for line in order.order_line:
lines.append(line.id)
elif order.order_type in ['donation_exp', 'donation_st', 'loan']:
self.write(cr, uid, [order.id], {'order_policy': 'manual'})
for line in order.order_line:
lines.append(line.id)
else:
self.write(cr, uid, [order.id], {'order_policy': 'manual'})
line_obj.write(cr, uid, lines, {'invoiced': 1})
return super(sale_order, self).action_wait(cr, uid, ids, args)
def action_purchase_order_create(self, cr, uid, ids, context={}):
'''
Create a purchase order as counterpart for the loan.
'''
if isinstance(ids, (int, long)):
ids = [ids]
purchase_obj = self.pool.get('purchase.order')
purchase_line_obj = self.pool.get('purchase.order.line')
partner_obj = self.pool.get('res.partner')
for order in self.browse(cr, uid, ids):
two_months = today() + RelativeDateTime(months=+2)
order_id = purchase_obj.create(cr, uid, {'partner_id': order.partner_id.id,
'partner_address_id': partner_obj.address_get(cr, uid, [order.partner_id.id], ['contact'])['contact'],
'pricelist_id': order.partner_id.property_product_pricelist_purchase.id,
'loan_id': order.id,
'loan_duration': order.loan_duration,
'origin': order.name,
'order_type': 'loan',
'delivery_requested_date': (today() + RelativeDateTime(months=+order.loan_duration)).strftime('%Y-%m-%d'),
'categ': order.categ,
'location_id': order.shop_id.warehouse_id.lot_stock_id.id,
'priority': order.priority,})
for line in order.order_line:
purchase_line_obj.create(cr, uid, {'product_id': line.product_id and line.product_id.id or False,
'product_uom': line.product_uom.id,
'order_id': order_id,
'price_unit': line.price_unit,
'product_qty': line.product_uom_qty,
'date_planned': (today() + RelativeDateTime(months=+order.loan_duration)).strftime('%Y-%m-%d'),
'name': line.name,})
self.write(cr, uid, [order.id], {'loan_id': order_id})
purchase = purchase_obj.browse(cr, uid, order_id)
message = _("Loan counterpart '%s' is created.") % (purchase.name,)
purchase_obj.log(cr, uid, order_id, message)
return order_id
def has_stockable_products(self, cr, uid, ids, *args):
'''
Override the has_stockable_product to return False
when the internal_type of the order is 'direct'
'''
for order in self.browse(cr, uid, ids):
if order.order_type != 'direct':
return super(sale_order, self).has_stockable_product(cr, uid, ids, args)
return False
#@@@override sale.sale_order.action_invoice_end
def action_invoice_end(self, cr, uid, ids, context=None):
'''
Modified to set lines invoiced when order_type is not regular
'''
for order in self.browse(cr, uid, ids, context=context):
#
# Update the sale order lines state (and invoiced flag).
#
for line in order.order_line:
vals = {}
#
# Check if the line is invoiced (has asociated invoice
# lines from non-cancelled invoices).
#
invoiced = order.noinvoice
if not invoiced:
for iline in line.invoice_lines:
if iline.invoice_id and iline.invoice_id.state != 'cancel':
invoiced = True
break
if line.invoiced != invoiced:
vals['invoiced'] = invoiced
# If the line was in exception state, now it gets confirmed.
if line.state == 'exception':
vals['state'] = 'confirmed'
# Update the line (only when needed).
if vals:
self.pool.get('sale.order.line').write(cr, uid, [line.id], vals, context=context)
#
# Update the sales order state.
#
if order.state == 'invoice_except':
self.write(cr, uid, [order.id], {'state': 'progress'}, context=context)
return True
#@@@end
def _hook_ship_create_stock_move(self, cr, uid, ids, move_data, order_line, *args, **kwargs):
return move_data
def _hook_ship_create_procurement_order(self, cr, uid, ids, procurement_data, order_line, *args, **kwargs):
return procurement_data
# @@@override@sale.sale.order.action_ship_create
def action_ship_create(self, cr, uid, ids, *args, **kwargs):
"""
Adds hooks
"""
wf_service = netsvc.LocalService("workflow")
picking_id = False
move_obj = self.pool.get('stock.move')
proc_obj = self.pool.get('procurement.order')
company = self.pool.get('res.users').browse(cr, uid, uid).company_id
for order in self.browse(cr, uid, ids, context={}):
proc_ids = []
reason_type_id = False
output_id = order.shop_id.warehouse_id.lot_output_id.id
picking_id = False
for line in order.order_line:
proc_id = False
date_planned = datetime.now() + relativedelta(days=line.delay or 0.0)
date_planned = (date_planned - timedelta(days=company.security_lead)).strftime('%Y-%m-%d %H:%M:%S')
if line.state == 'done':
continue
move_id = False
if line.product_id and line.product_id.product_tmpl_id.type in ('product', 'consu') and not line.order_id.procurement_request:
location_id = order.shop_id.warehouse_id.lot_stock_id.id
if not picking_id:
pick_name = self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.out')
picking_values = {
'name': pick_name,
'origin': order.name,
'type': 'out',
'state': 'auto',
'move_type': order.picking_policy,
'sale_id': order.id,
'address_id': order.partner_shipping_id.id,
'note': order.note,
'invoice_state': (order.order_policy=='picking' and '2binvoiced') or 'none',
'company_id': order.company_id.id,
}
if order.order_type == 'regular':
reason_type_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'reason_types_moves', 'reason_type_deliver_partner')[1],
if order.order_type == 'loan':
reason_type_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'reason_types_moves', 'reason_type_loan')[1],
if order.order_type == 'donation_st':
reason_type_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'reason_types_moves', 'reason_type_donation')[1],
if order.order_type == 'donation_exp':
reason_type_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'reason_types_moves', 'reason_type_donation_expiry')[1]
if reason_type_id:
picking_values.update({'reason_type_id': reason_type_id})
picking_id = self.pool.get('stock.picking').create(cr, uid, picking_values)
move_data = {
'name': line.name[:64],
'picking_id': picking_id,
'product_id': line.product_id.id,
'date': date_planned,
'date_expected': date_planned,
'product_qty': line.product_uom_qty,
'product_uom': line.product_uom.id,
'product_uos_qty': line.product_uos_qty,
'product_uos': (line.product_uos and line.product_uos.id)\
or line.product_uom.id,
'product_packaging': line.product_packaging.id,
'address_id': line.address_allotment_id.id or order.partner_shipping_id.id,
'location_id': location_id,
'location_dest_id': output_id,
'sale_line_id': line.id,
'tracking_id': False,
'state': 'draft',
#'state': 'waiting',
'note': line.notes,
'company_id': order.company_id.id,
}
if reason_type_id:
move_data.update({'reason_type_id': reason_type_id})
move_data = self._hook_ship_create_stock_move(cr, uid, ids, move_data, line, *args, **kwargs)
move_id = self.pool.get('stock.move').create(cr, uid, move_data)
if line.product_id:
proc_data = {
'name': line.name,
'origin': order.name,
'date_planned': date_planned,
'product_id': line.product_id.id,
'product_qty': line.product_uom_qty,
'product_uom': line.product_uom.id,
'product_uos_qty': (line.product_uos and line.product_uos_qty)\
or line.product_uom_qty,
'product_uos': (line.product_uos and line.product_uos.id)\
or line.product_uom.id,
'location_id': order.shop_id.warehouse_id.lot_stock_id.id,
'procure_method': line.type,
'move_id': move_id,
'property_ids': [(6, 0, [x.id for x in line.property_ids])],
'company_id': order.company_id.id,
}
proc_data = self._hook_ship_create_procurement_order(cr, uid, ids, proc_data, line, *args, **kwargs)
proc_id = self.pool.get('procurement.order').create(cr, uid, proc_data)
proc_ids.append(proc_id)
self.pool.get('sale.order.line').write(cr, uid, [line.id], {'procurement_id': proc_id})
if order.state == 'shipping_except':
for pick in order.picking_ids:
for move in pick.move_lines:
if move.state == 'cancel':
mov_ids = move_obj.search(cr, uid, [('state', '=', 'cancel'),('sale_line_id', '=', line.id),('picking_id', '=', pick.id)])
if mov_ids:
for mov in move_obj.browse(cr, uid, mov_ids):
move_obj.write(cr, uid, [move_id], {'product_qty': mov.product_qty, 'product_uos_qty': mov.product_uos_qty})
proc_obj.write(cr, uid, [proc_id], {'product_qty': mov.product_qty, 'product_uos_qty': mov.product_uos_qty})
val = {}
if picking_id:
wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
for proc_id in proc_ids:
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
if order.state == 'proc_progress':
wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_check', cr)
if order.state == 'shipping_except':
val['state'] = 'progress'
val['shipped'] = False
if (order.order_policy == 'manual'):
for line in order.order_line:
if (not line.invoiced) and (line.state not in ('cancel', 'draft')):
val['state'] = 'manual'
break
self.write(cr, uid, [order.id], val)
return True
# @@@end
sale_order()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|