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