[FIX] fix the description problem in invoice report and in notes of customer invoice...
[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 osv import osv, fields
26 from tools.translate import _
27 import 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 = 'number'
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] = obj.pieces * obj.number
47         return res
48
49     def on_change_sub(self, cr, uid, ids, pieces, number, *a):
50
51         """ Calculates Sub total on change of number
52         @param pieces: Names of fields.
53         @param number:
54         """
55         sub = pieces * number
56         return {'value': {'subtotal': sub or 0.0}}
57
58     _columns = {
59         'pieces': fields.float('Values', digits_compute=dp.get_precision('Account')),
60         'number': fields.integer('Number'),
61         'subtotal': fields.function(_sub_total, string='Sub Total', type='float', digits_compute=dp.get_precision('Account')),
62         'starting_id': fields.many2one('account.bank.statement', ondelete='cascade'),
63         'ending_id': fields.many2one('account.bank.statement', ondelete='cascade'),
64      }
65
66 account_cashbox_line()
67
68 class account_cash_statement(osv.osv):
69
70     _inherit = 'account.bank.statement'
71
72     def _get_starting_balance(self, cr, uid, ids, context=None):
73
74         """ Find starting balance
75         @param name: Names of fields.
76         @param arg: User defined arguments
77         @return: Dictionary of values.
78         """
79         res = {}
80         for statement in self.browse(cr, uid, ids, context=context):
81             amount_total = 0.0
82
83             if statement.journal_id.type not in('cash'):
84                 continue
85
86             for line in statement.starting_details_ids:
87                 amount_total+= line.pieces * line.number
88             res[statement.id] = {
89                 'balance_start': amount_total
90             }
91         return res
92
93     def _balance_end_cash(self, cr, uid, ids, name, arg, context=None):
94         """ Find ending balance  "
95         @param name: Names of fields.
96         @param arg: User defined arguments
97         @return: Dictionary of values.
98         """
99         res = {}
100         for statement in self.browse(cr, uid, ids, context=context):
101             amount_total = 0.0
102             for line in statement.ending_details_ids:
103                 amount_total += line.pieces * line.number
104             res[statement.id] = amount_total
105         return res
106
107     def _get_sum_entry_encoding(self, cr, uid, ids, name, arg, context=None):
108
109         """ Find encoding total of statements "
110         @param name: Names of fields.
111         @param arg: User defined arguments
112         @return: Dictionary of values.
113         """
114         res2 = {}
115         for statement in self.browse(cr, uid, ids, context=context):
116             encoding_total=0.0
117             for line in statement.line_ids:
118                encoding_total += line.amount
119             res2[statement.id] = encoding_total
120         return res2
121
122     def _get_company(self, cr, uid, context=None):
123         user_pool = self.pool.get('res.users')
124         company_pool = self.pool.get('res.company')
125         user = user_pool.browse(cr, uid, uid, context=context)
126         company_id = user.company_id
127         if not company_id:
128             company_id = company_pool.search(cr, uid, [])
129         return company_id and company_id[0] or False
130
131     def _get_cash_open_box_lines(self, cr, uid, context=None):
132         res = []
133         curr = [1, 2, 5, 10, 20, 50, 100, 500]
134         for rs in curr:
135             dct = {
136                 'pieces': rs,
137                 'number': 0
138             }
139             res.append(dct)
140         journal_ids = self.pool.get('account.journal').search(cr, uid, [('type', '=', 'cash')], context=context)
141         if journal_ids:
142             results = self.search(cr, uid, [('journal_id', 'in', journal_ids),('state', '=', 'confirm')], context=context)
143             if results:
144                 cash_st = self.browse(cr, uid, results, context=context)[0]
145                 for cash_line in cash_st.ending_details_ids:
146                     for r in res:
147                         if cash_line.pieces == r['pieces']:
148                             r['number'] = cash_line.number
149         return res
150
151     def _get_default_cash_close_box_lines(self, cr, uid, context=None):
152         res = []
153         curr = [1, 2, 5, 10, 20, 50, 100, 500]
154         for rs in curr:
155             dct = {
156                 'pieces': rs,
157                 'number': 0
158             }
159             res.append(dct)
160         return res
161
162     def _get_cash_close_box_lines(self, cr, uid, context=None):
163         res = []
164         curr = [1, 2, 5, 10, 20, 50, 100, 500]
165         for rs in curr:
166             dct = {
167                 'pieces': rs,
168                 'number': 0
169             }
170             res.append((0, 0, dct))
171         return res
172
173     def _get_cash_open_close_box_lines(self, cr, uid, context=None):
174         res = {}
175         start_l = []
176         end_l = []
177         starting_details = self._get_cash_open_box_lines(cr, uid, context=context)
178         ending_details = self._get_default_cash_close_box_lines(cr, uid, context)
179         for start in starting_details:
180             start_l.append((0, 0, start))
181         for end in ending_details:
182             end_l.append((0, 0, end))
183         res['start'] = start_l
184         res['end'] = end_l
185         return res
186
187     _columns = {
188         'total_entry_encoding': fields.function(_get_sum_entry_encoding, store=True, string="Cash Transaction", help="Total cash transactions"),
189         'closing_date': fields.datetime("Closed On"),
190         'balance_end_cash': fields.function(_balance_end_cash, store=True, string='Balance', help="Closing balance based on cashBox"),
191         'starting_details_ids': fields.one2many('account.cashbox.line', 'starting_id', string='Opening Cashbox'),
192         'ending_details_ids': fields.one2many('account.cashbox.line', 'ending_id', string='Closing Cashbox'),
193         'user_id': fields.many2one('res.users', 'Responsible', required=False),
194     }
195     _defaults = {
196         'state': 'draft',
197         'date': lambda *a: time.strftime("%Y-%m-%d %H:%M:%S"),
198         'user_id': lambda self, cr, uid, context=None: uid,
199         'starting_details_ids': _get_cash_open_box_lines,
200         'ending_details_ids': _get_default_cash_close_box_lines
201      }
202
203     def create(self, cr, uid, vals, context=None):
204         sql = [
205                 ('journal_id', '=', vals.get('journal_id', False)),
206                 ('state', '=', 'open')
207         ]
208         open_jrnl = self.search(cr, uid, sql)
209         if open_jrnl:
210             raise osv.except_osv(_('Error'), _('You can not have two open register for the same journal!'))
211
212         if self.pool.get('account.journal').browse(cr, uid, vals['journal_id'], context=context).type == 'cash':
213             open_close = self._get_cash_open_close_box_lines(cr, uid, context)
214             if vals.get('starting_details_ids', False):
215                 for start in vals.get('starting_details_ids'):
216                     dict_val = start[2]
217                     for end in open_close['end']:
218                        if end[2]['pieces'] == dict_val['pieces']:
219                            end[2]['number'] += dict_val['number']
220             vals.update({
221 #                'ending_details_ids': open_close['start'],
222                 'starting_details_ids': open_close['end']
223             })
224         else:
225             vals.update({
226                 'ending_details_ids': False,
227                 'starting_details_ids': False
228             })
229         res_id = super(account_cash_statement, self).create(cr, uid, vals, context=context)
230         self.write(cr, uid, [res_id], {})
231         return res_id
232
233     def write(self, cr, uid, ids, vals, context=None):
234         """
235         Update redord(s) comes in {ids}, with new value comes as {vals}
236         return True on success, False otherwise
237
238         @param cr: cursor to database
239         @param user: id of current user
240         @param ids: list of record ids to be update
241         @param vals: dict of new values to be set
242         @param context: context arguments, like lang, time zone
243
244         @return: True on success, False otherwise
245         """
246
247         super(account_cash_statement, self).write(cr, uid, ids, vals, context=context)
248         res = self._get_starting_balance(cr, uid, ids)
249         for rs in res:
250             super(account_cash_statement, self).write(cr, uid, [rs], res.get(rs))
251         return True
252
253     def onchange_journal_id(self, cr, uid, statement_id, journal_id, context=None):
254         """ Changes balance start and starting details if journal_id changes"
255         @param statement_id: Changed statement_id
256         @param journal_id: Changed journal_id
257         @return:  Dictionary of changed values
258         """
259         res = {}
260         balance_start = 0.0
261         if not journal_id:
262             res.update({
263                 'balance_start': balance_start
264             })
265             return res
266         return super(account_cash_statement, self).onchange_journal_id(cr, uid, statement_id, journal_id, context=context)
267
268     def _equal_balance(self, cr, uid, cash_id, context=None):
269         statement = self.browse(cr, uid, cash_id, context=context)
270         self.write(cr, uid, [cash_id], {'balance_end_real': statement.balance_end})
271         statement.balance_end_real = statement.balance_end
272         if statement.balance_end != statement.balance_end_cash:
273             return False
274         return True
275
276     def _user_allow(self, cr, uid, statement_id, context=None):
277         return True
278
279     def button_open(self, cr, uid, ids, context=None):
280         """ Changes statement state to Running.
281         @return: True
282         """
283         obj_seq = self.pool.get('ir.sequence')
284         if context is None:
285             context = {}
286         statement_pool = self.pool.get('account.bank.statement')
287         for statement in statement_pool.browse(cr, uid, ids, context=context):
288             vals = {}
289             if not self._user_allow(cr, uid, statement.id, context=context):
290                 raise osv.except_osv(_('Error !'), (_('User %s does not have rights to access %s journal !') % (statement.user_id.name, statement.journal_id.name)))
291
292             if statement.name and statement.name == '/':
293                 if statement.journal_id.sequence_id:
294                     c = {'fiscalyear_id': statement.period_id.fiscalyear_id.id}
295                     st_number = obj_seq.get_id(cr, uid, statement.journal_id.sequence_id.id, context=c)
296                 else:
297                     st_number = obj_seq.get(cr, uid, 'account.cash.statement')
298                 vals.update({
299                     'name': st_number
300                 })
301
302             vals.update({
303                 'date': time.strftime("%Y-%m-%d %H:%M:%S"),
304                 'state': 'open',
305             })
306             self.write(cr, uid, [statement.id], vals, context=context)
307         return True
308
309     def balance_check(self, cr, uid, cash_id, journal_type='bank', context=None):
310         if journal_type == 'bank':
311             return super(account_cash_statement, self).balance_check(cr, uid, cash_id, journal_type, context)
312         if not self._equal_balance(cr, uid, cash_id, context):
313             raise osv.except_osv(_('Error !'), _('CashBox Balance is not matching with Calculated Balance !'))
314         return True
315
316     def statement_close(self, cr, uid, ids, journal_type='bank', context=None):
317         if journal_type == 'bank':
318             return super(account_cash_statement, self).statement_close(cr, uid, ids, journal_type, context)
319         vals = {
320             'state':'confirm',
321             'closing_date': time.strftime("%Y-%m-%d %H:%M:%S")
322         }
323         return self.write(cr, uid, ids, vals, context=context)
324
325     def check_status_condition(self, cr, uid, state, journal_type='bank'):
326         if journal_type == 'bank':
327             return super(account_cash_statement, self).check_status_condition(cr, uid, state, journal_type)
328         return state=='open'
329
330     def button_confirm_cash(self, cr, uid, ids, context=None):
331         super(account_cash_statement, self).button_confirm_bank(cr, uid, ids, context=context)
332         return self.write(cr, uid, ids, {'closing_date': time.strftime("%Y-%m-%d %H:%M:%S")}, context=context)
333
334     def button_cancel(self, cr, uid, ids, context=None):
335         cash_box_line_pool = self.pool.get('account.cashbox.line')
336         super(account_cash_statement, self).button_cancel(cr, uid, ids, context=context)
337         for st in self.browse(cr, uid, ids, context):
338             for end in st.ending_details_ids:
339                 cash_box_line_pool.write(cr, uid, [end.id], {'number': 0})
340         return True
341
342 account_cash_statement()
343
344 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: