[MERGE]
[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-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 time
23 import decimal_precision as dp
24
25 from osv import fields
26 from osv import osv
27 from tools.translate import _
28 import tools
29 from tools import config
30
31 class account_analytic_line(osv.osv):
32     _inherit = 'account.analytic.line'
33     _description = 'Analytic Line'
34     _columns = {
35         'product_uom_id' : fields.many2one('product.uom', 'UoM'),
36         'product_id' : fields.many2one('product.product', 'Product'),
37         'general_account_id' : fields.many2one('account.account', 'General Account', required=True, ondelete='cascade'),
38         'move_id' : fields.many2one('account.move.line', 'Move Line', ondelete='cascade', select=True),
39         'journal_id' : fields.many2one('account.analytic.journal', 'Analytic Journal', required=True, ondelete='cascade', select=True),
40         'code' : fields.char('Code', size=8),
41         'ref': fields.char('Ref.', size=64),
42     }
43     _defaults = {
44         'date': lambda *a: time.strftime('%Y-%m-%d'),
45         'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.analytic.line', context=c),
46                 }
47     _order = 'date'
48
49     def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
50         if context is None:
51             context = {}
52
53         if context.get('from_date',False):
54             args.append(['date', '>=',context['from_date']])
55
56         if context.get('to_date',False):
57             args.append(['date','<=',context['to_date']])
58
59         return super(account_analytic_line, self).search(cr, uid, args, offset, limit,
60                 order, context=context, count=count)
61
62     def _check_company(self, cr, uid, ids):
63         lines = self.browse(cr, uid, ids)
64         for l in lines:
65             if l.move_id and not l.account_id.company_id.id == l.move_id.account_id.company_id.id:
66                 return False
67         return True
68     _constraints = [
69 #        (_check_company, 'You can not create analytic line that is not in the same company than the account line', ['account_id'])
70     ]
71
72     # Compute the cost based on the price type define into company
73     # property_valuation_price_type property
74     def on_change_unit_amount(self, cr, uid, id, prod_id, unit_amount,company_id,
75             unit=False, context=None):
76         if context==None:
77             context={}
78         uom_obj = self.pool.get('product.uom')
79         product_obj = self.pool.get('product.product')
80         company_obj=self.pool.get('res.company')
81         if  prod_id:
82             prod = product_obj.browse(cr, uid, prod_id)
83             a = prod.product_tmpl_id.property_account_expense.id
84             if not a:
85                 a = prod.categ_id.property_account_expense_categ.id
86             if not a:
87                 raise osv.except_osv(_('Error !'),
88                         _('There is no expense account defined ' \
89                                 'for this product: "%s" (id:%d)') % \
90                                 (prod.name, prod.id,))
91             if not company_id:
92                 company_id=company_obj._company_default_get(cr, uid, 'account.analytic.line', context)
93
94             # Compute based on pricetype
95             pricetype=self.pool.get('product.price.type').browse(cr,uid,company_obj.browse(cr,uid,company_id).property_valuation_price_type.id)
96             # Take the company currency as the reference one
97             context['currency_id']=company_obj.browse(cr,uid,company_id).currency_id.id
98             amount_unit=prod.price_get(pricetype.field, context)[prod.id]
99             amount=amount_unit*unit_amount or 1.0
100             return {'value': {
101                 'amount': - round(amount, 2),
102                 'general_account_id': a,
103                 }}
104         return {}
105
106     def view_header_get(self, cr, user, view_id, view_type, context):
107         if context.get('account_id', False):
108             # account_id in context may also be pointing to an account.account.id
109             cr.execute('select name from account_analytic_account where id=%s', (context['account_id'],))
110             res = cr.fetchone()
111             if res:
112                 res = _('Entries: ')+ (res[0] or '')
113             return res
114         return False
115
116 account_analytic_line()
117
118
119 class timesheet_invoice(osv.osv):
120     _name = "report.hr.timesheet.invoice.journal"
121     _description = "Analytic Account Costs and Revenues"
122     _auto = False
123     _columns = {
124         'name': fields.char('Year',size=64,required=False, readonly=True),
125         'account_id':fields.many2one('account.analytic.account', 'Analytic Account', readonly=True, select=True),
126         'journal_id': fields.many2one('account.analytic.journal', 'Journal', readonly=True),
127         'quantity': fields.float('Quantities', readonly=True),
128         'cost': fields.float('Credit', readonly=True),
129         'revenue': fields.float('Debit', readonly=True),
130         'month':fields.selection([('01','January'), ('02','February'), ('03','March'), ('04','April'), ('05','May'), ('06','June'),
131                                   ('07','July'), ('08','August'), ('09','September'), ('10','October'), ('11','November'), ('12','December')],'Month',readonly=True),
132     }
133     _order = 'name desc, account_id'
134     def init(self, cr):
135         tools.drop_view_if_exists(cr, 'report_hr_timesheet_invoice_journal')
136         cr.execute("""
137         create or replace view report_hr_timesheet_invoice_journal as (
138             select
139                 min(l.id) as id,
140                 to_char(l.date, 'YYYY') as name,
141                 to_char(l.date,'MM') as month,
142                 sum(
143                     CASE WHEN l.amount>0 THEN 0 ELSE l.amount
144                     END
145                 ) as cost,
146                 sum(
147                     CASE WHEN l.amount>0 THEN l.amount ELSE 0
148                     END
149                 ) as revenue,
150                 sum(l.unit_amount* COALESCE(u.factor, 1)) as quantity,
151                 journal_id,
152                 account_id
153             from account_analytic_line l
154                 LEFT OUTER join product_uom u on (u.id=l.product_uom_id)
155             group by
156                 to_char(l.date, 'YYYY'),
157                 to_char(l.date,'MM'),
158                 journal_id,
159                 account_id
160         )""")
161 timesheet_invoice()
162
163
164 class res_partner(osv.osv):
165     """ Inherits partner and adds contract information in the partner form """
166     _inherit = 'res.partner'
167
168     _columns = {
169                 'contract_ids': fields.one2many('account.analytic.account', \
170                                                     'partner_id', 'Contracts', readonly=True),
171                 }
172
173 res_partner()
174
175 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
176