[imp] refactoring in Widget in Web client
[odoo/odoo.git] / addons / point_of_sale / point_of_sale.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import time
23 from datetime import datetime
24 from dateutil.relativedelta import relativedelta
25 import logging
26
27 import netsvc
28 from osv import fields, osv
29 from tools.translate import _
30 from decimal import Decimal
31 import decimal_precision as dp
32
33 _logger = logging.getLogger(__name__)
34
35 class pos_config_journal(osv.osv):
36     """ Point of Sale journal configuration"""
37     _name = 'pos.config.journal'
38     _description = "Journal Configuration"
39
40     _columns = {
41         'name': fields.char('Description', size=64),
42         'code': fields.char('Code', size=64),
43         'journal_id': fields.many2one('account.journal', "Journal")
44     }
45
46 pos_config_journal()
47
48 class pos_order(osv.osv):
49     _name = "pos.order"
50     _description = "Point of Sale"
51     _order = "id desc"
52     
53     def create_from_ui(self, cr, uid, orders, context=None):
54         #_logger.info("orders: %r", orders)
55         list = []
56         for order in orders:
57             list.append(self.create(cr, uid, order, context))
58             wf_service = netsvc.LocalService("workflow")
59             wf_service.trg_validate(uid, 'pos.order', list[-1], 'paid', cr)
60         return list
61
62     def unlink(self, cr, uid, ids, context=None):
63         for rec in self.browse(cr, uid, ids, context=context):
64             if rec.state not in ('draft','cancel'):
65                 raise osv.except_osv(_('Unable to Delete !'), _('In order to delete a sale, it must be new or cancelled.'))
66         return super(pos_order, self).unlink(cr, uid, ids, context=context)
67
68     def onchange_partner_id(self, cr, uid, ids, part=False, context=None):
69         if not part:
70             return {'value': {}}
71         pricelist = self.pool.get('res.partner').browse(cr, uid, part, context=context).property_product_pricelist.id
72         return {'value': {'pricelist_id': pricelist}}
73
74     def _amount_all(self, cr, uid, ids, name, args, context=None):
75         tax_obj = self.pool.get('account.tax')
76         cur_obj = self.pool.get('res.currency')
77         res = {}
78         for order in self.browse(cr, uid, ids, context=context):
79             res[order.id] = {
80                 'amount_paid': 0.0,
81                 'amount_return':0.0,
82                 'amount_tax':0.0,
83             }
84             val1 = val2 = 0.0
85             cur = order.pricelist_id.currency_id
86             for payment in order.statement_ids:
87                 res[order.id]['amount_paid'] +=  payment.amount
88                 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
89             for line in order.lines:
90                 val1 += line.price_subtotal_incl
91                 val2 += line.price_subtotal
92             res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val1-val2)
93             res[order.id]['amount_total'] = cur_obj.round(cr, uid, cur, val1)
94         return res
95
96     def _default_sale_journal(self, cr, uid, context=None):
97         res = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'sale')], limit=1)
98         return res and res[0] or False
99
100     def _default_shop(self, cr, uid, context=None):
101         res = self.pool.get('sale.shop').search(cr, uid, [])
102         return res and res[0] or False
103
104     def copy(self, cr, uid, id, default=None, context=None):
105         if not default:
106             default = {}
107         d = {
108             'state': 'draft',
109             'invoice_id': False,
110             'account_move': False,
111             'picking_id': False,
112             'statement_ids': [],
113             'nb_print': 0,
114             'name': self.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
115         }
116         d.update(default)
117         return super(pos_order, self).copy(cr, uid, id, d, context=context)
118
119     _columns = {
120         'name': fields.char('Order Ref', size=64, required=True,
121             states={'draft': [('readonly', False)]}, readonly=True),
122         'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
123         'shop_id': fields.many2one('sale.shop', 'Shop', required=True,
124             states={'draft': [('readonly', False)]}, readonly=True),
125         'date_order': fields.datetime('Date Ordered', readonly=True, select=True),
126         'user_id': fields.many2one('res.users', 'Connected Salesman', help="Person who uses the the cash register. It could be a reliever, a student or an interim employee."),
127         'amount_tax': fields.function(_amount_all, string='Taxes', digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
128         'amount_total': fields.function(_amount_all, string='Total', multi='all'),
129         'amount_paid': fields.function(_amount_all, string='Paid', states={'draft': [('readonly', False)]}, readonly=True, digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
130         'amount_return': fields.function(_amount_all, 'Returned', digits_compute=dp.get_precision('Point Of Sale'), multi='all'),
131         'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True),
132         'statement_ids': fields.one2many('account.bank.statement.line', 'pos_statement_id', 'Payments', states={'draft': [('readonly', False)]}, readonly=True),
133         'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
134         'partner_id': fields.many2one('res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
135
136         'state': fields.selection([('draft', 'New'),
137                                    ('cancel', 'Cancelled'),
138                                    ('paid', 'Paid'),
139                                    ('done', 'Posted'),
140                                    ('invoiced', 'Invoiced')],
141                                   'State', readonly=True),
142
143         'invoice_id': fields.many2one('account.invoice', 'Invoice'),
144         'account_move': fields.many2one('account.move', 'Journal Entry', readonly=True),
145         'picking_id': fields.many2one('stock.picking', 'Picking', readonly=True),
146         'note': fields.text('Internal Notes'),
147         'nb_print': fields.integer('Number of Print', readonly=True),
148         'sale_journal': fields.many2one('account.journal', 'Journal', required=True, states={'draft': [('readonly', False)]}, readonly=True),
149     }
150
151     def _default_pricelist(self, cr, uid, context=None):
152         res = self.pool.get('sale.shop').search(cr, uid, [], context=context)
153         if res:
154             shop = self.pool.get('sale.shop').browse(cr, uid, res[0], context=context)
155             return shop.pricelist_id and shop.pricelist_id.id or False
156         return False
157
158     _defaults = {
159         'user_id': lambda self, cr, uid, context: uid,
160         'state': 'draft',
161         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order'),
162         'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
163         'nb_print': 0,
164         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
165         'sale_journal': _default_sale_journal,
166         'shop_id': _default_shop,
167         'pricelist_id': _default_pricelist,
168     }
169
170     def test_paid(self, cr, uid, ids, context=None):
171         """A Point of Sale is paid when the sum
172         @return: True
173         """
174         for order in self.browse(cr, uid, ids, context=context):
175             if order.lines and not order.amount_total:
176                 return True
177             if (not order.lines) or (not order.statement_ids) or \
178                 (abs(order.amount_total-order.amount_paid) > 0.00001):
179                 return False
180         return True
181
182     def create_picking(self, cr, uid, ids, context=None):
183         """Create a picking for each order and validate it."""
184         picking_obj = self.pool.get('stock.picking')
185         partner_obj = self.pool.get('res.partner')
186         move_obj = self.pool.get('stock.move')
187
188         for order in self.browse(cr, uid, ids, context=context):
189             if not order.state=='draft':
190                 continue
191             addr = order.partner_id and partner_obj.address_get(cr, uid, [order.partner_id.id], ['delivery']) or {}
192             picking_id = picking_obj.create(cr, uid, {
193                 'origin': order.name,
194                 'address_id': addr.get('delivery',False),
195                 'type': 'out',
196                 'company_id': order.company_id.id,
197                 'move_type': 'direct',
198                 'note': order.note or "",
199                 'invoice_state': 'none',
200                 'auto_picking': True,
201             }, context=context)
202             self.write(cr, uid, [order.id], {'picking_id': picking_id}, context=context)
203             location_id = order.shop_id.warehouse_id.lot_stock_id.id
204             output_id = order.shop_id.warehouse_id.lot_output_id.id
205
206             for line in order.lines:
207                 if line.product_id and line.product_id.type == 'service':
208                     continue
209                 if line.qty < 0:
210                     location_id, output_id = output_id, location_id
211
212                 move_obj.create(cr, uid, {
213                     'name': line.name,
214                     'product_uom': line.product_id.uom_id.id,
215                     'product_uos': line.product_id.uom_id.id,
216                     'picking_id': picking_id,
217                     'product_id': line.product_id.id,
218                     'product_uos_qty': abs(line.qty),
219                     'product_qty': abs(line.qty),
220                     'tracking_id': False,
221                     'state': 'draft',
222                     'location_id': location_id,
223                     'location_dest_id': output_id,
224                 }, context=context)
225                 if line.qty < 0:
226                     location_id, output_id = output_id, location_id
227
228             wf_service = netsvc.LocalService("workflow")
229             wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr)
230             picking_obj.force_assign(cr, uid, [picking_id], context)
231         return True
232
233     def set_to_draft(self, cr, uid, ids, *args):
234         if not len(ids):
235             return False
236         for order in self.browse(cr, uid, ids, context=context):
237             if order.state<>'cancel':
238                 raise osv.except_osv(_('Error!'), _('In order to set to draft a sale, it must be cancelled.'))
239         self.write(cr, uid, ids, {'state': 'draft'})
240         wf_service = netsvc.LocalService("workflow")
241         for i in ids:
242             wf_service.trg_create(uid, 'pos.order', i, cr)
243         return True
244
245     def cancel_order(self, cr, uid, ids, context=None):
246         """ Changes order state to cancel
247         @return: True
248         """
249         stock_picking_obj = self.pool.get('stock.picking')
250         for order in self.browse(cr, uid, ids, context=context):
251             wf_service.trg_validate(uid, 'stock.picking', order.picking_id.id, 'button_cancel', cr)
252             if stock_picking_obj.browse(cr, uid, order.picking_id.id, context=context).state <> 'cancel':
253                 raise osv.except_osv(_('Error!'), _('Unable to cancel the picking.'))
254         self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
255         return True
256
257     def add_payment(self, cr, uid, order_id, data, context=None):
258         """Create a new payment for the order"""
259         statement_obj = self.pool.get('account.bank.statement')
260         statement_line_obj = self.pool.get('account.bank.statement.line')
261         prod_obj = self.pool.get('product.product')
262         property_obj = self.pool.get('ir.property')
263         curr_c = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
264         curr_company = curr_c.id
265         order = self.browse(cr, uid, order_id, context=context)
266         ids_new = []
267         args = {
268             'amount': data['amount'],
269         }
270         if 'payment_date' in data.keys():
271             args['date'] = data['payment_date']
272         args['name'] = order.name
273         if data.get('payment_name', False):
274             args['name'] = args['name'] + ': ' + data['payment_name']
275         account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
276         args['account_id'] = (order.partner_id and order.partner_id.property_account_receivable \
277                              and order.partner_id.property_account_receivable.id) or (account_def and account_def.id) or False
278         args['partner_id'] = order.partner_id and order.partner_id.id or None
279
280         if not args['account_id']:
281             if not args['partner_id']:
282                 msg = _('There is no receivable account defined to make payment')
283             else:
284                 msg = _('There is no receivable account defined to make payment for the partner: "%s" (id:%d)') % (order.partner_id.name, order.partner_id.id,)
285             raise osv.except_osv(_('Configuration Error !'), msg)
286
287         statement_id = statement_obj.search(cr,uid, [
288                                                      ('journal_id', '=', int(data['journal'])),
289                                                      ('company_id', '=', curr_company),
290                                                      ('user_id', '=', uid),
291                                                      ('state', '=', 'open')], context=context)
292         if len(statement_id) == 0:
293             raise osv.except_osv(_('Error !'), _('You have to open at least one cashbox'))
294         if statement_id:
295             statement_id = statement_id[0]
296         args['statement_id'] = statement_id
297         args['pos_statement_id'] = order_id
298         args['journal_id'] = int(data['journal'])
299         args['type'] = 'customer'
300         args['ref'] = order.name
301         statement_line_obj.create(cr, uid, args, context=context)
302         ids_new.append(statement_id)
303
304         wf_service = netsvc.LocalService("workflow")
305         wf_service.trg_validate(uid, 'pos.order', order_id, 'paid', cr)
306         wf_service.trg_write(uid, 'pos.order', order_id, cr)
307
308         return statement_id
309
310     def refund(self, cr, uid, ids, context=None):
311         """Create a copy of order  for refund order"""
312         clone_list = []
313         line_obj = self.pool.get('pos.order.line')
314         for order in self.browse(cr, uid, ids, context=context):
315             clone_id = self.copy(cr, uid, order.id, {
316                 'name': order.name + ' REFUND',
317             }, context=context)
318             clone_list.append(clone_id)
319
320         for clone in self.browse(cr, uid, clone_list, context=context):
321             for order_line in clone.lines:
322                 line_obj.write(cr, uid, [order_line.id], {
323                     'qty': -order_line.qty
324                 }, context=context)
325
326         new_order = ','.join(map(str,clone_list))
327         abs = {
328             #'domain': "[('id', 'in', ["+new_order+"])]",
329             'name': _('Return Products'),
330             'view_type': 'form',
331             'view_mode': 'form',
332             'res_model': 'pos.order',
333             'res_id':clone_list[0],
334             'view_id': False,
335             'context':context,
336             'type': 'ir.actions.act_window',
337             'nodestroy': True,
338             'target': 'current',
339         }
340         return abs
341
342     def action_invoice_state(self, cr, uid, ids, context=None):
343         return self.write(cr, uid, ids, {'state':'invoiced'}, context=context)
344
345     def action_invoice(self, cr, uid, ids, context=None):
346         wf_service = netsvc.LocalService("workflow")
347         inv_ref = self.pool.get('account.invoice')
348         inv_line_ref = self.pool.get('account.invoice.line')
349         product_obj = self.pool.get('product.product')
350         inv_ids = []
351
352         for order in self.pool.get('pos.order').browse(cr, uid, ids, context=context):
353             if order.invoice_id:
354                 inv_ids.append(order.invoice_id.id)
355                 continue
356
357             if not order.partner_id:
358                 raise osv.except_osv(_('Error'), _('Please provide a partner for the sale.'))
359
360             acc = order.partner_id.property_account_receivable.id
361             inv = {
362                 'name': order.name,
363                 'origin': order.name,
364                 'account_id': acc,
365                 'journal_id': order.sale_journal.id or None,
366                 'type': 'out_invoice',
367                 'reference': order.name,
368                 'partner_id': order.partner_id.id,
369                 'comment': order.note or '',
370                 'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
371             }
372             inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
373             if not inv.get('account_id', None):
374                 inv['account_id'] = acc
375             inv_id = inv_ref.create(cr, uid, inv, context=context)
376
377             self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
378             inv_ids.append(inv_id)
379             for line in order.lines:
380                 inv_line = {
381                     'invoice_id': inv_id,
382                     'product_id': line.product_id.id,
383                     'quantity': line.qty,
384                 }
385                 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
386                 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
387                                                                line.product_id.id,
388                                                                line.product_id.uom_id.id,
389                                                                line.qty, partner_id = order.partner_id.id,
390                                                                fposition_id=order.partner_id.property_account_position.id)['value'])
391                 if line.product_id.description_sale:
392                     inv_line['note'] = line.product_id.description_sale
393                 inv_line['price_unit'] = line.price_unit
394                 inv_line['discount'] = line.discount
395                 inv_line['name'] = inv_name
396                 inv_line['invoice_line_tax_id'] = ('invoice_line_tax_id' in inv_line)\
397                     and [(6, 0, inv_line['invoice_line_tax_id'])] or []
398                 inv_line_ref.create(cr, uid, inv_line, context=context)
399             inv_ref.button_reset_taxes(cr, uid, [inv_id], context=context)
400             wf_service.trg_validate(uid, 'pos.order', order.id, 'invoice', cr)
401
402         if not inv_ids: return {}
403         
404         mod_obj = self.pool.get('ir.model.data')
405         res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form')
406         res_id = res and res[1] or False
407         return {
408             'name': _('Customer Invoice'),
409             'view_type': 'form',
410             'view_mode': 'form',
411             'view_id': [res_id],
412             'res_model': 'account.invoice',
413             'context': "{'type':'out_invoice'}",
414             'type': 'ir.actions.act_window',
415             'nodestroy': True,
416             'target': 'current',
417             'res_id': inv_ids and inv_ids[0] or False,
418         }
419
420     def create_account_move(self, cr, uid, ids, context=None):
421         """Create a account move line of order grouped by products or not."""
422         account_move_obj = self.pool.get('account.move')
423         account_move_line_obj = self.pool.get('account.move.line')
424         account_period_obj = self.pool.get('account.period')
425         period = account_period_obj.find(cr, uid, context=context)[0]
426         account_tax_obj = self.pool.get('account.tax')
427         res_obj=self.pool.get('res.users')
428         property_obj=self.pool.get('ir.property')
429
430         for order in self.browse(cr, uid, ids, context=context):
431             if order.state<>'paid': continue
432
433             curr_c = res_obj.browse(cr, uid, uid).company_id
434             comp_id = res_obj.browse(cr, order.user_id.id, order.user_id.id).company_id
435             comp_id = comp_id and comp_id.id or False
436             to_reconcile = []
437             group_tax = {}
438             account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context).id
439
440             order_account = order.partner_id and order.partner_id.property_account_receivable and order.partner_id.property_account_receivable.id or account_def or curr_c.account_receivable.id
441
442             # Create an entry for the sale
443             move_id = account_move_obj.create(cr, uid, {
444                 'journal_id': order.sale_journal.id,
445             }, context=context)
446
447             # Create an move for each order line
448             for line in order.lines:
449                 tax_amount = 0
450                 taxes = [t for t in line.product_id.taxes_id]
451                 computed = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit * (100.0-line.discount) / 100.0, line.qty)
452                 computed_taxes = computed['taxes']
453
454                 for tax in computed_taxes:
455                     tax_amount += round(tax['amount'], 2)
456                     group_key = (tax['tax_code_id'],
457                                 tax['base_code_id'],
458                                 tax['account_collected_id'])
459
460                     if group_key in group_tax:
461                         group_tax[group_key] += round(tax['amount'], 2)
462                     else:
463                         group_tax[group_key] = round(tax['amount'], 2)
464                 amount = line.price_subtotal
465
466                 # Search for the income account
467                 if  line.product_id.property_account_income.id:
468                     income_account = line.product_id.property_account_income.id
469                 elif line.product_id.categ_id.property_account_income_categ.id:
470                     income_account = line.product_id.categ_id.property_account_income_categ.id
471                 else:
472                     raise osv.except_osv(_('Error !'), _('There is no income '\
473                         'account defined for this product: "%s" (id:%d)') \
474                         % (line.product_id.name, line.product_id.id, ))
475
476                 # Empty the tax list as long as there is no tax code:
477                 tax_code_id = False
478                 tax_amount = 0
479                 while computed_taxes:
480                     tax = computed_taxes.pop(0)
481                     if amount > 0:
482                         tax_code_id = tax['base_code_id']
483                         tax_amount = line.price_subtotal * tax['base_sign']
484                     else:
485                         tax_code_id = tax['ref_base_code_id']
486                         tax_amount = line.price_subtotal * tax['ref_base_sign']
487                     # If there is one we stop
488                     if tax_code_id:
489                         break
490
491
492                 # Create a move for the line
493                 account_move_line_obj.create(cr, uid, {
494                     'name': line.name,
495                     'date': order.date_order[:10],
496                     'ref': order.name,
497                     'quantity': line.qty,
498                     'product_id': line.product_id.id,
499                     'move_id': move_id,
500                     'account_id': income_account,
501                     'company_id': comp_id,
502                     'credit': ((amount>0) and amount) or 0.0,
503                     'debit': ((amount<0) and -amount) or 0.0,
504                     'journal_id': order.sale_journal.id,
505                     'period_id': period,
506                     'tax_code_id': tax_code_id,
507                     'tax_amount': tax_amount,
508                     'partner_id': order.partner_id and order.partner_id.id or False
509                 }, context=context)
510
511                 # For each remaining tax with a code, whe create a move line
512                 for tax in computed_taxes:
513                     if amount > 0:
514                         tax_code_id = tax['base_code_id']
515                         tax_amount = line.price_subtotal * tax['base_sign']
516                     else:
517                         tax_code_id = tax['ref_base_code_id']
518                         tax_amount = line.price_subtotal * tax['ref_base_sign']
519                     if not tax_code_id:
520                         continue
521
522                     account_move_line_obj.create(cr, uid, {
523                         'name': "Tax" + line.name,
524                         'date': order.date_order[:10],
525                         'ref': order.name,
526                         'product_id':line.product_id.id,
527                         'quantity': line.qty,
528                         'move_id': move_id,
529                         'account_id': income_account,
530                         'company_id': comp_id,
531                         'credit': 0.0,
532                         'debit': 0.0,
533                         'journal_id': order.sale_journal.id,
534                         'period_id': period,
535                         'tax_code_id': tax_code_id,
536                         'tax_amount': tax_amount,
537                     }, context=context)
538
539
540             # Create a move for each tax group
541             (tax_code_pos, base_code_pos, account_pos)= (0, 1, 2)
542             for key, amount in group_tax.items():
543                 account_move_line_obj.create(cr, uid, {
544                     'name': 'Tax',
545                     'date': order.date_order[:10],
546                     'ref': order.name,
547                     'move_id': move_id,
548                     'company_id': comp_id,
549                     'quantity': line.qty,
550                     'product_id': line.product_id.id,
551                     'account_id': key[account_pos],
552                     'credit': ((amount>0) and amount) or 0.0,
553                     'debit': ((amount<0) and -amount) or 0.0,
554                     'journal_id': order.sale_journal.id,
555                     'period_id': period,
556                     'tax_code_id': key[tax_code_pos],
557                     'tax_amount': amount,
558                 }, context=context)
559
560             # counterpart
561             to_reconcile.append(account_move_line_obj.create(cr, uid, {
562                 'name': order.name,
563                 'date': order.date_order[:10],
564                 'ref': order.name,
565                 'move_id': move_id,
566                 'company_id': comp_id,
567                 'account_id': order_account,
568                 'credit': ((order.amount_total < 0) and -order.amount_total)\
569                     or 0.0,
570                 'debit': ((order.amount_total > 0) and order.amount_total)\
571                     or 0.0,
572                 'journal_id': order.sale_journal.id,
573                 'period_id': period,
574                 'partner_id': order.partner_id and order.partner_id.id or False
575             }, context=context))
576             self.write(cr, uid, order.id, {'state':'done', 'account_move': move_id}, context=context)
577         return True
578
579     def action_payment(self, cr, uid, ids, context=None):
580         return self.write(cr, uid, ids, {'state': 'payment'}, context=context)
581
582     def action_paid(self, cr, uid, ids, context=None):
583         context = context or {}
584         self.create_picking(cr, uid, ids, context=None)
585         self.write(cr, uid, ids, {'state': 'paid'}, context=context)
586         return True
587
588     def action_cancel(self, cr, uid, ids, context=None):
589         self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
590         return True
591
592     def action_done(self, cr, uid, ids, context=None):
593         self.create_account_move(cr, uid, ids, context=context)
594         return True
595
596 pos_order()
597
598 class account_bank_statement(osv.osv):
599     _inherit = 'account.bank.statement'
600     _columns= {
601         'user_id': fields.many2one('res.users', 'User', readonly=True),
602     }
603     _defaults = {
604         'user_id': lambda self,cr,uid,c={}: uid
605     }
606 account_bank_statement()
607
608 class account_bank_statement_line(osv.osv):
609     _inherit = 'account.bank.statement.line'
610     _columns= {
611         'journal_id': fields.related('statement_id','journal_id','name', store=True, string='Journal', type='char', size=64),
612         'pos_statement_id': fields.many2one('pos.order', ondelete='cascade'),
613     }
614 account_bank_statement_line()
615
616 class pos_order_line(osv.osv):
617     _name = "pos.order.line"
618     _description = "Lines of Point of Sale"
619     _rec_name = "product_id"
620
621     def _amount_line_all(self, cr, uid, ids, field_names, arg, context=None):
622         res = dict([(i, {}) for i in ids])
623         account_tax_obj = self.pool.get('account.tax')
624         cur_obj = self.pool.get('res.currency')
625         for line in self.browse(cr, uid, ids, context=context):
626             taxes = line.product_id.taxes_id
627             price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
628             taxes = account_tax_obj.compute_all(cr, uid, line.product_id.taxes_id, price, line.qty, product=line.product_id, partner=line.order_id.partner_id or False)
629
630             cur = line.order_id.pricelist_id.currency_id
631             res[line.id]['price_subtotal'] = cur_obj.round(cr, uid, cur, taxes['total'])
632             res[line.id]['price_subtotal_incl'] = cur_obj.round(cr, uid, cur, taxes['total_included'])
633         return res
634
635     def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False, context=None):
636        context = context or {}
637        if not product_id:
638             return {}
639        if not pricelist:
640            raise osv.except_osv(_('No Pricelist !'),
641                _('You have to select a pricelist in the sale form !\n' \
642                'Please set one before choosing a product.'))
643
644        price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist],
645                product_id, qty or 1.0, partner_id)[pricelist]
646
647        result = self.onchange_qty(cr, uid, ids, product_id, 0.0, qty, price, context=context)
648        result['value']['price_unit'] = price
649        return result
650
651     def onchange_qty(self, cr, uid, ids, product, discount, qty, price_unit, context=None):
652         result = {}
653         if not product:
654             return result
655         account_tax_obj = self.pool.get('account.tax')
656         cur_obj = self.pool.get('res.currency')
657
658         prod = self.pool.get('product.product').browse(cr, uid, product, context=context)
659
660         taxes = prod.taxes_id
661         price = price_unit * (1 - (discount or 0.0) / 100.0)
662         taxes = account_tax_obj.compute_all(cr, uid, prod.taxes_id, price, qty, product=prod, partner=False)
663
664         result['price_subtotal'] = taxes['total']
665         result['price_subtotal_incl'] = taxes['total_included']
666         return {'value': result}
667
668     _columns = {
669         'company_id': fields.many2one('res.company', 'Company', required=True),
670         'name': fields.char('Line No', size=32, required=True),
671         'notice': fields.char('Discount Notice', size=128),
672         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
673         'price_unit': fields.float(string='Unit Price', digits=(16, 2)),
674         'qty': fields.float('Quantity', digits=(16, 2)),
675         'price_subtotal': fields.function(_amount_line_all, multi='pos_order_line_amount', string='Subtotal w/o Tax', store=True),
676         'price_subtotal_incl': fields.function(_amount_line_all, multi='pos_order_line_amount', string='Subtotal', store=True),
677         'discount': fields.float('Discount (%)', digits=(16, 2)),
678         'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
679         'create_date': fields.datetime('Creation Date', readonly=True),
680     }
681
682     _defaults = {
683         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
684         'qty': lambda *a: 1,
685         'discount': lambda *a: 0.0,
686         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
687     }
688
689     def copy_data(self, cr, uid, id, default=None, context=None):
690         if not default:
691             default = {}
692         default.update({
693             'name': self.pool.get('ir.sequence').get(cr, uid, 'pos.order.line')
694         })
695         return super(pos_order_line, self).copy_data(cr, uid, id, default, context=context)
696
697 pos_order_line()
698
699 class pos_category(osv.osv):
700     _name = 'pos.category'
701     _description = "PoS Category"
702     _order = "sequence, name"
703     def _check_recursion(self, cr, uid, ids, context=None):
704         level = 100
705         while len(ids):
706             cr.execute('select distinct parent_id from pos_category where id IN %s',(tuple(ids),))
707             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
708             if not level:
709                 return False
710             level -= 1
711         return True
712
713     _constraints = [
714         (_check_recursion, 'Error ! You cannot create recursive categories.', ['parent_id'])
715     ]
716
717     def name_get(self, cr, uid, ids, context=None):
718         if not len(ids):
719             return []
720         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
721         res = []
722         for record in reads:
723             name = record['name']
724             if record['parent_id']:
725                 name = record['parent_id'][1]+' / '+name
726             res.append((record['id'], name))
727         return res
728
729     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
730         res = self.name_get(cr, uid, ids, context=context)
731         return dict(res)
732
733     _columns = {
734         'name': fields.char('Name', size=64, required=True, translate=True),
735         'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
736         'parent_id': fields.many2one('pos.category','Parent Category', select=True),
737         'child_id': fields.one2many('pos.category', 'parent_id', string='Children Categories'),
738         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of product categories."),
739     }
740 pos_category()
741
742 class product_product(osv.osv):
743     _inherit = 'product.product'
744     _columns = {
745         'income_pdt': fields.boolean('PoS Cash Input', help="This is a product you can use to put cash into a statement for the point of sale backend."),
746         'expense_pdt': fields.boolean('PoS Cash Output', help="This is a product you can use to take cash from a statement for the point of sale backend, exemple: money lost, transfer to bank, etc."),
747         'pos_categ_id': fields.many2one('pos.category','PoS Category',
748             help="If you want to sell this product through the point of sale, select the category it belongs to.")
749     }
750 product_product()
751
752
753 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: