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.

381 lines
18 KiB

  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. from operator import itemgetter
  22. import time
  23. from openerp.osv import fields, osv
  24. from openerp import api
  25. class account_fiscal_position(osv.osv):
  26. _name = 'account.fiscal.position'
  27. _description = 'Fiscal Position'
  28. _order = 'sequence'
  29. _columns = {
  30. 'sequence': fields.integer('Sequence'),
  31. 'name': fields.char('Fiscal Position', required=True),
  32. 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a fiscal position without deleting it."),
  33. 'company_id': fields.many2one('res.company', 'Company'),
  34. 'account_ids': fields.one2many('account.fiscal.position.account', 'position_id', 'Account Mapping', copy=True),
  35. 'tax_ids': fields.one2many('account.fiscal.position.tax', 'position_id', 'Tax Mapping', copy=True),
  36. 'note': fields.text('Notes'),
  37. 'auto_apply': fields.boolean('Automatic', help="Apply automatically this fiscal position if the conditions match."),
  38. 'vat_required': fields.boolean('VAT required', help="Apply only if partner has a VAT number."),
  39. 'country_id': fields.many2one('res.country', 'Country', help="Apply when the shipping or invoicing country matches. Takes precedence over positions matching on a country group."),
  40. 'country_group_id': fields.many2one('res.country.group', 'Country Group', help="Apply when the shipping or invoicing country is in this country group, and no position matches the country directly."),
  41. }
  42. _defaults = {
  43. 'active': True,
  44. }
  45. def _check_country(self, cr, uid, ids, context=None):
  46. obj = self.browse(cr, uid, ids[0], context=context)
  47. if obj.country_id and obj.country_group_id:
  48. return False
  49. return True
  50. _constraints = [
  51. (_check_country, 'You can not select a country and a group of countries', ['country_id', 'country_group_id']),
  52. ]
  53. @api.v7
  54. def map_tax(self, cr, uid, fposition_id, taxes, context=None):
  55. if not taxes:
  56. return []
  57. if not fposition_id:
  58. return map(lambda x: x.id, taxes)
  59. result = set()
  60. for t in taxes:
  61. ok = False
  62. for tax in fposition_id.tax_ids:
  63. if tax.tax_src_id.id == t.id:
  64. if tax.tax_dest_id:
  65. result.add(tax.tax_dest_id.id)
  66. ok=True
  67. if not ok:
  68. result.add(t.id)
  69. return list(result)
  70. @api.v8 # noqa
  71. def map_tax(self, taxes):
  72. result = self.env['account.tax'].browse()
  73. for tax in taxes:
  74. tax_count = 0
  75. for t in self.tax_ids:
  76. if t.tax_src_id == tax:
  77. tax_count += 1
  78. if t.tax_dest_id:
  79. result |= t.tax_dest_id
  80. if not tax_count:
  81. result |= tax
  82. return result
  83. @api.v7
  84. def map_account(self, cr, uid, fposition_id, account_id, context=None):
  85. if not fposition_id:
  86. return account_id
  87. for pos in fposition_id.account_ids:
  88. if pos.account_src_id.id == account_id:
  89. account_id = pos.account_dest_id.id
  90. break
  91. return account_id
  92. @api.v8
  93. def map_account(self, account):
  94. for pos in self.account_ids:
  95. if pos.account_src_id == account:
  96. return pos.account_dest_id
  97. return account
  98. def get_fiscal_position(self, cr, uid, company_id, partner_id, delivery_id=None, context=None):
  99. if not partner_id:
  100. return False
  101. # This can be easily overriden to apply more complex fiscal rules
  102. part_obj = self.pool['res.partner']
  103. partner = part_obj.browse(cr, uid, partner_id, context=context)
  104. # if no delivery use invocing
  105. if delivery_id:
  106. delivery = part_obj.browse(cr, uid, delivery_id, context=context)
  107. else:
  108. delivery = partner
  109. # partner manually set fiscal position always win
  110. if delivery.property_account_position or partner.property_account_position:
  111. return delivery.property_account_position.id or partner.property_account_position.id
  112. domains = [[('auto_apply', '=', True), ('vat_required', '=', partner.vat_subjected)]]
  113. if partner.vat_subjected:
  114. # Possibly allow fallback to non-VAT positions, if no VAT-required position matches
  115. domains += [[('auto_apply', '=', True), ('vat_required', '=', False)]]
  116. for domain in domains:
  117. if delivery.country_id.id:
  118. fiscal_position_ids = self.search(cr, uid, domain + [('country_id', '=', delivery.country_id.id)], context=context, limit=1)
  119. if fiscal_position_ids:
  120. return fiscal_position_ids[0]
  121. fiscal_position_ids = self.search(cr, uid, domain + [('country_group_id.country_ids', '=', delivery.country_id.id)], context=context, limit=1)
  122. if fiscal_position_ids:
  123. return fiscal_position_ids[0]
  124. fiscal_position_ids = self.search(cr, uid, domain + [('country_id', '=', None), ('country_group_id', '=', None)], context=context, limit=1)
  125. if fiscal_position_ids:
  126. return fiscal_position_ids[0]
  127. return False
  128. class account_fiscal_position_tax(osv.osv):
  129. _name = 'account.fiscal.position.tax'
  130. _description = 'Taxes Fiscal Position'
  131. _rec_name = 'position_id'
  132. _columns = {
  133. 'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
  134. 'tax_src_id': fields.many2one('account.tax', 'Tax Source', required=True),
  135. 'tax_dest_id': fields.many2one('account.tax', 'Replacement Tax')
  136. }
  137. _sql_constraints = [
  138. ('tax_src_dest_uniq',
  139. 'unique (position_id,tax_src_id,tax_dest_id)',
  140. 'A tax fiscal position could be defined only once time on same taxes.')
  141. ]
  142. class account_fiscal_position_account(osv.osv):
  143. _name = 'account.fiscal.position.account'
  144. _description = 'Accounts Fiscal Position'
  145. _rec_name = 'position_id'
  146. _columns = {
  147. 'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
  148. 'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type','<>','view')], required=True),
  149. 'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type','<>','view')], required=True)
  150. }
  151. _sql_constraints = [
  152. ('account_src_dest_uniq',
  153. 'unique (position_id,account_src_id,account_dest_id)',
  154. 'An account fiscal position could be defined only once time on same accounts.')
  155. ]
  156. class res_partner(osv.osv):
  157. _name = 'res.partner'
  158. _inherit = 'res.partner'
  159. _description = 'Partner'
  160. def _credit_debit_get(self, cr, uid, ids, field_names, arg, context=None):
  161. ctx = context.copy()
  162. ctx['all_fiscalyear'] = True
  163. query = self.pool.get('account.move.line')._query_get(cr, uid, context=ctx)
  164. cr.execute("""SELECT l.partner_id, a.type, SUM(l.debit-l.credit)
  165. FROM account_move_line l
  166. LEFT JOIN account_account a ON (l.account_id=a.id)
  167. WHERE a.type IN ('receivable','payable')
  168. AND l.partner_id IN %s
  169. AND l.reconcile_id IS NULL
  170. AND """ + query + """
  171. GROUP BY l.partner_id, a.type
  172. """,
  173. (tuple(ids),))
  174. maps = {'receivable':'credit', 'payable':'debit' }
  175. res = {}
  176. for id in ids:
  177. res[id] = {}.fromkeys(field_names, 0)
  178. for pid,type,val in cr.fetchall():
  179. if val is None: val=0
  180. res[pid][maps[type]] = (type=='receivable') and val or -val
  181. return res
  182. def _asset_difference_search(self, cr, uid, obj, name, type, args, context=None):
  183. if not args:
  184. return []
  185. having_values = tuple(map(itemgetter(2), args))
  186. where = ' AND '.join(
  187. map(lambda x: '(SUM(bal2) %(operator)s %%s)' % {
  188. 'operator':x[1]},args))
  189. query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
  190. cr.execute(('SELECT pid AS partner_id, SUM(bal2) FROM ' \
  191. '(SELECT CASE WHEN bal IS NOT NULL THEN bal ' \
  192. 'ELSE 0.0 END AS bal2, p.id as pid FROM ' \
  193. '(SELECT (debit-credit) AS bal, partner_id ' \
  194. 'FROM account_move_line l ' \
  195. 'WHERE account_id IN ' \
  196. '(SELECT id FROM account_account '\
  197. 'WHERE type=%s AND active) ' \
  198. 'AND reconcile_id IS NULL ' \
  199. 'AND '+query+') AS l ' \
  200. 'RIGHT JOIN res_partner p ' \
  201. 'ON p.id = partner_id ) AS pl ' \
  202. 'GROUP BY pid HAVING ' + where),
  203. (type,) + having_values)
  204. res = cr.fetchall()
  205. if not res:
  206. return [('id','=','0')]
  207. return [('id','in',map(itemgetter(0), res))]
  208. def _credit_search(self, cr, uid, obj, name, args, context=None):
  209. return self._asset_difference_search(cr, uid, obj, name, 'receivable', args, context=context)
  210. def _debit_search(self, cr, uid, obj, name, args, context=None):
  211. return self._asset_difference_search(cr, uid, obj, name, 'payable', args, context=context)
  212. def _invoice_total(self, cr, uid, ids, field_name, arg, context=None):
  213. result = {}
  214. account_invoice_report = self.pool.get('account.invoice.report')
  215. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  216. user_currency_id = user.company_id.currency_id.id
  217. for partner_id in ids:
  218. all_partner_ids = self.pool['res.partner'].search(
  219. cr, uid, [('id', 'child_of', partner_id)], context=context)
  220. # searching account.invoice.report via the orm is comparatively expensive
  221. # (generates queries "id in []" forcing to build the full table).
  222. # In simple cases where all invoices are in the same currency than the user's company
  223. # access directly these elements
  224. # generate where clause to include multicompany rules
  225. where_query = account_invoice_report._where_calc(cr, uid, [
  226. ('partner_id', 'in', all_partner_ids), ('state', 'not in', ['draft', 'cancel'])
  227. ], context=context)
  228. account_invoice_report._apply_ir_rules(cr, uid, where_query, 'read', context=context)
  229. from_clause, where_clause, where_clause_params = where_query.get_sql()
  230. query = """ WITH currency_rate (currency_id, rate, date_start, date_end) AS (
  231. SELECT r.currency_id, r.rate, r.name AS date_start,
  232. (SELECT name FROM res_currency_rate r2
  233. WHERE r2.name > r.name AND
  234. r2.currency_id = r.currency_id
  235. ORDER BY r2.name ASC
  236. LIMIT 1) AS date_end
  237. FROM res_currency_rate r
  238. )
  239. SELECT SUM(price_total * cr.rate) as total
  240. FROM account_invoice_report account_invoice_report, currency_rate cr
  241. WHERE %s
  242. AND cr.currency_id = %%s
  243. AND (COALESCE(account_invoice_report.date, NOW()) >= cr.date_start)
  244. AND (COALESCE(account_invoice_report.date, NOW()) < cr.date_end OR cr.date_end IS NULL)
  245. """ % where_clause
  246. # price_total is in the currency with rate = 1
  247. # total_invoice should be displayed in the current user's currency
  248. # HACK: Avoid super expensive query taking 290s, see https://projects.sysmocom.de/issues/5379
  249. #cr.execute(query, where_clause_params + [user_currency_id])
  250. #result[partner_id] = cr.fetchone()[0]
  251. result[partner_id] = 0
  252. return result
  253. def _journal_item_count(self, cr, uid, ids, field_name, arg, context=None):
  254. MoveLine = self.pool('account.move.line')
  255. AnalyticAccount = self.pool('account.analytic.account')
  256. results = {}
  257. for partner_id in ids:
  258. results[partner_id] = {}
  259. if 'contracts_count' in field_name:
  260. results[partner_id]['contracts_count'] = AnalyticAccount.search_count(cr, uid, [('partner_id', '=', partner_id)], context=context)
  261. if 'journal_item_count' in field_name:
  262. results[partner_id]['journal_item_count'] = MoveLine.search_count(cr, uid, [('partner_id', '=', partner_id)], context=context)
  263. return results
  264. def has_something_to_reconcile(self, cr, uid, partner_id, context=None):
  265. '''
  266. at least a debit, a credit and a line older than the last reconciliation date of the partner
  267. '''
  268. cr.execute('''
  269. SELECT l.partner_id, SUM(l.debit) AS debit, SUM(l.credit) AS credit
  270. FROM account_move_line l
  271. RIGHT JOIN account_account a ON (a.id = l.account_id)
  272. RIGHT JOIN res_partner p ON (l.partner_id = p.id)
  273. WHERE a.reconcile IS TRUE
  274. AND p.id = %s
  275. AND l.reconcile_id IS NULL
  276. AND (p.last_reconciliation_date IS NULL OR l.date > p.last_reconciliation_date)
  277. AND l.state <> 'draft'
  278. GROUP BY l.partner_id''', (partner_id,))
  279. res = cr.dictfetchone()
  280. if res:
  281. return bool(res['debit'] and res['credit'])
  282. return False
  283. def mark_as_reconciled(self, cr, uid, ids, context=None):
  284. return self.write(cr, uid, ids, {'last_reconciliation_date': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
  285. _columns = {
  286. 'vat_subjected': fields.boolean('VAT Legal Statement', help="Check this box if the partner is subjected to the VAT. It will be used for the VAT legal statement."),
  287. 'credit': fields.function(_credit_debit_get,
  288. fnct_search=_credit_search, string='Total Receivable', multi='dc', help="Total amount this customer owes you."),
  289. 'debit': fields.function(_credit_debit_get, fnct_search=_debit_search, string='Total Payable', multi='dc', help="Total amount you have to pay to this supplier."),
  290. 'debit_limit': fields.float('Payable Limit'),
  291. 'total_invoiced': fields.function(_invoice_total, string="Total Invoiced", type='float', groups='account.group_account_invoice'),
  292. 'contracts_count': fields.function(_journal_item_count, string="Contracts", type='integer', multi="invoice_journal"),
  293. 'journal_item_count': fields.function(_journal_item_count, string="Journal Items", type="integer", multi="invoice_journal"),
  294. 'property_account_payable': fields.property(
  295. type='many2one',
  296. relation='account.account',
  297. string="Account Payable",
  298. domain="[('type', '=', 'payable')]",
  299. help="This account will be used instead of the default one as the payable account for the current partner",
  300. required=True),
  301. 'property_account_receivable': fields.property(
  302. type='many2one',
  303. relation='account.account',
  304. string="Account Receivable",
  305. domain="[('type', '=', 'receivable')]",
  306. help="This account will be used instead of the default one as the receivable account for the current partner",
  307. required=True),
  308. 'property_account_position': fields.property(
  309. type='many2one',
  310. relation='account.fiscal.position',
  311. string="Fiscal Position",
  312. help="The fiscal position will determine taxes and accounts used for the partner.",
  313. ),
  314. 'property_payment_term': fields.property(
  315. type='many2one',
  316. relation='account.payment.term',
  317. string ='Customer Payment Term',
  318. help="This payment term will be used instead of the default one for sale orders and customer invoices"),
  319. 'property_supplier_payment_term': fields.property(
  320. type='many2one',
  321. relation='account.payment.term',
  322. string ='Supplier Payment Term',
  323. help="This payment term will be used instead of the default one for purchase orders and supplier invoices"),
  324. 'ref_companies': fields.one2many('res.company', 'partner_id',
  325. 'Companies that refers to partner'),
  326. 'last_reconciliation_date': fields.datetime(
  327. 'Latest Full Reconciliation Date', copy=False,
  328. help='Date on which the partner accounting entries were fully reconciled last time. '
  329. 'It differs from the last date where a reconciliation has been made for this partner, '
  330. 'as here we depict the fact that nothing more was to be reconciled at this date. '
  331. 'This can be achieved in 2 different ways: either the last unreconciled debit/credit '
  332. 'entry of this partner was reconciled, either the user pressed the button '
  333. '"Nothing more to reconcile" during the manual reconciliation process.')
  334. }
  335. def _commercial_fields(self, cr, uid, context=None):
  336. return super(res_partner, self)._commercial_fields(cr, uid, context=context) + \
  337. ['debit_limit', 'property_account_payable', 'property_account_receivable', 'property_account_position',
  338. 'property_payment_term', 'property_supplier_payment_term', 'last_reconciliation_date']
  339. # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: