[FIX] point_of_sale: continuation of the session closing fix
[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 logging
23 import time
24
25 from openerp import tools
26 from openerp.osv import fields, osv
27 from openerp.tools.translate import _
28
29 import openerp.addons.decimal_precision as dp
30 import openerp.addons.product.product
31
32 _logger = logging.getLogger(__name__)
33
34 class pos_config(osv.osv):
35     _name = 'pos.config'
36
37     POS_CONFIG_STATE = [
38         ('active', 'Active'),
39         ('inactive', 'Inactive'),
40         ('deprecated', 'Deprecated')
41     ]
42
43     def _get_currency(self, cr, uid, ids, fieldnames, args, context=None):
44         result = dict.fromkeys(ids, False)
45         for pos_config in self.browse(cr, uid, ids, context=context):
46             if pos_config.journal_id:
47                 currency_id = pos_config.journal_id.currency.id or pos_config.journal_id.company_id.currency_id.id
48             else:
49                 currency_id = self.pool['res.users'].browse(cr, uid, uid, context=context).company_id.currency_id.id
50             result[pos_config.id] = currency_id
51         return result
52
53     _columns = {
54         'name' : fields.char('Point of Sale Name', select=1,
55              required=True, help="An internal identification of the point of sale"),
56         'journal_ids' : fields.many2many('account.journal', 'pos_config_journal_rel', 
57              'pos_config_id', 'journal_id', 'Available Payment Methods',
58              domain="[('journal_user', '=', True ), ('type', 'in', ['bank', 'cash'])]",),
59         'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type'),
60         'stock_location_id': fields.many2one('stock.location', 'Stock Location', domain=[('usage', '=', 'internal')], required=True),
61         'journal_id' : fields.many2one('account.journal', 'Sale Journal',
62              domain=[('type', '=', 'sale')],
63              help="Accounting journal used to post sales entries."),
64         'currency_id' : fields.function(_get_currency, type="many2one", string="Currency", relation="res.currency"),
65         'iface_self_checkout' : fields.boolean('Self Checkout Mode',
66              help="Check this if this point of sale should open by default in a self checkout mode. If unchecked, Odoo uses the normal cashier mode by default."),
67         'iface_cashdrawer' : fields.boolean('Cashdrawer', help="Automatically open the cashdrawer"),
68         'iface_payment_terminal' : fields.boolean('Payment Terminal', help="Enables Payment Terminal integration"),
69         'iface_electronic_scale' : fields.boolean('Electronic Scale', help="Enables Electronic Scale integration"),
70         'iface_vkeyboard' : fields.boolean('Virtual KeyBoard', help="Enables an integrated Virtual Keyboard"),
71         'iface_print_via_proxy' : fields.boolean('Print via Proxy', help="Bypass browser printing and prints via the hardware proxy"),
72         'iface_scan_via_proxy' : fields.boolean('Scan via Proxy', help="Enable barcode scanning with a remotely connected barcode scanner"),
73         'iface_invoicing': fields.boolean('Invoicing',help='Enables invoice generation from the Point of Sale'),
74         'iface_big_scrollbars': fields.boolean('Large Scrollbars',help='For imprecise industrial touchscreens'),
75         'receipt_header': fields.text('Receipt Header',help="A short text that will be inserted as a header in the printed receipt"),
76         'receipt_footer': fields.text('Receipt Footer',help="A short text that will be inserted as a footer in the printed receipt"),
77         'proxy_ip':       fields.char('IP Address', help='The hostname or ip address of the hardware proxy, Will be autodetected if left empty', size=45),
78
79         'state' : fields.selection(POS_CONFIG_STATE, 'Status', required=True, readonly=True, copy=False),
80         'sequence_id' : fields.many2one('ir.sequence', 'Order IDs Sequence', readonly=True,
81             help="This sequence is automatically created by Odoo but you can change it "\
82                 "to customize the reference numbers of your orders.", copy=False),
83         'session_ids': fields.one2many('pos.session', 'config_id', 'Sessions'),
84         'group_by' : fields.boolean('Group Journal Items', help="Check this if you want to group the Journal Items by Product while closing a Session"),
85         'pricelist_id': fields.many2one('product.pricelist','Pricelist', required=True),
86         'company_id': fields.many2one('res.company', 'Company', required=True),
87         'barcode_product':  fields.char('Product Barcodes', size=64, help='The pattern that identifies product barcodes'),
88         'barcode_cashier':  fields.char('Cashier Barcodes', size=64, help='The pattern that identifies cashier login barcodes'),
89         'barcode_customer': fields.char('Customer Barcodes',size=64, help='The pattern that identifies customer\'s client card barcodes'),
90         'barcode_price':    fields.char('Price Barcodes',   size=64, help='The pattern that identifies a product with a barcode encoded price'),
91         'barcode_weight':   fields.char('Weight Barcodes',  size=64, help='The pattern that identifies a product with a barcode encoded weight'),
92         'barcode_discount': fields.char('Discount Barcodes',  size=64, help='The pattern that identifies a product with a barcode encoded discount'),
93     }
94
95     def _check_cash_control(self, cr, uid, ids, context=None):
96         return all(
97             (sum(int(journal.cash_control) for journal in record.journal_ids) <= 1)
98             for record in self.browse(cr, uid, ids, context=context)
99         )
100
101     _constraints = [
102         (_check_cash_control, "You cannot have two cash controls in one Point Of Sale !", ['journal_ids']),
103     ]
104
105     def name_get(self, cr, uid, ids, context=None):
106         result = []
107         states = {
108             'opening_control': _('Opening Control'),
109             'opened': _('In Progress'),
110             'closing_control': _('Closing Control'),
111             'closed': _('Closed & Posted'),
112         }
113         for record in self.browse(cr, uid, ids, context=context):
114             if (not record.session_ids) or (record.session_ids[0].state=='closed'):
115                 result.append((record.id, record.name+' ('+_('not used')+')'))
116                 continue
117             session = record.session_ids[0]
118             result.append((record.id, record.name + ' ('+session.user_id.name+')')) #, '+states[session.state]+')'))
119         return result
120
121     def _default_sale_journal(self, cr, uid, context=None):
122         company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
123         res = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'sale'), ('company_id', '=', company_id)], limit=1, context=context)
124         return res and res[0] or False
125
126     def _default_pricelist(self, cr, uid, context=None):
127         res = self.pool.get('product.pricelist').search(cr, uid, [('type', '=', 'sale')], limit=1, context=context)
128         return res and res[0] or False
129
130     def _get_default_location(self, cr, uid, context=None):
131         wh_obj = self.pool.get('stock.warehouse')
132         user = self.pool.get('res.users').browse(cr, uid, uid, context)
133         res = wh_obj.search(cr, uid, [('company_id', '=', user.company_id.id)], limit=1, context=context)
134         if res and res[0]:
135             return wh_obj.browse(cr, uid, res[0], context=context).lot_stock_id.id
136         return False
137
138     def _get_default_company(self, cr, uid, context=None):
139         company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
140         return company_id
141
142     _defaults = {
143         'state' : POS_CONFIG_STATE[0][0],
144         'journal_id': _default_sale_journal,
145         'group_by' : True,
146         'pricelist_id': _default_pricelist,
147         'iface_invoicing': True,
148         'stock_location_id': _get_default_location,
149         'company_id': _get_default_company,
150         'barcode_product': '*', 
151         'barcode_cashier': '041*', 
152         'barcode_customer':'042*', 
153         'barcode_weight':  '21xxxxxNNDDD', 
154         'barcode_discount':'22xxxxxxxxNN', 
155         'barcode_price':   '23xxxxxNNNDD', 
156     }
157
158     def onchange_picking_type_id(self, cr, uid, ids, picking_type_id, context=None):
159         p_type_obj = self.pool.get("stock.picking.type")
160         p_type = p_type_obj.browse(cr, uid, picking_type_id, context=context)
161         if p_type.default_location_src_id and p_type.default_location_src_id.usage == 'internal' and p_type.default_location_dest_id and p_type.default_location_dest_id.usage == 'customer':
162             return {'value': {'stock_location_id': p_type.default_location_src_id.id}}
163         return False
164
165     def set_active(self, cr, uid, ids, context=None):
166         return self.write(cr, uid, ids, {'state' : 'active'}, context=context)
167
168     def set_inactive(self, cr, uid, ids, context=None):
169         return self.write(cr, uid, ids, {'state' : 'inactive'}, context=context)
170
171     def set_deprecate(self, cr, uid, ids, context=None):
172         return self.write(cr, uid, ids, {'state' : 'deprecated'}, context=context)
173
174     def create(self, cr, uid, values, context=None):
175         proxy = self.pool.get('ir.sequence')
176         sequence_values = dict(
177             name='PoS %s' % values['name'],
178             padding=5,
179             prefix="%s/"  % values['name'],
180         )
181         sequence_id = proxy.create(cr, uid, sequence_values, context=context)
182         values['sequence_id'] = sequence_id
183         return super(pos_config, self).create(cr, uid, values, context=context)
184
185     def unlink(self, cr, uid, ids, context=None):
186         for obj in self.browse(cr, uid, ids, context=context):
187             if obj.sequence_id:
188                 obj.sequence_id.unlink()
189         return super(pos_config, self).unlink(cr, uid, ids, context=context)
190
191 class pos_session(osv.osv):
192     _name = 'pos.session'
193     _order = 'id desc'
194
195     POS_SESSION_STATE = [
196         ('opening_control', 'Opening Control'),  # Signal open
197         ('opened', 'In Progress'),                    # Signal closing
198         ('closing_control', 'Closing Control'),  # Signal close
199         ('closed', 'Closed & Posted'),
200     ]
201
202     def _compute_cash_all(self, cr, uid, ids, fieldnames, args, context=None):
203         result = dict()
204
205         for record in self.browse(cr, uid, ids, context=context):
206             result[record.id] = {
207                 'cash_journal_id' : False,
208                 'cash_register_id' : False,
209                 'cash_control' : False,
210             }
211             for st in record.statement_ids:
212                 if st.journal_id.cash_control == True:
213                     result[record.id]['cash_control'] = True
214                     result[record.id]['cash_journal_id'] = st.journal_id.id
215                     result[record.id]['cash_register_id'] = st.id
216
217         return result
218
219     _columns = {
220         'config_id' : fields.many2one('pos.config', 'Point of Sale',
221                                       help="The physical point of sale you will use.",
222                                       required=True,
223                                       select=1,
224                                       domain="[('state', '=', 'active')]",
225                                      ),
226
227         'name' : fields.char('Session ID', required=True, readonly=True),
228         'user_id' : fields.many2one('res.users', 'Responsible',
229                                     required=True,
230                                     select=1,
231                                     readonly=True,
232                                     states={'opening_control' : [('readonly', False)]}
233                                    ),
234         'currency_id' : fields.related('config_id', 'currency_id', type="many2one", relation='res.currency', string="Currnecy"),
235         'start_at' : fields.datetime('Opening Date', readonly=True), 
236         'stop_at' : fields.datetime('Closing Date', readonly=True),
237
238         'state' : fields.selection(POS_SESSION_STATE, 'Status',
239                 required=True, readonly=True,
240                 select=1, copy=False),
241         
242         'sequence_number': fields.integer('Order Sequence Number', help='A sequence number that is incremented with each order'),
243         'login_number':  fields.integer('Login Sequence Number', help='A sequence number that is incremented each time a user resumes the pos session'),
244
245         'cash_control' : fields.function(_compute_cash_all,
246                                          multi='cash',
247                                          type='boolean', string='Has Cash Control'),
248         'cash_journal_id' : fields.function(_compute_cash_all,
249                                             multi='cash',
250                                             type='many2one', relation='account.journal',
251                                             string='Cash Journal', store=True),
252         'cash_register_id' : fields.function(_compute_cash_all,
253                                              multi='cash',
254                                              type='many2one', relation='account.bank.statement',
255                                              string='Cash Register', store=True),
256
257         'opening_details_ids' : fields.related('cash_register_id', 'opening_details_ids', 
258                 type='one2many', relation='account.cashbox.line',
259                 string='Opening Cash Control'),
260         'details_ids' : fields.related('cash_register_id', 'details_ids', 
261                 type='one2many', relation='account.cashbox.line',
262                 string='Cash Control'),
263
264         'cash_register_balance_end_real' : fields.related('cash_register_id', 'balance_end_real',
265                 type='float',
266                 digits_compute=dp.get_precision('Account'),
267                 string="Ending Balance",
268                 help="Total of closing cash control lines.",
269                 readonly=True),
270         'cash_register_balance_start' : fields.related('cash_register_id', 'balance_start',
271                 type='float',
272                 digits_compute=dp.get_precision('Account'),
273                 string="Starting Balance",
274                 help="Total of opening cash control lines.",
275                 readonly=True),
276         'cash_register_total_entry_encoding' : fields.related('cash_register_id', 'total_entry_encoding',
277                 string='Total Cash Transaction',
278                 readonly=True,
279                 help="Total of all paid sale orders"),
280         'cash_register_balance_end' : fields.related('cash_register_id', 'balance_end',
281                 type='float',
282                 digits_compute=dp.get_precision('Account'),
283                 string="Theoretical Closing Balance",
284                 help="Sum of opening balance and transactions.",
285                 readonly=True),
286         'cash_register_difference' : fields.related('cash_register_id', 'difference',
287                 type='float',
288                 string='Difference',
289                 help="Difference between the theoretical closing balance and the real closing balance.",
290                 readonly=True),
291
292         'journal_ids' : fields.related('config_id', 'journal_ids',
293                                        type='many2many',
294                                        readonly=True,
295                                        relation='account.journal',
296                                        string='Available Payment Methods'),
297         'order_ids' : fields.one2many('pos.order', 'session_id', 'Orders'),
298
299         'statement_ids' : fields.one2many('account.bank.statement', 'pos_session_id', 'Bank Statement', readonly=True),
300     }
301
302     _defaults = {
303         'name' : '/',
304         'user_id' : lambda obj, cr, uid, context: uid,
305         'state' : 'opening_control',
306         'sequence_number': 1,
307         'login_number': 0,
308     }
309
310     _sql_constraints = [
311         ('uniq_name', 'unique(name)', "The name of this POS Session must be unique !"),
312     ]
313
314     def _check_unicity(self, cr, uid, ids, context=None):
315         for session in self.browse(cr, uid, ids, context=None):
316             # open if there is no session in 'opening_control', 'opened', 'closing_control' for one user
317             domain = [
318                 ('state', 'not in', ('closed','closing_control')),
319                 ('user_id', '=', session.user_id.id)
320             ]
321             count = self.search_count(cr, uid, domain, context=context)
322             if count>1:
323                 return False
324         return True
325
326     def _check_pos_config(self, cr, uid, ids, context=None):
327         for session in self.browse(cr, uid, ids, context=None):
328             domain = [
329                 ('state', '!=', 'closed'),
330                 ('config_id', '=', session.config_id.id)
331             ]
332             count = self.search_count(cr, uid, domain, context=context)
333             if count>1:
334                 return False
335         return True
336
337     _constraints = [
338         (_check_unicity, "You cannot create two active sessions with the same responsible!", ['user_id', 'state']),
339         (_check_pos_config, "You cannot create two active sessions related to the same point of sale!", ['config_id']),
340     ]
341
342     def create(self, cr, uid, values, context=None):
343         context = dict(context or {})
344         config_id = values.get('config_id', False) or context.get('default_config_id', False)
345         if not config_id:
346             raise osv.except_osv( _('Error!'),
347                 _("You should assign a Point of Sale to your session."))
348
349         # journal_id is not required on the pos_config because it does not
350         # exists at the installation. If nothing is configured at the
351         # installation we do the minimal configuration. Impossible to do in
352         # the .xml files as the CoA is not yet installed.
353         jobj = self.pool.get('pos.config')
354         pos_config = jobj.browse(cr, uid, config_id, context=context)
355         context.update({'company_id': pos_config.company_id.id})
356         if not pos_config.journal_id:
357             jid = jobj.default_get(cr, uid, ['journal_id'], context=context)['journal_id']
358             if jid:
359                 jobj.write(cr, uid, [pos_config.id], {'journal_id': jid}, context=context)
360             else:
361                 raise osv.except_osv( _('error!'),
362                     _("Unable to open the session. You have to assign a sale journal to your point of sale."))
363
364         # define some cash journal if no payment method exists
365         if not pos_config.journal_ids:
366             journal_proxy = self.pool.get('account.journal')
367             cashids = journal_proxy.search(cr, uid, [('journal_user', '=', True), ('type','=','cash')], context=context)
368             if not cashids:
369                 cashids = journal_proxy.search(cr, uid, [('type', '=', 'cash')], context=context)
370                 if not cashids:
371                     cashids = journal_proxy.search(cr, uid, [('journal_user','=',True)], context=context)
372
373             jobj.write(cr, uid, [pos_config.id], {'journal_ids': [(6,0, cashids)]})
374
375
376         pos_config = jobj.browse(cr, uid, config_id, context=context)
377         bank_statement_ids = []
378         for journal in pos_config.journal_ids:
379             bank_values = {
380                 'journal_id' : journal.id,
381                 'user_id' : uid,
382                 'company_id' : pos_config.company_id.id
383             }
384             statement_id = self.pool.get('account.bank.statement').create(cr, uid, bank_values, context=context)
385             bank_statement_ids.append(statement_id)
386
387         values.update({
388             'name' : pos_config.sequence_id._next(),
389             'statement_ids' : [(6, 0, bank_statement_ids)],
390             'config_id': config_id
391         })
392
393         return super(pos_session, self).create(cr, uid, values, context=context)
394
395     def unlink(self, cr, uid, ids, context=None):
396         for obj in self.browse(cr, uid, ids, context=context):
397             for statement in obj.statement_ids:
398                 statement.unlink(context=context)
399         return super(pos_session, self).unlink(cr, uid, ids, context=context)
400
401     def open_cb(self, cr, uid, ids, context=None):
402         """
403         call the Point Of Sale interface and set the pos.session to 'opened' (in progress)
404         """
405         if context is None:
406             context = dict()
407
408         if isinstance(ids, (int, long)):
409             ids = [ids]
410
411         this_record = self.browse(cr, uid, ids[0], context=context)
412         this_record.signal_workflow('open')
413
414         context.update(active_id=this_record.id)
415
416         return {
417             'type' : 'ir.actions.act_url',
418             'url'  : '/pos/web/',
419             'target': 'self',
420         }
421
422     def login(self, cr, uid, ids, context=None):
423         this_record = self.browse(cr, uid, ids[0], context=context)
424         this_record.write({
425             'login_number': this_record.login_number+1,
426         })
427
428     def wkf_action_open(self, cr, uid, ids, context=None):
429         # second browse because we need to refetch the data from the DB for cash_register_id
430         for record in self.browse(cr, uid, ids, context=context):
431             values = {}
432             if not record.start_at:
433                 values['start_at'] = time.strftime('%Y-%m-%d %H:%M:%S')
434             values['state'] = 'opened'
435             record.write(values)
436             for st in record.statement_ids:
437                 st.button_open()
438
439         return self.open_frontend_cb(cr, uid, ids, context=context)
440
441     def wkf_action_opening_control(self, cr, uid, ids, context=None):
442         return self.write(cr, uid, ids, {'state' : 'opening_control'}, context=context)
443
444     def wkf_action_closing_control(self, cr, uid, ids, context=None):
445         for session in self.browse(cr, uid, ids, context=context):
446             for statement in session.statement_ids:
447                 if (statement != session.cash_register_id) and (statement.balance_end != statement.balance_end_real):
448                     self.pool.get('account.bank.statement').write(cr, uid, [statement.id], {'balance_end_real': statement.balance_end})
449         return self.write(cr, uid, ids, {'state' : 'closing_control', 'stop_at' : time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
450
451     def wkf_action_close(self, cr, uid, ids, context=None):
452         # Close CashBox
453         bsl = self.pool.get('account.bank.statement.line')
454         for record in self.browse(cr, uid, ids, context=context):
455             for st in record.statement_ids:
456                 if abs(st.difference) > st.journal_id.amount_authorized_diff:
457                     # The pos manager can close statements with maximums.
458                     if not self.pool.get('ir.model.access').check_groups(cr, uid, "point_of_sale.group_pos_manager"):
459                         raise osv.except_osv( _('Error!'),
460                             _("Your ending balance is too different from the theoretical cash closing (%.2f), the maximum allowed is: %.2f. You can contact your manager to force it.") % (st.difference, st.journal_id.amount_authorized_diff))
461                 if (st.journal_id.type not in ['bank', 'cash']):
462                     raise osv.except_osv(_('Error!'), 
463                         _("The type of the journal for your payment method should be bank or cash "))
464                 if st.difference and st.journal_id.cash_control == True:
465                     if st.difference > 0.0:
466                         name= _('Point of Sale Profit')
467                     else:
468                         name= _('Point of Sale Loss')
469                     bsl.create(cr, uid, {
470                         'statement_id': st.id,
471                         'amount': st.difference,
472                         'ref': record.name,
473                         'name': name,
474                         'journal_id': st.journal_id.id,
475                     }, context=context)
476
477                 st.write({'balance_end_real': st.balance_end}) # will update balances for cash statements
478                 getattr(st, 'button_confirm_%s' % st.journal_id.type)(context=context)
479         self._confirm_orders(cr, uid, ids, context=context)
480         self.write(cr, uid, ids, {'state' : 'closed'}, context=context)
481
482         obj = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'point_of_sale', 'menu_point_root')[1]
483         return {
484             'type' : 'ir.actions.client',
485             'name' : 'Point of Sale Menu',
486             'tag' : 'reload',
487             'params' : {'menu_id': obj},
488         }
489
490     def _confirm_orders(self, cr, uid, ids, context=None):
491         account_move_obj = self.pool.get('account.move')
492         pos_order_obj = self.pool.get('pos.order')
493         for session in self.browse(cr, uid, ids, context=context):
494             local_context = dict(context or {}, force_company=session.config_id.journal_id.company_id.id)
495             order_ids = [order.id for order in session.order_ids if order.state == 'paid']
496
497             move_id = account_move_obj.create(cr, uid, {'ref' : session.name, 'journal_id' : session.config_id.journal_id.id, }, context=local_context)
498
499             pos_order_obj._create_account_move_line(cr, uid, order_ids, session, move_id, context=local_context)
500
501             for order in session.order_ids:
502                 if order.state == 'done':
503                     continue
504                 if order.state not in ('paid', 'invoiced'):
505                     raise osv.except_osv(
506                         _('Error!'),
507                         _("You cannot confirm all orders of this session, because they have not the 'paid' status"))
508                 else:
509                     pos_order_obj.signal_workflow(cr, uid, [order.id], 'done')
510
511         return True
512
513     def open_frontend_cb(self, cr, uid, ids, context=None):
514         if not context:
515             context = {}
516         if not ids:
517             return {}
518         for session in self.browse(cr, uid, ids, context=context):
519             if session.user_id.id != uid:
520                 raise osv.except_osv(
521                         _('Error!'),
522                         _("You cannot use the session of another users. This session is owned by %s. Please first close this one to use this point of sale." % session.user_id.name))
523         context.update({'active_id': ids[0]})
524         return {
525             'type' : 'ir.actions.act_url',
526             'target': 'self',
527             'url':   '/pos/web/',
528         }
529
530 class pos_order(osv.osv):
531     _name = "pos.order"
532     _description = "Point of Sale"
533     _order = "id desc"
534
535     def _order_fields(self, cr, uid, ui_order, context=None):
536         return {
537             'name':         ui_order['name'],
538             'user_id':      ui_order['user_id'] or False,
539             'session_id':   ui_order['pos_session_id'],
540             'lines':        ui_order['lines'],
541             'pos_reference':ui_order['name'],
542             'partner_id':   ui_order['partner_id'] or False,
543         }
544
545     def _payment_fields(self, cr, uid, ui_paymentline, context=None):
546         return {
547             'amount':       ui_paymentline['amount'] or 0.0,
548             'payment_date': ui_paymentline['name'],
549             'statement_id': ui_paymentline['statement_id'],
550             'payment_name': ui_paymentline.get('note',False),
551             'journal':      ui_paymentline['journal_id'],
552         }
553
554     def create_from_ui(self, cr, uid, orders, context=None):
555         # Keep only new orders
556         submitted_references = [o['data']['name'] for o in orders]
557         existing_order_ids = self.search(cr, uid, [('pos_reference', 'in', submitted_references)], context=context)
558         existing_orders = self.read(cr, uid, existing_order_ids, ['pos_reference'], context=context)
559         existing_references = set([o['pos_reference'] for o in existing_orders])
560         orders_to_save = [o for o in orders if o['data']['name'] not in existing_references]
561
562         order_ids = []
563
564         for tmp_order in orders_to_save:
565             to_invoice = tmp_order['to_invoice']
566             order = tmp_order['data']
567             order_id = self.create(cr, uid, self._order_fields(cr, uid, order, context=context),context)
568
569             for payments in order['statement_ids']:
570                 self.add_payment(cr, uid, order_id, self._payment_fields(cr, uid, payments[2], context=context), context=context)
571
572             session = self.pool.get('pos.session').browse(cr, uid, order['pos_session_id'], context=context)
573             if session.sequence_number <= order['sequence_number']:
574                 session.write({'sequence_number': order['sequence_number'] + 1})
575                 session.refresh()
576
577             if order['amount_return']:
578                 cash_journal = session.cash_journal_id
579                 if not cash_journal:
580                     cash_journal_ids = filter(lambda st: st.journal_id.type=='cash', session.statement_ids)
581                     if not len(cash_journal_ids):
582                         raise osv.except_osv( _('error!'),
583                             _("No cash statement found for this session. Unable to record returned cash."))
584                     cash_journal = cash_journal_ids[0].journal_id
585                 self.add_payment(cr, uid, order_id, {
586                     'amount': -order['amount_return'],
587                     'payment_date': time.strftime('%Y-%m-%d %H:%M:%S'),
588                     'payment_name': _('return'),
589                     'journal': cash_journal.id,
590                 }, context=context)
591             order_ids.append(order_id)
592
593             try:
594                 self.signal_workflow(cr, uid, [order_id], 'paid')
595             except Exception as e:
596                 _logger.error('Could not fully process the POS Order: %s', tools.ustr(e))
597
598             if to_invoice:
599                 self.action_invoice(cr, uid, [order_id], context)
600                 order_obj = self.browse(cr, uid, order_id, context)
601                 self.pool['account.invoice'].signal_workflow(cr, uid, [order_obj.invoice_id.id], 'invoice_open')
602
603         return order_ids
604
605     def write(self, cr, uid, ids, vals, context=None):
606         res = super(pos_order, self).write(cr, uid, ids, vals, context=context)
607         #If you change the partner of the PoS order, change also the partner of the associated bank statement lines
608         partner_obj = self.pool.get('res.partner')
609         bsl_obj = self.pool.get("account.bank.statement.line")
610         if 'partner_id' in vals:
611             for posorder in self.browse(cr, uid, ids, context=context):
612                 if posorder.invoice_id:
613                     raise osv.except_osv( _('Error!'), _("You cannot change the partner of a POS order for which an invoice has already been issued."))
614                 if vals['partner_id']:
615                     p_id = partner_obj.browse(cr, uid, vals['partner_id'], context=context)
616                     part_id = partner_obj._find_accounting_partner(p_id).id
617                 else:
618                     part_id = False
619                 bsl_ids = [x.id for x in posorder.statement_ids]
620                 bsl_obj.write(cr, uid, bsl_ids, {'partner_id': part_id}, context=context)
621         return res
622
623     def unlink(self, cr, uid, ids, context=None):
624         for rec in self.browse(cr, uid, ids, context=context):
625             if rec.state not in ('draft','cancel'):
626                 raise osv.except_osv(_('Unable to Delete!'), _('In order to delete a sale, it must be new or cancelled.'))
627         return super(pos_order, self).unlink(cr, uid, ids, context=context)
628
629     def onchange_partner_id(self, cr, uid, ids, part=False, context=None):
630         if not part:
631             return {'value': {}}
632         pricelist = self.pool.get('res.partner').browse(cr, uid, part, context=context).property_product_pricelist.id
633         return {'value': {'pricelist_id': pricelist}}
634
635     def _amount_all(self, cr, uid, ids, name, args, context=None):
636         cur_obj = self.pool.get('res.currency')
637         res = {}
638         for order in self.browse(cr, uid, ids, context=context):
639             res[order.id] = {
640                 'amount_paid': 0.0,
641                 'amount_return':0.0,
642                 'amount_tax':0.0,
643             }
644             val1 = val2 = 0.0
645             cur = order.pricelist_id.currency_id
646             for payment in order.statement_ids:
647                 res[order.id]['amount_paid'] +=  payment.amount
648                 res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0)
649             for line in order.lines:
650                 val1 += line.price_subtotal_incl
651                 val2 += line.price_subtotal
652             res[order.id]['amount_tax'] = cur_obj.round(cr, uid, cur, val1-val2)
653             res[order.id]['amount_total'] = cur_obj.round(cr, uid, cur, val1)
654         return res
655
656     _columns = {
657         'name': fields.char('Order Ref', required=True, readonly=True, copy=False),
658         'company_id':fields.many2one('res.company', 'Company', required=True, readonly=True),
659         'date_order': fields.datetime('Order Date', readonly=True, select=True),
660         'user_id': fields.many2one('res.users', 'Salesman', help="Person who uses the the cash register. It can be a reliever, a student or an interim employee."),
661         'amount_tax': fields.function(_amount_all, string='Taxes', digits_compute=dp.get_precision('Account'), multi='all'),
662         'amount_total': fields.function(_amount_all, string='Total', multi='all'),
663         'amount_paid': fields.function(_amount_all, string='Paid', states={'draft': [('readonly', False)]}, readonly=True, digits_compute=dp.get_precision('Account'), multi='all'),
664         'amount_return': fields.function(_amount_all, 'Returned', digits_compute=dp.get_precision('Account'), multi='all'),
665         'lines': fields.one2many('pos.order.line', 'order_id', 'Order Lines', states={'draft': [('readonly', False)]}, readonly=True, copy=True),
666         'statement_ids': fields.one2many('account.bank.statement.line', 'pos_statement_id', 'Payments', states={'draft': [('readonly', False)]}, readonly=True),
667         'pricelist_id': fields.many2one('product.pricelist', 'Pricelist', required=True, states={'draft': [('readonly', False)]}, readonly=True),
668         'partner_id': fields.many2one('res.partner', 'Customer', change_default=True, select=1, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]}),
669         'sequence_number': fields.integer('Sequence Number', help='A session-unique sequence number for the order'),
670
671         'session_id' : fields.many2one('pos.session', 'Session', 
672                                         #required=True,
673                                         select=1,
674                                         domain="[('state', '=', 'opened')]",
675                                         states={'draft' : [('readonly', False)]},
676                                         readonly=True),
677
678         'state': fields.selection([('draft', 'New'),
679                                    ('cancel', 'Cancelled'),
680                                    ('paid', 'Paid'),
681                                    ('done', 'Posted'),
682                                    ('invoiced', 'Invoiced')],
683                                   'Status', readonly=True, copy=False),
684
685         'invoice_id': fields.many2one('account.invoice', 'Invoice', copy=False),
686         'account_move': fields.many2one('account.move', 'Journal Entry', readonly=True, copy=False),
687         'picking_id': fields.many2one('stock.picking', 'Picking', readonly=True, copy=False),
688         'picking_type_id': fields.related('session_id', 'config_id', 'picking_type_id', string="Picking Type", type='many2one', relation='stock.picking.type'),
689         'location_id': fields.related('session_id', 'config_id', 'stock_location_id', string="Location", type='many2one', store=True, relation='stock.location'),
690         'note': fields.text('Internal Notes'),
691         'nb_print': fields.integer('Number of Print', readonly=True, copy=False),
692         'pos_reference': fields.char('Receipt Ref', readonly=True, copy=False),
693         'sale_journal': fields.related('session_id', 'config_id', 'journal_id', relation='account.journal', type='many2one', string='Sale Journal', store=True, readonly=True),
694     }
695
696     def _default_session(self, cr, uid, context=None):
697         so = self.pool.get('pos.session')
698         session_ids = so.search(cr, uid, [('state','=', 'opened'), ('user_id','=',uid)], context=context)
699         return session_ids and session_ids[0] or False
700
701     def _default_pricelist(self, cr, uid, context=None):
702         session_ids = self._default_session(cr, uid, context) 
703         if session_ids:
704             session_record = self.pool.get('pos.session').browse(cr, uid, session_ids, context=context)
705             return session_record.config_id.pricelist_id and session_record.config_id.pricelist_id.id or False
706         return False
707
708     def _get_out_picking_type(self, cr, uid, context=None):
709         return self.pool.get('ir.model.data').xmlid_to_res_id(
710                     cr, uid, 'point_of_sale.picking_type_posout', context=context)
711
712     _defaults = {
713         'user_id': lambda self, cr, uid, context: uid,
714         'state': 'draft',
715         'name': '/', 
716         'date_order': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
717         'nb_print': 0,
718         'sequence_number': 1,
719         'session_id': _default_session,
720         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
721         'pricelist_id': _default_pricelist,
722     }
723
724     def create(self, cr, uid, values, context=None):
725         values['name'] = self.pool.get('ir.sequence').get(cr, uid, 'pos.order')
726         return super(pos_order, self).create(cr, uid, values, context=context)
727
728     def test_paid(self, cr, uid, ids, context=None):
729         """A Point of Sale is paid when the sum
730         @return: True
731         """
732         for order in self.browse(cr, uid, ids, context=context):
733             if order.lines and not order.amount_total:
734                 return True
735             if (not order.lines) or (not order.statement_ids) or \
736                 (abs(order.amount_total-order.amount_paid) > 0.00001):
737                 return False
738         return True
739
740     def create_picking(self, cr, uid, ids, context=None):
741         """Create a picking for each order and validate it."""
742         picking_obj = self.pool.get('stock.picking')
743         partner_obj = self.pool.get('res.partner')
744         move_obj = self.pool.get('stock.move')
745
746         for order in self.browse(cr, uid, ids, context=context):
747             addr = order.partner_id and partner_obj.address_get(cr, uid, [order.partner_id.id], ['delivery']) or {}
748             picking_type = order.picking_type_id
749             picking_id = False
750             if picking_type:
751                 picking_id = picking_obj.create(cr, uid, {
752                     'origin': order.name,
753                     'partner_id': addr.get('delivery',False),
754                     'picking_type_id': picking_type.id,
755                     'company_id': order.company_id.id,
756                     'move_type': 'direct',
757                     'note': order.note or "",
758                     'invoice_state': 'none',
759                 }, context=context)
760                 self.write(cr, uid, [order.id], {'picking_id': picking_id}, context=context)
761             location_id = order.location_id.id
762             if order.partner_id:
763                 destination_id = order.partner_id.property_stock_customer.id
764             elif picking_type:
765                 if not picking_type.default_location_dest_id:
766                     raise osv.except_osv(_('Error!'), _('Missing source or destination location for picking type %s. Please configure those fields and try again.' % (picking_type.name,)))
767                 destination_id = picking_type.default_location_dest_id.id
768             else:
769                 destination_id = partner_obj.default_get(cr, uid, ['property_stock_customer'], context=context)['property_stock_customer']
770
771             move_list = []
772             for line in order.lines:
773                 if line.product_id and line.product_id.type == 'service':
774                     continue
775
776                 move_list.append(move_obj.create(cr, uid, {
777                     'name': line.name,
778                     'product_uom': line.product_id.uom_id.id,
779                     'product_uos': line.product_id.uom_id.id,
780                     'picking_id': picking_id,
781                     'picking_type_id': picking_type.id, 
782                     'product_id': line.product_id.id,
783                     'product_uos_qty': abs(line.qty),
784                     'product_uom_qty': abs(line.qty),
785                     'state': 'draft',
786                     'location_id': location_id if line.qty >= 0 else destination_id,
787                     'location_dest_id': destination_id if line.qty >= 0 else location_id,
788                 }, context=context))
789                 
790             if picking_id:
791                 picking_obj.action_confirm(cr, uid, [picking_id], context=context)
792                 picking_obj.force_assign(cr, uid, [picking_id], context=context)
793                 picking_obj.action_done(cr, uid, [picking_id], context=context)
794             elif move_list:
795                 move_obj.action_confirm(cr, uid, move_list, context=context)
796                 move_obj.force_assign(cr, uid, move_list, context=context)
797                 move_obj.action_done(cr, uid, move_list, context=context)
798         return True
799
800     def cancel_order(self, cr, uid, ids, context=None):
801         """ Changes order state to cancel
802         @return: True
803         """
804         stock_picking_obj = self.pool.get('stock.picking')
805         for order in self.browse(cr, uid, ids, context=context):
806             stock_picking_obj.action_cancel(cr, uid, [order.picking_id.id])
807             if stock_picking_obj.browse(cr, uid, order.picking_id.id, context=context).state <> 'cancel':
808                 raise osv.except_osv(_('Error!'), _('Unable to cancel the picking.'))
809         self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
810         return True
811
812     def add_payment(self, cr, uid, order_id, data, context=None):
813         """Create a new payment for the order"""
814         context = dict(context or {})
815         statement_line_obj = self.pool.get('account.bank.statement.line')
816         property_obj = self.pool.get('ir.property')
817         order = self.browse(cr, uid, order_id, context=context)
818         args = {
819             'amount': data['amount'],
820             'date': data.get('payment_date', time.strftime('%Y-%m-%d')),
821             'name': order.name + ': ' + (data.get('payment_name', '') or ''),
822             'partner_id': order.partner_id and order.partner_id.id or None,
823         }
824         account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
825         args['account_id'] = (order.partner_id and order.partner_id.property_account_receivable \
826                              and order.partner_id.property_account_receivable.id) or (account_def and account_def.id) or False
827
828         if not args['account_id']:
829             if not args['partner_id']:
830                 msg = _('There is no receivable account defined to make payment.')
831             else:
832                 msg = _('There is no receivable account defined to make payment for the partner: "%s" (id:%d).') % (order.partner_id.name, order.partner_id.id,)
833             raise osv.except_osv(_('Configuration Error!'), msg)
834
835         context.pop('pos_session_id', False)
836
837         journal_id = data.get('journal', False)
838         statement_id = data.get('statement_id', False)
839         assert journal_id or statement_id, "No statement_id or journal_id passed to the method!"
840
841         for statement in order.session_id.statement_ids:
842             if statement.id == statement_id:
843                 journal_id = statement.journal_id.id
844                 break
845             elif statement.journal_id.id == journal_id:
846                 statement_id = statement.id
847                 break
848
849         if not statement_id:
850             raise osv.except_osv(_('Error!'), _('You have to open at least one cashbox.'))
851
852         args.update({
853             'statement_id': statement_id,
854             'pos_statement_id': order_id,
855             'journal_id': journal_id,
856             'ref': order.session_id.name,
857         })
858
859         statement_line_obj.create(cr, uid, args, context=context)
860
861         return statement_id
862
863     def refund(self, cr, uid, ids, context=None):
864         """Create a copy of order  for refund order"""
865         clone_list = []
866         line_obj = self.pool.get('pos.order.line')
867         
868         for order in self.browse(cr, uid, ids, context=context):
869             current_session_ids = self.pool.get('pos.session').search(cr, uid, [
870                 ('state', '!=', 'closed'),
871                 ('user_id', '=', uid)], context=context)
872             if not current_session_ids:
873                 raise osv.except_osv(_('Error!'), _('To return product(s), you need to open a session that will be used to register the refund.'))
874
875             clone_id = self.copy(cr, uid, order.id, {
876                 'name': order.name + ' REFUND', # not used, name forced by create
877                 'session_id': current_session_ids[0],
878                 'date_order': time.strftime('%Y-%m-%d %H:%M:%S'),
879             }, context=context)
880             clone_list.append(clone_id)
881
882         for clone in self.browse(cr, uid, clone_list, context=context):
883             for order_line in clone.lines:
884                 line_obj.write(cr, uid, [order_line.id], {
885                     'qty': -order_line.qty
886                 }, context=context)
887
888         abs = {
889             'name': _('Return Products'),
890             'view_type': 'form',
891             'view_mode': 'form',
892             'res_model': 'pos.order',
893             'res_id':clone_list[0],
894             'view_id': False,
895             'context':context,
896             'type': 'ir.actions.act_window',
897             'nodestroy': True,
898             'target': 'current',
899         }
900         return abs
901
902     def action_invoice_state(self, cr, uid, ids, context=None):
903         return self.write(cr, uid, ids, {'state':'invoiced'}, context=context)
904
905     def action_invoice(self, cr, uid, ids, context=None):
906         inv_ref = self.pool.get('account.invoice')
907         inv_line_ref = self.pool.get('account.invoice.line')
908         product_obj = self.pool.get('product.product')
909         inv_ids = []
910
911         for order in self.pool.get('pos.order').browse(cr, uid, ids, context=context):
912             if order.invoice_id:
913                 inv_ids.append(order.invoice_id.id)
914                 continue
915
916             if not order.partner_id:
917                 raise osv.except_osv(_('Error!'), _('Please provide a partner for the sale.'))
918
919             acc = order.partner_id.property_account_receivable.id
920             inv = {
921                 'name': order.name,
922                 'origin': order.name,
923                 'account_id': acc,
924                 'journal_id': order.sale_journal.id or None,
925                 'type': 'out_invoice',
926                 'reference': order.name,
927                 'partner_id': order.partner_id.id,
928                 'comment': order.note or '',
929                 'currency_id': order.pricelist_id.currency_id.id, # considering partner's sale pricelist's currency
930             }
931             inv.update(inv_ref.onchange_partner_id(cr, uid, [], 'out_invoice', order.partner_id.id)['value'])
932             if not inv.get('account_id', None):
933                 inv['account_id'] = acc
934             inv_id = inv_ref.create(cr, uid, inv, context=context)
935
936             self.write(cr, uid, [order.id], {'invoice_id': inv_id, 'state': 'invoiced'}, context=context)
937             inv_ids.append(inv_id)
938             for line in order.lines:
939                 inv_line = {
940                     'invoice_id': inv_id,
941                     'product_id': line.product_id.id,
942                     'quantity': line.qty,
943                 }
944                 inv_name = product_obj.name_get(cr, uid, [line.product_id.id], context=context)[0][1]
945                 inv_line.update(inv_line_ref.product_id_change(cr, uid, [],
946                                                                line.product_id.id,
947                                                                line.product_id.uom_id.id,
948                                                                line.qty, partner_id = order.partner_id.id,
949                                                                fposition_id=order.partner_id.property_account_position.id)['value'])
950                 inv_line['price_unit'] = line.price_unit
951                 inv_line['discount'] = line.discount
952                 inv_line['name'] = inv_name
953                 inv_line['invoice_line_tax_id'] = [(6, 0, [x.id for x in line.product_id.taxes_id] )]
954                 inv_line_ref.create(cr, uid, inv_line, context=context)
955             inv_ref.button_reset_taxes(cr, uid, [inv_id], context=context)
956             self.signal_workflow(cr, uid, [order.id], 'invoice')
957             inv_ref.signal_workflow(cr, uid, [inv_id], 'validate')
958
959         if not inv_ids: return {}
960
961         mod_obj = self.pool.get('ir.model.data')
962         res = mod_obj.get_object_reference(cr, uid, 'account', 'invoice_form')
963         res_id = res and res[1] or False
964         return {
965             'name': _('Customer Invoice'),
966             'view_type': 'form',
967             'view_mode': 'form',
968             'view_id': [res_id],
969             'res_model': 'account.invoice',
970             'context': "{'type':'out_invoice'}",
971             'type': 'ir.actions.act_window',
972             'nodestroy': True,
973             'target': 'current',
974             'res_id': inv_ids and inv_ids[0] or False,
975         }
976
977     def create_account_move(self, cr, uid, ids, context=None):
978         return self._create_account_move_line(cr, uid, ids, None, None, context=context)
979
980     def _create_account_move_line(self, cr, uid, ids, session=None, move_id=None, context=None):
981         # Tricky, via the workflow, we only have one id in the ids variable
982         """Create a account move line of order grouped by products or not."""
983         account_move_obj = self.pool.get('account.move')
984         account_period_obj = self.pool.get('account.period')
985         account_tax_obj = self.pool.get('account.tax')
986         property_obj = self.pool.get('ir.property')
987         cur_obj = self.pool.get('res.currency')
988
989         #session_ids = set(order.session_id for order in self.browse(cr, uid, ids, context=context))
990
991         if session and not all(session.id == order.session_id.id for order in self.browse(cr, uid, ids, context=context)):
992             raise osv.except_osv(_('Error!'), _('Selected orders do not have the same session!'))
993
994         grouped_data = {}
995         have_to_group_by = session and session.config_id.group_by or False
996
997         def compute_tax(amount, tax, line):
998             if amount > 0:
999                 tax_code_id = tax['base_code_id']
1000                 tax_amount = line.price_subtotal * tax['base_sign']
1001             else:
1002                 tax_code_id = tax['ref_base_code_id']
1003                 tax_amount = line.price_subtotal * tax['ref_base_sign']
1004
1005             return (tax_code_id, tax_amount,)
1006
1007         for order in self.browse(cr, uid, ids, context=context):
1008             if order.account_move:
1009                 continue
1010             if order.state != 'paid':
1011                 continue
1012
1013             current_company = order.sale_journal.company_id
1014
1015             group_tax = {}
1016             account_def = property_obj.get(cr, uid, 'property_account_receivable', 'res.partner', context=context)
1017
1018             order_account = order.partner_id and \
1019                             order.partner_id.property_account_receivable and \
1020                             order.partner_id.property_account_receivable.id or \
1021                             account_def and account_def.id or current_company.account_receivable.id
1022
1023             if move_id is None:
1024                 # Create an entry for the sale
1025                 move_id = account_move_obj.create(cr, uid, {
1026                     'ref' : order.name,
1027                     'journal_id': order.sale_journal.id,
1028                 }, context=context)
1029
1030             def insert_data(data_type, values):
1031                 # if have_to_group_by:
1032
1033                 sale_journal_id = order.sale_journal.id
1034                 period = account_period_obj.find(cr, uid, context=dict(context or {}, company_id=current_company.id))[0]
1035
1036                 # 'quantity': line.qty,
1037                 # 'product_id': line.product_id.id,
1038                 values.update({
1039                     'date': order.date_order[:10],
1040                     'ref': order.name,
1041                     'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False,
1042                     'journal_id' : sale_journal_id,
1043                     'period_id' : period,
1044                     'move_id' : move_id,
1045                     'company_id': current_company.id,
1046                 })
1047
1048                 if data_type == 'product':
1049                     key = ('product', values['partner_id'], values['product_id'], values['debit'] > 0)
1050                 elif data_type == 'tax':
1051                     key = ('tax', values['partner_id'], values['tax_code_id'], values['debit'] > 0)
1052                 elif data_type == 'counter_part':
1053                     key = ('counter_part', values['partner_id'], values['account_id'], values['debit'] > 0)
1054                 else:
1055                     return
1056
1057                 grouped_data.setdefault(key, [])
1058
1059                 # if not have_to_group_by or (not grouped_data[key]):
1060                 #     grouped_data[key].append(values)
1061                 # else:
1062                 #     pass
1063
1064                 if have_to_group_by:
1065                     if not grouped_data[key]:
1066                         grouped_data[key].append(values)
1067                     else:
1068                         current_value = grouped_data[key][0]
1069                         current_value['quantity'] = current_value.get('quantity', 0.0) +  values.get('quantity', 0.0)
1070                         current_value['credit'] = current_value.get('credit', 0.0) + values.get('credit', 0.0)
1071                         current_value['debit'] = current_value.get('debit', 0.0) + values.get('debit', 0.0)
1072                         current_value['tax_amount'] = current_value.get('tax_amount', 0.0) + values.get('tax_amount', 0.0)
1073                 else:
1074                     grouped_data[key].append(values)
1075
1076             #because of the weird way the pos order is written, we need to make sure there is at least one line, 
1077             #because just after the 'for' loop there are references to 'line' and 'income_account' variables (that 
1078             #are set inside the for loop)
1079             #TOFIX: a deep refactoring of this method (and class!) is needed in order to get rid of this stupid hack
1080             assert order.lines, _('The POS order must have lines when calling this method')
1081             # Create an move for each order line
1082
1083             cur = order.pricelist_id.currency_id
1084             for line in order.lines:
1085                 tax_amount = 0
1086                 taxes = []
1087                 for t in line.product_id.taxes_id:
1088                     if t.company_id.id == current_company.id:
1089                         taxes.append(t)
1090                 computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit * (100.0-line.discount) / 100.0, line.qty)['taxes']
1091
1092                 for tax in computed_taxes:
1093                     tax_amount += cur_obj.round(cr, uid, cur, tax['amount'])
1094                     group_key = (tax['tax_code_id'], tax['base_code_id'], tax['account_collected_id'], tax['id'])
1095
1096                     group_tax.setdefault(group_key, 0)
1097                     group_tax[group_key] += cur_obj.round(cr, uid, cur, tax['amount'])
1098
1099                 amount = line.price_subtotal
1100
1101                 # Search for the income account
1102                 if  line.product_id.property_account_income.id:
1103                     income_account = line.product_id.property_account_income.id
1104                 elif line.product_id.categ_id.property_account_income_categ.id:
1105                     income_account = line.product_id.categ_id.property_account_income_categ.id
1106                 else:
1107                     raise osv.except_osv(_('Error!'), _('Please define income '\
1108                         'account for this product: "%s" (id:%d).') \
1109                         % (line.product_id.name, line.product_id.id, ))
1110
1111                 # Empty the tax list as long as there is no tax code:
1112                 tax_code_id = False
1113                 tax_amount = 0
1114                 while computed_taxes:
1115                     tax = computed_taxes.pop(0)
1116                     tax_code_id, tax_amount = compute_tax(amount, tax, line)
1117
1118                     # If there is one we stop
1119                     if tax_code_id:
1120                         break
1121
1122                 # Create a move for the line
1123                 insert_data('product', {
1124                     'name': line.product_id.name,
1125                     'quantity': line.qty,
1126                     'product_id': line.product_id.id,
1127                     'account_id': income_account,
1128                     'credit': ((amount>0) and amount) or 0.0,
1129                     'debit': ((amount<0) and -amount) or 0.0,
1130                     'tax_code_id': tax_code_id,
1131                     'tax_amount': tax_amount,
1132                     'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False
1133                 })
1134
1135                 # For each remaining tax with a code, whe create a move line
1136                 for tax in computed_taxes:
1137                     tax_code_id, tax_amount = compute_tax(amount, tax, line)
1138                     if not tax_code_id:
1139                         continue
1140
1141                     insert_data('tax', {
1142                         'name': _('Tax'),
1143                         'product_id':line.product_id.id,
1144                         'quantity': line.qty,
1145                         'account_id': income_account,
1146                         'credit': 0.0,
1147                         'debit': 0.0,
1148                         'tax_code_id': tax_code_id,
1149                         'tax_amount': tax_amount,
1150                         'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False
1151                     })
1152
1153             # Create a move for each tax group
1154             (tax_code_pos, base_code_pos, account_pos, tax_id)= (0, 1, 2, 3)
1155
1156             for key, tax_amount in group_tax.items():
1157                 tax = self.pool.get('account.tax').browse(cr, uid, key[tax_id], context=context)
1158                 insert_data('tax', {
1159                     'name': _('Tax') + ' ' + tax.name,
1160                     'quantity': line.qty,
1161                     'product_id': line.product_id.id,
1162                     'account_id': key[account_pos] or income_account,
1163                     'credit': ((tax_amount>0) and tax_amount) or 0.0,
1164                     'debit': ((tax_amount<0) and -tax_amount) or 0.0,
1165                     'tax_code_id': key[tax_code_pos],
1166                     'tax_amount': tax_amount,
1167                     'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False
1168                 })
1169
1170             # counterpart
1171             insert_data('counter_part', {
1172                 'name': _("Trade Receivables"), #order.name,
1173                 'account_id': order_account,
1174                 'credit': ((order.amount_total < 0) and -order.amount_total) or 0.0,
1175                 'debit': ((order.amount_total > 0) and order.amount_total) or 0.0,
1176                 'partner_id': order.partner_id and self.pool.get("res.partner")._find_accounting_partner(order.partner_id).id or False
1177             })
1178
1179             order.write({'state':'done', 'account_move': move_id})
1180
1181         all_lines = []
1182         for group_key, group_data in grouped_data.iteritems():
1183             for value in group_data:
1184                 all_lines.append((0, 0, value),)
1185         if move_id: #In case no order was changed
1186             self.pool.get("account.move").write(cr, uid, [move_id], {'line_id':all_lines}, context=context)
1187
1188         return True
1189
1190     def action_payment(self, cr, uid, ids, context=None):
1191         return self.write(cr, uid, ids, {'state': 'payment'}, context=context)
1192
1193     def action_paid(self, cr, uid, ids, context=None):
1194         self.write(cr, uid, ids, {'state': 'paid'}, context=context)
1195         self.create_picking(cr, uid, ids, context=context)
1196         return True
1197
1198     def action_cancel(self, cr, uid, ids, context=None):
1199         self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
1200         return True
1201
1202     def action_done(self, cr, uid, ids, context=None):
1203         self.create_account_move(cr, uid, ids, context=context)
1204         return True
1205
1206 class account_bank_statement(osv.osv):
1207     _inherit = 'account.bank.statement'
1208     _columns= {
1209         'user_id': fields.many2one('res.users', 'User', readonly=True),
1210     }
1211     _defaults = {
1212         'user_id': lambda self,cr,uid,c={}: uid
1213     }
1214
1215 class account_bank_statement_line(osv.osv):
1216     _inherit = 'account.bank.statement.line'
1217     _columns= {
1218         'pos_statement_id': fields.many2one('pos.order', ondelete='cascade'),
1219     }
1220
1221
1222 class pos_order_line(osv.osv):
1223     _name = "pos.order.line"
1224     _description = "Lines of Point of Sale"
1225     _rec_name = "product_id"
1226
1227     def _amount_line_all(self, cr, uid, ids, field_names, arg, context=None):
1228         res = dict([(i, {}) for i in ids])
1229         account_tax_obj = self.pool.get('account.tax')
1230         cur_obj = self.pool.get('res.currency')
1231         for line in self.browse(cr, uid, ids, context=context):
1232             taxes_ids = [ tax for tax in line.product_id.taxes_id if tax.company_id.id == line.order_id.company_id.id ]
1233             price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
1234             taxes = account_tax_obj.compute_all(cr, uid, taxes_ids, price, line.qty, product=line.product_id, partner=line.order_id.partner_id or False)
1235
1236             cur = line.order_id.pricelist_id.currency_id
1237             res[line.id]['price_subtotal'] = cur_obj.round(cr, uid, cur, taxes['total'])
1238             res[line.id]['price_subtotal_incl'] = cur_obj.round(cr, uid, cur, taxes['total_included'])
1239         return res
1240
1241     def onchange_product_id(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False, context=None):
1242        context = context or {}
1243        if not product_id:
1244             return {}
1245        if not pricelist:
1246            raise osv.except_osv(_('No Pricelist!'),
1247                _('You have to select a pricelist in the sale form !\n' \
1248                'Please set one before choosing a product.'))
1249
1250        price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist],
1251                product_id, qty or 1.0, partner_id)[pricelist]
1252
1253        result = self.onchange_qty(cr, uid, ids, product_id, 0.0, qty, price, context=context)
1254        result['value']['price_unit'] = price
1255        return result
1256
1257     def onchange_qty(self, cr, uid, ids, product, discount, qty, price_unit, context=None):
1258         result = {}
1259         if not product:
1260             return result
1261         account_tax_obj = self.pool.get('account.tax')
1262         cur_obj = self.pool.get('res.currency')
1263
1264         prod = self.pool.get('product.product').browse(cr, uid, product, context=context)
1265
1266         price = price_unit * (1 - (discount or 0.0) / 100.0)
1267         taxes = account_tax_obj.compute_all(cr, uid, prod.taxes_id, price, qty, product=prod, partner=False)
1268
1269         result['price_subtotal'] = taxes['total']
1270         result['price_subtotal_incl'] = taxes['total_included']
1271         return {'value': result}
1272
1273     _columns = {
1274         'company_id': fields.many2one('res.company', 'Company', required=True),
1275         'name': fields.char('Line No', required=True, copy=False),
1276         'notice': fields.char('Discount Notice'),
1277         'product_id': fields.many2one('product.product', 'Product', domain=[('sale_ok', '=', True)], required=True, change_default=True),
1278         'price_unit': fields.float(string='Unit Price', digits_compute=dp.get_precision('Account')),
1279         'qty': fields.float('Quantity', digits_compute=dp.get_precision('Product UoS')),
1280         'price_subtotal': fields.function(_amount_line_all, multi='pos_order_line_amount', string='Subtotal w/o Tax', store=True),
1281         'price_subtotal_incl': fields.function(_amount_line_all, multi='pos_order_line_amount', string='Subtotal', store=True),
1282         'discount': fields.float('Discount (%)', digits_compute=dp.get_precision('Account')),
1283         'order_id': fields.many2one('pos.order', 'Order Ref', ondelete='cascade'),
1284         'create_date': fields.datetime('Creation Date', readonly=True),
1285     }
1286
1287     _defaults = {
1288         'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'pos.order.line'),
1289         'qty': lambda *a: 1,
1290         'discount': lambda *a: 0.0,
1291         'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
1292     }
1293
1294 class ean_wizard(osv.osv_memory):
1295     _name = 'pos.ean_wizard'
1296     _columns = {
1297         'ean13_pattern': fields.char('Reference', size=13, required=True, translate=True),
1298     }
1299     def sanitize_ean13(self, cr, uid, ids, context):
1300         for r in self.browse(cr,uid,ids):
1301             ean13 = openerp.addons.product.product.sanitize_ean13(r.ean13_pattern)
1302             m = context.get('active_model')
1303             m_id =  context.get('active_id')
1304             self.pool[m].write(cr,uid,[m_id],{'ean13':ean13})
1305         return { 'type' : 'ir.actions.act_window_close' }
1306
1307 class pos_category(osv.osv):
1308     _name = "pos.category"
1309     _description = "Public Category"
1310     _order = "sequence, name"
1311
1312     _constraints = [
1313         (osv.osv._check_recursion, 'Error ! You cannot create recursive categories.', ['parent_id'])
1314     ]
1315
1316     def name_get(self, cr, uid, ids, context=None):
1317         if not len(ids):
1318             return []
1319         reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
1320         res = []
1321         for record in reads:
1322             name = record['name']
1323             if record['parent_id']:
1324                 name = record['parent_id'][1]+' / '+name
1325             res.append((record['id'], name))
1326         return res
1327
1328     def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
1329         res = self.name_get(cr, uid, ids, context=context)
1330         return dict(res)
1331
1332     def _get_image(self, cr, uid, ids, name, args, context=None):
1333         result = dict.fromkeys(ids, False)
1334         for obj in self.browse(cr, uid, ids, context=context):
1335             result[obj.id] = tools.image_get_resized_images(obj.image)
1336         return result
1337     
1338     def _set_image(self, cr, uid, id, name, value, args, context=None):
1339         return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
1340
1341     _columns = {
1342         'name': fields.char('Name', required=True, translate=True),
1343         'complete_name': fields.function(_name_get_fnc, type="char", string='Name'),
1344         'parent_id': fields.many2one('pos.category','Parent Category', select=True),
1345         'child_id': fields.one2many('pos.category', 'parent_id', string='Children Categories'),
1346         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of product categories."),
1347         
1348         # NOTE: there is no 'default image', because by default we don't show thumbnails for categories. However if we have a thumbnail
1349         # for at least one category, then we display a default image on the other, so that the buttons have consistent styling.
1350         # In this case, the default image is set by the js code.
1351         # NOTE2: image: all image fields are base64 encoded and PIL-supported
1352         'image': fields.binary("Image",
1353             help="This field holds the image used as image for the cateogry, limited to 1024x1024px."),
1354         'image_medium': fields.function(_get_image, fnct_inv=_set_image,
1355             string="Medium-sized image", type="binary", multi="_get_image",
1356             store={
1357                 'pos.category': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
1358             },
1359             help="Medium-sized image of the category. It is automatically "\
1360                  "resized as a 128x128px image, with aspect ratio preserved. "\
1361                  "Use this field in form views or some kanban views."),
1362         'image_small': fields.function(_get_image, fnct_inv=_set_image,
1363             string="Smal-sized image", type="binary", multi="_get_image",
1364             store={
1365                 'pos.category': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
1366             },
1367             help="Small-sized image of the category. It is automatically "\
1368                  "resized as a 64x64px image, with aspect ratio preserved. "\
1369                  "Use this field anywhere a small image is required."),
1370     }
1371
1372 class product_template(osv.osv):
1373     _inherit = 'product.template'
1374
1375     _columns = {
1376         'income_pdt': fields.boolean('Point of Sale Cash In', help="Check if, this is a product you can use to put cash into a statement for the point of sale backend."),
1377         'expense_pdt': fields.boolean('Point of Sale Cash Out', help="Check if, this is a product you can use to take cash from a statement for the point of sale backend, example: money lost, transfer to bank, etc."),
1378         'available_in_pos': fields.boolean('Available in the Point of Sale', help='Check if you want this product to appear in the Point of Sale'), 
1379         'to_weight' : fields.boolean('To Weigh With Scale', help="Check if the product should be weighted using the hardware scale integration"),
1380         'pos_categ_id': fields.many2one('pos.category','Point of Sale Category', help="Those categories are used to group similar products for point of sale."),
1381     }
1382
1383     _defaults = {
1384         'to_weight' : False,
1385         'available_in_pos': True,
1386     }
1387
1388 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: