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