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