[FIX] difference POS / Cash
[odoo/odoo.git] / addons / account / account_cash_statement.py
1 # encoding: utf-8
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2008 PC Solutions (<http://pcsol.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 import time
24
25 from openerp.osv import fields, osv
26 from openerp.tools.translate import _
27 import openerp.addons.decimal_precision as dp
28
29 class account_cashbox_line(osv.osv):
30
31     """ Cash Box Details """
32
33     _name = 'account.cashbox.line'
34     _description = 'CashBox Line'
35     _rec_name = 'pieces'
36
37     def _sub_total(self, cr, uid, ids, name, arg, context=None):
38
39         """ Calculates Sub total
40         @param name: Names of fields.
41         @param arg: User defined arguments
42         @return: Dictionary of values.
43         """
44         res = {}
45         for obj in self.browse(cr, uid, ids, context=context):
46             res[obj.id] = {
47                 'subtotal_opening' : obj.pieces * obj.number_opening,
48                 'subtotal_closing' : obj.pieces * obj.number_closing,
49             }
50         return res
51
52     def on_change_sub_opening(self, cr, uid, ids, pieces, number, *a):
53         """ Compute the subtotal for the opening """
54         return {'value' : {'subtotal_opening' : (pieces * number) or 0.0 }}
55
56     def on_change_sub_closing(self, cr, uid, ids, pieces, number, *a):
57         """ Compute the subtotal for the closing """
58         return {'value' : {'subtotal_closing' : (pieces * number) or 0.0 }}
59
60     _columns = {
61         'pieces': fields.float('Unit of Currency', digits_compute=dp.get_precision('Account')),
62         'number_opening' : fields.integer('Number of Units', help='Opening Unit Numbers'),
63         'number_closing' : fields.integer('Number of Units', help='Closing Unit Numbers'),
64         'subtotal_opening': fields.function(_sub_total, string='Opening Subtotal', type='float', digits_compute=dp.get_precision('Account'), multi='subtotal'),
65         'subtotal_closing': fields.function(_sub_total, string='Closing Subtotal', type='float', digits_compute=dp.get_precision('Account'), multi='subtotal'),
66         'bank_statement_id' : fields.many2one('account.bank.statement', ondelete='cascade'),
67      }
68
69
70 class account_cash_statement(osv.osv):
71
72     _inherit = 'account.bank.statement'
73
74     def _update_balances(self, cr, uid, ids, context=None):
75         """
76             Set starting and ending balances according to pieces count
77         """
78         res = {}
79         for statement in self.browse(cr, uid, ids, context=context):
80             if (statement.journal_id.type not in ('cash',)):
81                 continue
82             if not statement.journal_id.cash_control:
83                 if statement.balance_end_real <> statement.balance_end:
84                     statement.write({'balance_end_real' : statement.balance_end})
85                 continue
86             start = end = 0
87             for line in statement.details_ids:
88                 start += line.subtotal_opening
89                 end += line.subtotal_closing
90             data = {
91                 'balance_start': start,
92                 'balance_end_real': end,
93             }
94             res[statement.id] = data
95             super(account_cash_statement, self).write(cr, uid, [statement.id], data, context=context)
96         return res
97
98     def _get_sum_entry_encoding(self, cr, uid, ids, name, arg, context=None):
99
100         """ Find encoding total of statements "
101         @param name: Names of fields.
102         @param arg: User defined arguments
103         @return: Dictionary of values.
104         """
105         res = {}
106         for statement in self.browse(cr, uid, ids, context=context):
107             res[statement.id] = sum((line.amount for line in statement.line_ids), 0.0)
108         return res
109
110     def _get_company(self, cr, uid, context=None):
111         user_pool = self.pool.get('res.users')
112         company_pool = self.pool.get('res.company')
113         user = user_pool.browse(cr, uid, uid, context=context)
114         company_id = user.company_id
115         if not company_id:
116             company_id = company_pool.search(cr, uid, [])
117         return company_id and company_id[0] or False
118
119     def _get_statement_from_line(self, cr, uid, ids, context=None):
120         result = {}
121         for line in self.pool.get('account.bank.statement.line').browse(cr, uid, ids, context=context):
122             result[line.statement_id.id] = True
123         return result.keys()
124
125     def _compute_difference(self, cr, uid, ids, fieldnames, args, context=None):
126         result =  dict.fromkeys(ids, 0.0)
127
128         for obj in self.browse(cr, uid, ids, context=context):
129             result[obj.id] = obj.balance_end_real - obj.balance_end
130
131         return result
132
133     def _compute_last_closing_balance(self, cr, uid, ids, fieldnames, args, context=None):
134         result = dict.fromkeys(ids, 0.0)
135
136         for obj in self.browse(cr, uid, ids, context=context):
137             if obj.state == 'draft':
138                 statement_ids = self.search(cr, uid,
139                     [('journal_id', '=', obj.journal_id.id),('state', '=', 'confirm')],
140                     order='create_date desc',
141                     limit=1,
142                     context=context
143                 )
144
145                 if not statement_ids:
146                     continue
147                 else:
148                     st = self.browse(cr, uid, statement_ids[0], context=context)
149                     result[obj.id] = st.balance_end_real
150
151         return result
152
153     def onchange_journal_id(self, cr, uid, ids, journal_id, context=None):
154         result = super(account_cash_statement, self).onchange_journal_id(cr, uid, ids, journal_id)
155
156         if not journal_id:
157             return result
158
159         statement_ids = self.search(cr, uid,
160                 [('journal_id', '=', journal_id),('state', '=', 'confirm')],
161                 order='create_date desc',
162                 limit=1,
163                 context=context
164         )
165
166         opening_details_ids = self._get_cash_open_box_lines(cr, uid, journal_id, context)
167         if opening_details_ids:
168             result['value']['opening_details_ids'] = opening_details_ids
169
170         if not statement_ids:
171             return result
172
173         st = self.browse(cr, uid, statement_ids[0], context=context)
174         result.setdefault('value', {}).update({'last_closing_balance' : st.balance_end_real})
175
176         return result
177
178     _columns = {
179         'total_entry_encoding': fields.function(_get_sum_entry_encoding, string="Total Transactions",
180             store = {
181                 'account.bank.statement': (lambda self, cr, uid, ids, context=None: ids, ['line_ids','move_line_ids'], 10),
182                 'account.bank.statement.line': (_get_statement_from_line, ['amount'], 10),
183             },
184             help="Total of cash transaction lines."),
185         'closing_date': fields.datetime("Closed On"),
186         'details_ids' : fields.one2many('account.cashbox.line', 'bank_statement_id', string='CashBox Lines', copy=True),
187         'opening_details_ids' : fields.one2many('account.cashbox.line', 'bank_statement_id', string='Opening Cashbox Lines'),
188         'closing_details_ids' : fields.one2many('account.cashbox.line', 'bank_statement_id', string='Closing Cashbox Lines'),
189         'user_id': fields.many2one('res.users', 'Responsible', required=False),
190         'difference' : fields.function(_compute_difference, method=True, string="Difference", type="float", help="Difference between the theoretical closing balance and the real closing balance."),
191         'last_closing_balance' : fields.function(_compute_last_closing_balance, method=True, string='Last Closing Balance', type='float'),
192     }
193     _defaults = {
194         'state': 'draft',
195         'date': lambda self, cr, uid, context={}: context.get('date', time.strftime("%Y-%m-%d %H:%M:%S")),
196         'user_id': lambda self, cr, uid, context=None: uid,
197     }
198
199     def _get_cash_open_box_lines(self, cr, uid, journal_id, context):
200         details_ids = []
201         if not journal_id:
202             return details_ids
203         journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context=context)
204         if journal and (journal.type == 'cash'):
205             last_pieces = None
206
207             if journal.with_last_closing_balance == True:
208                 domain = [('journal_id', '=', journal.id),
209                           ('state', '=', 'confirm')]
210                 last_bank_statement_ids = self.search(cr, uid, domain, limit=1, order='create_date desc', context=context)
211                 if last_bank_statement_ids:
212                     last_bank_statement = self.browse(cr, uid, last_bank_statement_ids[0], context=context)
213
214                     last_pieces = dict(
215                         (line.pieces, line.number_closing) for line in last_bank_statement.details_ids
216                     )
217             for value in journal.cashbox_line_ids:
218                 nested_values = {
219                     'number_closing' : 0,
220                     'number_opening' : last_pieces.get(value.pieces, 0) if isinstance(last_pieces, dict) else 0,
221                     'pieces' : value.pieces
222                 }
223                 details_ids.append([0, False, nested_values])
224         return details_ids
225
226     def create(self, cr, uid, vals, context=None):
227         journal_id = vals.get('journal_id')
228         if journal_id and not vals.get('opening_details_ids'):
229             vals['opening_details_ids'] = vals.get('opening_details_ids') or self._get_cash_open_box_lines(cr, uid, journal_id, context)
230         res_id = super(account_cash_statement, self).create(cr, uid, vals, context=context)
231         self._update_balances(cr, uid, [res_id], context)
232         return res_id
233
234     def write(self, cr, uid, ids, vals, context=None):
235         """
236         Update redord(s) comes in {ids}, with new value comes as {vals}
237         return True on success, False otherwise
238
239         @param cr: cursor to database
240         @param user: id of current user
241         @param ids: list of record ids to be update
242         @param vals: dict of new values to be set
243         @param context: context arguments, like lang, time zone
244
245         @return: True on success, False otherwise
246         """
247         if vals.get('journal_id', False):
248             cashbox_line_obj = self.pool.get('account.cashbox.line')
249             cashbox_ids = cashbox_line_obj.search(cr, uid, [('bank_statement_id', 'in', ids)], context=context)
250             cashbox_line_obj.unlink(cr, uid, cashbox_ids, context)
251         res = super(account_cash_statement, self).write(cr, uid, ids, vals, context=context)
252         self._update_balances(cr, uid, ids, context)
253         return res
254
255     def _user_allow(self, cr, uid, statement_id, context=None):
256         return True
257
258     def button_open(self, cr, uid, ids, context=None):
259         """ Changes statement state to Running.
260         @return: True
261         """
262         obj_seq = self.pool.get('ir.sequence')
263         if context is None:
264             context = {}
265         statement_pool = self.pool.get('account.bank.statement')
266         for statement in statement_pool.browse(cr, uid, ids, context=context):
267             vals = {}
268             if not self._user_allow(cr, uid, statement.id, context=context):
269                 raise osv.except_osv(_('Error!'), (_('You do not have rights to open this %s journal!') % (statement.journal_id.name, )))
270
271             if statement.name and statement.name == '/':
272                 c = {'fiscalyear_id': statement.period_id.fiscalyear_id.id}
273                 if statement.journal_id.sequence_id:
274                     st_number = obj_seq.next_by_id(cr, uid, statement.journal_id.sequence_id.id, context=c)
275                 else:
276                     st_number = obj_seq.next_by_code(cr, uid, 'account.cash.statement', context=c)
277                 vals.update({
278                     'name': st_number
279                 })
280
281             vals.update({
282                 'state': 'open',
283             })
284             self.write(cr, uid, [statement.id], vals, context=context)
285         return True
286
287     def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
288         if journal_type == 'bank':
289             return super(account_cash_statement, self).statement_close(cr, uid, ids, journal_type, context)
290         vals = {
291             'state':'confirm',
292             'closing_date': time.strftime("%Y-%m-%d %H:%M:%S")
293         }
294         return self.write(cr, uid, ids, vals, context=context)
295
296     def check_status_condition(self, cr, uid, state, journal_type='bank'):
297         if journal_type == 'bank':
298             return super(account_cash_statement, self).check_status_condition(cr, uid, state, journal_type)
299         return state=='open'
300
301     def button_confirm_cash(self, cr, uid, ids, context=None):
302         absl_proxy = self.pool.get('account.bank.statement.line')
303
304         TABLES = ((_('Profit'), 'profit_account_id'), (_('Loss'), 'loss_account_id'),)
305
306         for obj in self.browse(cr, uid, ids, context=context):
307             if obj.difference == 0.0:
308                 continue
309
310             for item_label, item_account in TABLES:
311                 if not getattr(obj.journal_id, item_account):
312                     raise osv.except_osv(_('Error!'),
313                                          _('There is no %s Account on the journal %s.') % (item_label, obj.journal_id.name,))
314
315             is_profit = obj.difference < 0.0
316
317             account = getattr(obj.journal_id, TABLES[is_profit][1])
318
319             values = {
320                 'statement_id' : obj.id,
321                 'journal_id' : obj.journal_id.id,
322                 'account_id' : account.id,
323                 'amount' : obj.difference,
324                 'name' : 'Exceptional %s' % TABLES[is_profit][0],
325             }
326
327             absl_proxy.create(cr, uid, values, context=context)
328
329         return super(account_cash_statement, self).button_confirm_bank(cr, uid, ids, context=context)
330
331
332 class account_journal(osv.osv):
333     _inherit = 'account.journal'
334
335     def _default_cashbox_line_ids(self, cr, uid, context=None):
336         # Return a list of coins in Euros.
337         result = [
338             dict(pieces=value) for value in [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500]
339         ]
340         return result
341
342     _columns = {
343         'cashbox_line_ids' : fields.one2many('account.journal.cashbox.line', 'journal_id', 'CashBox', copy=True),
344     }
345
346     _defaults = {
347         'cashbox_line_ids' : _default_cashbox_line_ids,
348     }
349
350
351 class account_journal_cashbox_line(osv.osv):
352     _name = 'account.journal.cashbox.line'
353     _rec_name = 'pieces'
354     _columns = {
355         'pieces': fields.float('Values', digits_compute=dp.get_precision('Account')),
356         'journal_id' : fields.many2one('account.journal', 'Journal', required=True, select=1, ondelete="cascade"),
357     }
358
359     _order = 'pieces asc'
360
361
362 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: