[IMP] Change pricelist for price type into company property
[odoo/odoo.git] / addons / account / account_analytic_line.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #    
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 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 time
23
24 from osv import fields
25 from osv import osv
26 from tools.translate import _
27 import tools
28 from tools import config
29
30 class account_analytic_line(osv.osv):
31     _name = 'account.analytic.line'
32     _description = 'Analytic lines'
33     
34     def _amount_currency(self, cr, uid, ids, field_name, arg, context={}):
35         result = {}
36         for rec in self.browse(cr, uid, ids, context):
37             cmp_cur_id=rec.company_id.currency_id.id
38             aa_cur_id=rec.account_id.currency_id.id
39             # Always provide the amount in currency
40             if cmp_cur_id <> aa_cur_id:
41                 cur_obj = self.pool.get('res.currency')
42                 ctx = {}
43                 if rec.date and rec.amount:
44                     ctx['date'] = rec.date
45                     result[rec.id] = cur_obj.compute(cr, uid, rec.company_id.currency_id.id,
46                         rec.account_id.currency_id.id, rec.amount,
47                         context=ctx)
48             else:
49                 result[rec.id]=rec.amount
50         return result
51         
52     def _get_account_currency(self, cr, uid, ids, field_name, arg, context={}):
53         result = {}
54         for rec in self.browse(cr, uid, ids, context):
55             # Always provide second currency
56             result[rec.id] = (rec.account_id.currency_id.id,rec.account_id.currency_id.code)
57         return result
58     
59     def _get_account_line(self, cr, uid, ids, context={}):
60         aac_ids = {}
61         for acc in self.pool.get('account.analytic.account').browse(cr, uid, ids):
62             aac_ids[acc.id] = True
63         aal_ids = []
64         if aac_ids:
65             aal_ids = self.pool.get('account.analytic.line').search(cr, uid, [('account_id','in',aac_ids.keys())], context=context)
66         return aal_ids
67
68     _columns = {
69         'name' : fields.char('Description', size=256, required=True),
70         'date' : fields.date('Date', required=True),
71         'amount' : fields.float('Amount', required=True),
72         'unit_amount' : fields.float('Quantity'),
73         'product_uom_id' : fields.many2one('product.uom', 'UoM'),
74         'product_id' : fields.many2one('product.product', 'Product'),
75         'account_id' : fields.many2one('account.analytic.account', 'Analytic Account', required=True, ondelete='cascade', select=True),
76         'general_account_id' : fields.many2one('account.account', 'General Account', required=True, ondelete='cascade'),
77         'move_id' : fields.many2one('account.move.line', 'Move Line', ondelete='cascade', select=True),
78         'journal_id' : fields.many2one('account.analytic.journal', 'Analytic Journal', required=True, ondelete='cascade', select=True),
79         'code' : fields.char('Code', size=8),
80         'user_id' : fields.many2one('res.users', 'User',),
81         'currency_id': fields.function(_get_account_currency, method=True, type='many2one', relation='res.currency', string='Account currency',
82                 store={
83                     'account.analytic.account': (_get_account_line, ['company_id'], 50),
84                     'account.analytic.line': (lambda self,cr,uid,ids,c={}: ids, ['amount','unit_amount'],10),
85                 },
86                 help="The related account currency if not equal to the company one."),
87         'company_id': fields.many2one('res.company','Company',required=True),
88         'amount_currency': fields.function(_amount_currency, method=True, digits=(16, int(config['price_accuracy'])), string='Amount currency',
89                 store={
90                     'account.analytic.account': (_get_account_line, ['company_id'], 50),
91                     'account.analytic.line': (lambda self,cr,uid,ids,c={}: ids, ['amount','unit_amount'],10),
92                 },
93                 help="The amount expressed in the related account currency if not equal to the company one."),
94         'ref': fields.char('Reference', size=32),
95     }
96     _defaults = {
97         'date': lambda *a: time.strftime('%Y-%m-%d'),
98         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.analytic.line', c),
99     }
100     _order = 'date'
101     
102     def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
103         if context is None:
104             context = {}
105
106         if context.get('from_date',False):
107             args.append(['date', '>=',context['from_date']])
108             
109         if context.get('to_date',False):
110             args.append(['date','<=',context['to_date']])
111             
112         return super(account_analytic_line, self).search(cr, uid, args, offset, limit,
113                 order, context=context, count=count)
114         
115     def _check_company(self, cr, uid, ids):
116         lines = self.browse(cr, uid, ids)
117         for l in lines:
118             if l.move_id and not l.account_id.company_id.id == l.move_id.account_id.company_id.id:
119                 return False
120         return True
121     _constraints = [
122 #        (_check_company, 'You can not create analytic line that is not in the same company than the account line', ['account_id'])
123     ]
124     
125     # Compute the cost based on the price type define into company
126     # property_valuation_price_type property
127     def on_change_unit_amount(self, cr, uid, id, prod_id, unit_amount,company_id,
128             date,unit=False, context=None):
129         if context==None:
130             context={}
131         uom_obj = self.pool.get('product.uom')
132         product_obj = self.pool.get('product.product')
133         company_obj=self.pool.get('res.company')
134         if  prod_id:
135             prod = product_obj.browse(cr, uid, prod_id)
136             a = prod.product_tmpl_id.property_account_expense.id
137             if not a:
138                 a = prod.categ_id.property_account_expense_categ.id
139             if not a:
140                 raise osv.except_osv(_('Error !'),
141                         _('There is no expense account defined ' \
142                                 'for this product: "%s" (id:%d)') % \
143                                 (prod.name, prod.id,))
144             if not company_id:
145                 company_id=company_obj._company_default_get(cr, uid, 'account.analytic.line', context)
146       
147             # Compute based on pricetype
148             pricetype=self.pool.get('product.price.type').browse(cr,uid,company_obj.browse(cr,uid,company_id).property_valuation_price_type.id)
149             amount_unit=prod.price_get(pricetype.field, context)[prod.id]
150
151             amount=amount_unit*unit_amount or 1.0
152             return {'value': {
153                 'amount': - round(amount, 2),
154                 'general_account_id': a,
155                 }}
156         return {}
157
158     def view_header_get(self, cr, user, view_id, view_type, context):
159         if context.get('account_id', False):
160             # account_id in context may also be pointing to an account.account.id
161             cr.execute('select name from account_analytic_account where id=%s', (context['account_id'],))
162             res = cr.fetchone()
163             if res:
164                 res = _('Entries: ')+ (res[0] or '')
165             return res
166         return False
167
168 account_analytic_line()
169
170
171 class timesheet_invoice(osv.osv):
172     _name = "report.hr.timesheet.invoice.journal"
173     _description = "Analytic account costs and revenues"
174     _auto = False
175     _columns = {
176         'name': fields.char('Year',size=64,required=False, readonly=True),
177         'account_id':fields.many2one('account.analytic.account', 'Analytic Account', readonly=True, select=True),
178         'journal_id': fields.many2one('account.analytic.journal', 'Journal', readonly=True),
179         'quantity': fields.float('Quantities', readonly=True),
180         'cost': fields.float('Credit', readonly=True),
181         'revenue': fields.float('Debit', readonly=True),
182         'month':fields.selection([('01','January'), ('02','February'), ('03','March'), ('04','April'), ('05','May'), ('06','June'),
183                                   ('07','July'), ('08','August'), ('09','September'), ('10','October'), ('11','November'), ('12','December')],'Month',readonly=True),
184     }
185     _order = 'name desc, account_id'
186     def init(self, cr):
187         tools.drop_view_if_exists(cr, 'report_hr_timesheet_invoice_journal')
188         cr.execute("""
189         create or replace view report_hr_timesheet_invoice_journal as (
190             select
191                 min(l.id) as id,
192                 to_char(l.date, 'YYYY') as name,
193                 to_char(l.date,'MM') as month,
194                 sum(
195                     CASE WHEN l.amount>0 THEN 0 ELSE l.amount
196                     END
197                 ) as cost,
198                 sum(
199                     CASE WHEN l.amount>0 THEN l.amount ELSE 0
200                     END
201                 ) as revenue,
202                 sum(l.unit_amount* COALESCE(u.factor, 1)) as quantity,
203                 journal_id,
204                 account_id
205             from account_analytic_line l
206                 LEFT OUTER join product_uom u on (u.id=l.product_uom_id)
207             group by
208                 to_char(l.date, 'YYYY'),
209                 to_char(l.date,'MM'),
210                 journal_id,
211                 account_id
212         )""")
213 timesheet_invoice()
214
215 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
216