You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

367 lines
14 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Author: Vincent Renaville, ported by Joel Grand-Guillaume
  5. # Copyright 2010-2012 Camptocamp SA
  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. from openerp.osv import orm, fields
  22. class AccountHoursBlock(orm.Model):
  23. _name = "account.hours.block"
  24. _inherit = ['mail.thread']
  25. def _get_last_action(self, cr, uid, ids, name, arg, context=None):
  26. """ Return the last analytic line date for an invoice"""
  27. res = {}
  28. for block in self.browse(cr, uid, ids, context=context):
  29. cr.execute("SELECT max(al.date) FROM account_analytic_line AS al"
  30. " WHERE al.invoice_id = %s", (block.invoice_id.id,))
  31. fetch_res = cr.fetchone()
  32. res[block.id] = fetch_res[0] if fetch_res else False
  33. return res
  34. def _compute_hours(self, cr, uid, ids, fields, args, context=None):
  35. """Return a dict of [id][fields]"""
  36. if isinstance(ids, (int, long)):
  37. ids = [ids]
  38. result = {}
  39. aal_obj = self.pool.get('account.analytic.line')
  40. for block in self.browse(cr, uid, ids, context=context):
  41. result[block.id] = {'amount_hours_block': 0.0,
  42. 'amount_hours_block_done': 0.0}
  43. # Compute hours bought
  44. for line in block.invoice_id.invoice_line:
  45. hours_bought = 0.0
  46. if line.product_id:
  47. # We will now calculate the product_quantity
  48. factor = line.uos_id.factor
  49. if factor == 0.0:
  50. factor = 1.0
  51. amount = line.quantity
  52. hours_bought += (amount / factor)
  53. result[block.id]['amount_hours_block'] += hours_bought
  54. # Compute hours spent
  55. hours_used = 0.0
  56. # Get ids of analytic line generated from
  57. # timesheet associated to the current block
  58. cr.execute("SELECT al.id "
  59. "FROM account_analytic_line AS al, "
  60. " account_analytic_journal AS aj "
  61. "WHERE aj.id = al.journal_id "
  62. "AND aj.type = 'general' "
  63. "AND al.invoice_id = %s", (block.invoice_id.id,))
  64. res_line_ids = cr.fetchall()
  65. line_ids = [l[0] for l in res_line_ids] if res_line_ids else []
  66. for line in aal_obj.browse(cr, uid, line_ids, context=context):
  67. factor = 1.0
  68. if line.product_uom_id and line.product_uom_id.factor != 0.0:
  69. factor = line.product_uom_id.factor
  70. factor_invoicing = 1.0
  71. if line.to_invoice and line.to_invoice.factor != 0.0:
  72. factor_invoicing = 1.0 - line.to_invoice.factor / 100
  73. hours_used += ((line.unit_amount / factor) * factor_invoicing)
  74. result[block.id]['amount_hours_block_done'] = hours_used
  75. return result
  76. def _compute_amount(self, cr, uid, ids, fields, args, context=None):
  77. if context is None:
  78. context = {}
  79. result = {}
  80. aal_obj = self.pool.get('account.analytic.line')
  81. pricelist_obj = self.pool.get('product.pricelist')
  82. for block in self.browse(cr, uid, ids, context=context):
  83. result[block.id] = {'amount_hours_block': 0.0,
  84. 'amount_hours_block_done': 0.0}
  85. # Compute amount bought
  86. for line in block.invoice_id.invoice_line:
  87. amount_bought = 0.0
  88. if line.product_id:
  89. ## We will now calculate the product_quantity
  90. factor = line.uos_id.factor
  91. if factor == 0.0:
  92. factor = 1.0
  93. amount = line.quantity * line.price_unit
  94. amount_bought += (amount / factor)
  95. result[block.id]['amount_hours_block'] += amount_bought
  96. # Compute total amount
  97. # Get ids of analytic line generated from timesheet associated to current block
  98. cr.execute("SELECT al.id FROM account_analytic_line AS al,"
  99. " account_analytic_journal AS aj"
  100. " WHERE aj.id = al.journal_id"
  101. " AND aj.type='general'"
  102. " AND al.invoice_id = %s", (block.invoice_id.id,))
  103. res_line_ids = cr.fetchall()
  104. line_ids = [l[0] for l in res_line_ids] if res_line_ids else []
  105. total_amount = 0.0
  106. for line in aal_obj.browse(cr, uid, line_ids, context=context):
  107. factor_invoicing = 1.0
  108. if line.to_invoice and line.to_invoice.factor != 0.0:
  109. factor_invoicing = 1.0 - line.to_invoice.factor / 100
  110. ctx = dict(context, uom=line.product_uom_id.id)
  111. amount = pricelist_obj.price_get(
  112. cr, uid,
  113. [line.account_id.pricelist_id.id],
  114. line.product_id.id,
  115. line.unit_amount or 1.0,
  116. line.account_id.partner_id.id or False,
  117. ctx)[line.account_id.pricelist_id.id]
  118. total_amount += amount * line.unit_amount * factor_invoicing
  119. result[block.id]['amount_hours_block_done'] += total_amount
  120. return result
  121. def _compute(self, cr, uid, ids, fields, args, context=None):
  122. result = {}
  123. block_per_types = {}
  124. for block in self.browse(cr, uid, ids, context=context):
  125. block_per_types.setdefault(block.type, []).append(block.id)
  126. for block_type in block_per_types:
  127. if block_type:
  128. func = getattr(self, "_compute_%s" % block_type)
  129. result.update(func(cr, uid, ids, fields, args, context=context))
  130. for block in result:
  131. result[block]['amount_hours_block_delta'] = \
  132. result[block]['amount_hours_block'] - \
  133. result[block]['amount_hours_block_done']
  134. return result
  135. def _get_analytic_line(self, cr, uid, ids, context=None):
  136. invoice_ids = []
  137. an_lines_obj = self.pool.get('account.analytic.line')
  138. block_obj = self.pool.get('account.hours.block')
  139. for line in an_lines_obj.browse(cr, uid, ids, context=context):
  140. if line.invoice_id:
  141. invoice_ids.append(line.invoice_id.id)
  142. return block_obj.search(
  143. cr, uid, [('invoice_id', 'in', invoice_ids)], context=context)
  144. def _get_invoice(self, cr, uid, ids, context=None):
  145. block_ids = set()
  146. inv_obj = self.pool.get('account.invoice')
  147. for invoice in inv_obj.browse(cr, uid, ids, context=context):
  148. block_ids.update([inv.id for inv in invoice.account_hours_block_ids])
  149. return list(block_ids)
  150. def action_send_block(self, cr, uid, ids, context=None):
  151. """Open a form to send by email. Return an action dict."""
  152. assert len(ids) == 1, '''\
  153. This option should only be used for a single ID at a time.'''
  154. ir_model_data = self.pool.get('ir.model.data')
  155. try:
  156. template_id = ir_model_data.get_object_reference(
  157. cr, uid, 'analytic_hours_block', 'email_template_hours_block'
  158. )[1]
  159. except ValueError:
  160. template_id = False
  161. try:
  162. compose_form_id = ir_model_data.get_object_reference(
  163. cr, uid, 'mail', 'email_compose_message_wizard_form'
  164. )[1]
  165. except ValueError:
  166. compose_form_id = False
  167. ctx = context.copy()
  168. ctx.update({
  169. 'default_model': self._name,
  170. 'default_res_id': ids[0],
  171. 'default_use_template': bool(template_id),
  172. 'default_template_id': template_id,
  173. 'default_composition_mode': 'comment',
  174. })
  175. return {
  176. 'type': 'ir.actions.act_window',
  177. 'view_type': 'form',
  178. 'view_mode': 'form',
  179. 'res_model': 'mail.compose.message',
  180. 'views': [(compose_form_id, 'form')],
  181. 'view_id': compose_form_id,
  182. 'target': 'new',
  183. 'context': ctx,
  184. }
  185. _recompute_triggers = {
  186. 'account.hours.block': (lambda self, cr, uid, ids, c=None:
  187. ids, ['invoice_id', 'type'], 10),
  188. 'account.invoice': (_get_invoice, ['analytic_line_ids'], 10),
  189. 'account.analytic.line': (
  190. _get_analytic_line,
  191. ['product_uom_id', 'unit_amount', 'to_invoice', 'invoice_id'],
  192. 10),
  193. }
  194. _columns = {
  195. 'amount_hours_block': fields.function(
  196. _compute,
  197. type='float',
  198. string='Quantity / Amount bought',
  199. store=_recompute_triggers,
  200. multi='amount_hours_block_delta',
  201. help="Amount bought by the customer. "
  202. "This amount is expressed in the base Unit of Measure "
  203. "(factor=1.0)"),
  204. 'amount_hours_block_done': fields.function(
  205. _compute,
  206. type='float',
  207. string='Quantity / Amount used',
  208. store=_recompute_triggers,
  209. multi='amount_hours_block_delta',
  210. help="Amount done by the staff. "
  211. "This amount is expressed in the base Unit of Measure "
  212. "(factor=1.0)"),
  213. 'amount_hours_block_delta': fields.function(
  214. _compute,
  215. type='float',
  216. string='Difference',
  217. store=_recompute_triggers,
  218. multi='amount_hours_block_delta',
  219. help="Difference between bought and used. "
  220. "This amount is expressed in the base Unit of Measure "
  221. "(factor=1.0)"),
  222. 'last_action_date': fields.function(
  223. _get_last_action,
  224. type='date',
  225. string='Last action date',
  226. help="Date of the last analytic line linked to the invoice "
  227. "related to this block hours."),
  228. 'close_date': fields.date('Closed Date'),
  229. 'invoice_id': fields.many2one(
  230. 'account.invoice',
  231. 'Invoice',
  232. ondelete='cascade',
  233. required=True),
  234. 'type': fields.selection(
  235. [('hours', 'Hours'),
  236. ('amount', 'Amount')],
  237. string='Type of Block',
  238. required=True,
  239. help="The block is based on the quantity of hours "
  240. "or on the amount."),
  241. # Invoices related infos
  242. 'date_invoice': fields.related(
  243. 'invoice_id', 'date_invoice',
  244. type="date",
  245. string="Invoice Date",
  246. store=True,
  247. readonly=True),
  248. 'user_id': fields.related(
  249. 'invoice_id', 'user_id',
  250. type="many2one",
  251. relation="res.users",
  252. string="Salesman",
  253. store=True,
  254. readonly=True),
  255. 'partner_id': fields.related(
  256. 'invoice_id', 'partner_id',
  257. type="many2one",
  258. relation="res.partner",
  259. string="Partner",
  260. store=True,
  261. readonly=True),
  262. 'name': fields.related(
  263. 'invoice_id', 'name',
  264. type="char",
  265. string="Description",
  266. store=True,
  267. readonly=True),
  268. 'number': fields.related(
  269. 'invoice_id', 'number',
  270. type="char",
  271. string="Number",
  272. store=True,
  273. readonly=True),
  274. 'journal_id': fields.related(
  275. 'invoice_id', 'journal_id',
  276. type="many2one",
  277. relation="account.journal",
  278. string="Journal",
  279. store=True,
  280. readonly=True),
  281. 'period_id': fields.related(
  282. 'invoice_id', 'period_id',
  283. type="many2one",
  284. relation="account.period",
  285. string="Period",
  286. store=True,
  287. readonly=True),
  288. 'company_id': fields.related(
  289. 'invoice_id', 'company_id',
  290. type="many2one",
  291. relation="res.company",
  292. string="Company",
  293. store=True,
  294. readonly=True),
  295. 'currency_id': fields.related(
  296. 'invoice_id', 'currency_id',
  297. type="many2one",
  298. relation="res.currency",
  299. string="Currency",
  300. store=True,
  301. readonly=True),
  302. 'residual': fields.related(
  303. 'invoice_id', 'residual',
  304. type="float",
  305. string="Residual",
  306. store=True,
  307. readonly=True),
  308. 'amount_total': fields.related(
  309. 'invoice_id', 'amount_total',
  310. type="float",
  311. string="Total",
  312. store=True,
  313. readonly=True),
  314. 'state': fields.related(
  315. 'invoice_id', 'state',
  316. type='selection',
  317. selection=[
  318. ('draft', 'Draft'),
  319. ('proforma', 'Pro-forma'),
  320. ('proforma2', 'Pro-forma'),
  321. ('open', 'Open'),
  322. ('paid', 'Paid'),
  323. ('cancel', 'Cancelled'),
  324. ],
  325. string='State',
  326. readonly=True,
  327. store=True),
  328. }
  329. ############################################################################
  330. ## Add hours blocks on invoice
  331. ############################################################################
  332. class AccountInvoice(orm.Model):
  333. _inherit = 'account.invoice'
  334. _columns = {
  335. 'account_hours_block_ids': fields.one2many(
  336. 'account.hours.block',
  337. 'invoice_id',
  338. string='Hours Block')
  339. }