From d2ff95f66505842995786872924507f077c714dd Mon Sep 17 00:00:00 2001 From: Christophe Simonis Date: Tue, 22 Jul 2008 17:11:28 +0200 Subject: [PATCH] replace tabs with 4 spaces bzr revid: christophe@tinyerp.com-20080722151128-f5zy75tsn8pgtndd --- addons/account/__terp__.py | 94 +- addons/account/account.py | 2984 ++++++++--------- addons/account/account_analytic_line.py | 176 +- addons/account/account_bank_statement.py | 930 ++--- addons/account/account_move_line.py | 1308 ++++---- addons/account/invoice.py | 1860 +++++----- addons/account/partner.py | 168 +- addons/account/product.py | 96 +- addons/account/project/project.py | 396 +-- .../account/project/report/account_journal.py | 30 +- .../project/report/analytic_balance.py | 252 +- .../account/project/report/analytic_check.py | 122 +- .../project/report/analytic_journal.py | 52 +- addons/account/project/report/cost_ledger.py | 148 +- .../report/inverted_analytic_balance.py | 152 +- .../project/report/quantity_cost_ledger.py | 198 +- .../wizard_account_analytic_analytic_check.py | 28 +- .../wizard_account_analytic_balance_report.py | 28 +- ...analytic_cost_ledger_for_journal_report.py | 60 +- ...ard_account_analytic_cost_ledger_report.py | 28 +- ...ccount_analytic_inverted_balance_report.py | 28 +- .../wizard_account_analytic_journal_report.py | 28 +- addons/account/report/account_balance.py | 164 +- addons/account/report/account_journal.py | 40 +- addons/account/report/aged_trial_balance.py | 294 +- addons/account/report/budget_report.py | 70 +- addons/account/report/central_journal.py | 40 +- addons/account/report/general_journal.py | 116 +- addons/account/report/general_ledger.py | 218 +- addons/account/report/invoice.py | 20 +- addons/account/report/overdue.py | 44 +- addons/account/report/partner_balance.py | 370 +- addons/account/report/tax_report.py | 146 +- addons/account/report/third_party_ledger.py | 272 +- .../wizard/wizard_account_balance_report.py | 44 +- addons/account/wizard/wizard_account_chart.py | 86 +- .../wizard/wizard_account_duplicate.py | 30 +- .../wizard/wizard_aged_trial_balance.py | 98 +- .../wizard/wizard_automatic_reconcile.py | 494 +-- .../account/wizard/wizard_bank_reconcile.py | 54 +- addons/account/wizard/wizard_budget_report.py | 28 +- addons/account/wizard/wizard_budget_spread.py | 38 +- .../account/wizard/wizard_fiscalyear_close.py | 242 +- .../wizard/wizard_general_ledger_report.py | 38 +- addons/account/wizard/wizard_invoice_state.py | 40 +- addons/account/wizard/wizard_journal.py | 100 +- .../account/wizard/wizard_journal_select.py | 32 +- .../account/wizard/wizard_move_line_select.py | 52 +- .../wizard/wizard_open_closed_fiscalyear.py | 80 +- .../wizard/wizard_partner_balance_report.py | 62 +- addons/account/wizard/wizard_pay_invoice.py | 154 +- addons/account/wizard/wizard_period_close.py | 38 +- addons/account/wizard/wizard_reconcile.py | 156 +- .../account/wizard/wizard_reconcile_select.py | 42 +- addons/account/wizard/wizard_refund.py | 48 +- .../wizard/wizard_subscription_generate.py | 36 +- .../wizard/wizard_third_party_ledger.py | 60 +- addons/account/wizard/wizard_unreconcile.py | 66 +- .../wizard/wizard_unreconcile_select.py | 42 +- .../wizard/wizard_validate_account_move.py | 82 +- addons/account/wizard/wizard_vat.py | 94 +- addons/account_analytic_analysis/__terp__.py | 32 +- .../account_analytic_analysis.py | 1358 ++++---- addons/account_chart/__terp__.py | 30 +- addons/account_followup/__terp__.py | 48 +- addons/account_followup/followup.py | 50 +- addons/account_followup/followup_report.py | 92 +- .../report/report_followup_print.py | 62 +- .../wizard/wizard_followup_print.py | 432 +-- addons/account_payment/__terp__.py | 34 +- addons/account_payment/account_invoice.py | 42 +- addons/account_payment/account_move_line.py | 158 +- addons/account_payment/payment.py | 810 ++--- addons/account_payment/wizard/wizard_pay.py | 56 +- .../wizard/wizard_payment_order.py | 176 +- .../wizard/wizard_populate_statement.py | 140 +- addons/account_report/__terp__.py | 30 +- addons/account_report/account.py | 262 +- addons/account_report/report/__init__.py | 0 .../report/accounting_report.py | 48 +- addons/account_tax_include/__terp__.py | 26 +- .../account_tax_include/invoice_tax_incl.py | 314 +- addons/base_iban/__terp__.py | 22 +- addons/base_iban/base_iban.py | 28 +- addons/base_module_publish/__terp__.py | 24 +- .../wizard/base_module_publish.py | 502 +-- .../wizard/base_module_publish_all.py | 228 +- .../base_module_publish/wizard/module_zip.py | 74 +- .../wizard/wizard_module_export.py | 48 +- addons/base_setup/__terp__.py | 56 +- addons/base_setup/base_setup.py | 8 +- addons/base_setup/wizard/wizard_base_setup.py | 716 ++-- addons/base_vat/__terp__.py | 16 +- addons/board/__terp__.py | 20 +- addons/board/board.py | 152 +- addons/board/wizard/board_wizard.py | 68 +- addons/board_account/__terp__.py | 52 +- addons/board_project/__terp__.py | 48 +- addons/board_sale/__terp__.py | 32 +- addons/crm/__terp__.py | 24 +- addons/crm/crm.py | 1328 ++++---- addons/crm/crm_operators.py | 62 +- addons/crm/crm_segmentation.py | 236 +- addons/crm/report/report_businessopp.py | 204 +- .../tinyerp-mailgate/tinyerp-mailgate.py | 474 +-- addons/crm/wizard/crm_wizard.py | 162 +- addons/custom/__terp__.py | 22 +- addons/custom/custom.py | 12 +- addons/delivery/__terp__.py | 22 +- addons/delivery/delivery.py | 190 +- addons/delivery/partner.py | 24 +- addons/delivery/sale.py | 40 +- addons/delivery/stock.py | 114 +- addons/delivery/wizard/delivery_sale_order.py | 76 +- addons/hr/__terp__.py | 58 +- addons/hr/hr.py | 406 +-- addons/hr/hr_department.py | 90 +- addons/hr/report/attendance_errors.py | 86 +- addons/hr/report/bymonth.py | 232 +- addons/hr/report/timesheet.py | 272 +- addons/hr/wizard/print_attendance_error.py | 36 +- addons/hr/wizard/print_bymonth.py | 30 +- addons/hr/wizard/print_byweek.py | 32 +- addons/hr/wizard/sign_in_out.py | 208 +- addons/hr_contract/__terp__.py | 44 +- addons/hr_contract/hr_contract.py | 118 +- addons/hr_expense/__terp__.py | 46 +- addons/hr_expense/hr_expense.py | 332 +- addons/hr_expense/report/expense.py | 10 +- addons/hr_timesheet/__terp__.py | 26 +- addons/hr_timesheet/hr_timesheet.py | 156 +- addons/hr_timesheet/report/user_timesheet.py | 106 +- addons/hr_timesheet/report/users_timesheet.py | 118 +- addons/hr_timesheet/wizard/sign_in_out.py | 214 +- .../wizard/wizard_print_timesheet.py | 62 +- .../wizard/wizard_print_timesheet_users.py | 36 +- addons/hr_timesheet_invoice/__terp__.py | 36 +- .../hr_timesheet_invoice.py | 172 +- .../report/account_analytic_profit.py | 188 +- .../report/cost_ledger.py | 252 +- .../wizard/account_analytic_profit.py | 88 +- .../hr_timesheet_final_invoice_create.py | 404 +-- .../wizard/hr_timesheet_invoice_create.py | 298 +- ...ard_account_analytic_cost_ledger_report.py | 28 +- addons/hr_timesheet_project/__terp__.py | 20 +- .../wizard/timesheet_hour_encode.py | 106 +- addons/hr_timesheet_sheet/__terp__.py | 26 +- .../hr_timesheet_sheet/hr_timesheet_sheet.py | 1102 +++--- .../wizard/wizard_timesheet_current.py | 68 +- .../wizard/wizard_timesheet_department.py | 138 +- addons/l10n_be/__terp__.py | 20 +- addons/l10n_chart_uk_minimal/__init__.py | 0 addons/l10n_chart_uk_minimal/__terp__.py | 22 +- addons/l10n_fr/__terp__.py | 22 +- addons/l10n_fr/wizard/__init__.py | 0 addons/l10n_fr/wizard/pdf_ext.py | 6 +- addons/l10n_fr/wizard/wizard_chart_report.py | 0 addons/mrp/__terp__.py | 82 +- addons/mrp/mrp.py | 1894 +++++------ addons/mrp/report/price.py | 284 +- addons/mrp/report/workcenter_load.py | 290 +- addons/mrp/wizard/schedulers.py | 412 +-- .../wizard/wizard_orderpoint_procurement.py | 44 +- addons/mrp/wizard/wizard_price.py | 24 +- addons/mrp/wizard/wizard_procurement.py | 80 +- addons/mrp/wizard/wizard_schedulers_all.py | 88 +- addons/mrp/wizard/wizard_track_prod.py | 120 +- addons/mrp/wizard/wizard_workcenter_load.py | 30 +- addons/multi_company/__terp__.py | 20 +- addons/multi_company_account/__terp__.py | 20 +- .../multi_company_account.py | 80 +- addons/processus/report/report_processus.py | 104 +- addons/product/__terp__.py | 52 +- addons/product/_common.py | 6 +- addons/product/partner.py | 28 +- addons/product/pricelist.py | 554 +-- addons/product/product.py | 934 +++--- addons/profile_accounting/__terp__.py | 18 +- addons/profile_manufacturing/__terp__.py | 18 +- addons/profile_service/__terp__.py | 38 +- addons/project/__terp__.py | 36 +- addons/project/project.py | 524 +-- addons/project/report/_date_compute.py | 106 +- addons/project/report/gantt.py | 132 +- addons/project/report/gantt_report.py | 84 +- addons/project/wizard/billing.py | 202 +- addons/project/wizard/close_task.py | 136 +- addons/project/wizard/task_delegate.py | 128 +- addons/purchase/__terp__.py | 44 +- addons/purchase/partner.py | 26 +- addons/purchase/purchase.py | 620 ++-- addons/purchase/report/order.py | 102 +- addons/purchase/report/request_quotation.py | 12 +- addons/purchase/stock.py | 112 +- addons/purchase/wizard/wizard_group.py | 200 +- addons/report_account/__terp__.py | 24 +- addons/report_account/report_receivable.py | 70 +- addons/report_analytic/__terp__.py | 24 +- addons/report_analytic/report_analytic.py | 68 +- addons/report_analytic_line/__terp__.py | 30 +- addons/report_analytic_planning/__terp__.py | 34 +- .../report_analytic_planning.py | 332 +- addons/report_crm/__terp__.py | 24 +- addons/report_crm/report_crm.py | 150 +- addons/report_intrastat/__terp__.py | 24 +- addons/report_intrastat/report_intrastat.py | 170 +- addons/report_mrp/__terp__.py | 22 +- addons/report_mrp/report_mrp.py | 128 +- addons/report_project/__terp__.py | 24 +- addons/report_purchase/__terp__.py | 22 +- addons/report_purchase/report_purchase.py | 164 +- addons/report_sale/__terp__.py | 42 +- addons/report_sale/report_sale.py | 178 +- addons/report_stock/__terp__.py | 34 +- addons/report_stock/report_stock.py | 88 +- addons/report_task/__init__.py | 4 +- addons/report_task/__terp__.py | 24 +- addons/report_task/report_task.py | 64 +- addons/report_timesheet/__terp__.py | 22 +- addons/report_timesheet/report_timesheet.py | 224 +- addons/sale/__terp__.py | 72 +- addons/sale/partner.py | 10 +- addons/sale/report/order.py | 10 +- addons/sale/report/sale_prepare_allot.py | 30 +- addons/sale/sale.py | 1472 ++++---- addons/sale/stock.py | 132 +- addons/sale/wizard/make_invoice.py | 78 +- .../sale/wizard/wizard_sale_line_invoice.py | 148 +- addons/scrum/__terp__.py | 56 +- addons/scrum/report/_burndown.py | 66 +- addons/scrum/report/sprint_burndown.py | 84 +- addons/scrum/report/task_burndown.py | 150 +- addons/scrum/scrum.py | 350 +- addons/scrum/wizard/backlog_to_task.py | 68 +- addons/stock/__terp__.py | 22 +- addons/stock/partner.py | 44 +- addons/stock/product.py | 118 +- addons/stock/report/lot_location.py | 48 +- addons/stock/report/product_location.py | 66 +- addons/stock/report/product_stock.py | 98 +- addons/stock/report/stock_by_location.py | 88 +- addons/stock/report/stock_graph.py | 138 +- addons/stock/report/ups.py | 14 +- addons/stock/stock.py | 1950 +++++------ addons/stock/wizard/stock_traceability.py | 80 +- .../stock/wizard/wizard_invoice_onshipping.py | 186 +- addons/stock/wizard/wizard_partial_picking.py | 304 +- addons/stock/wizard/wizard_picking_make.py | 92 +- addons/stock/wizard/wizard_replacement.py | 52 +- addons/stock/wizard/wizard_return.py | 160 +- addons/stock/wizard/wizard_split_lot_line.py | 72 +- addons/stock/wizard/wizard_track_line.py | 146 +- addons/stock/wizard/wizard_ups.py | 56 +- addons/subscription/__terp__.py | 20 +- addons/subscription/subscription.py | 208 +- 255 files changed, 22328 insertions(+), 22328 deletions(-) mode change 100755 => 100644 addons/account_report/report/__init__.py mode change 100755 => 100644 addons/account_report/report/accounting_report.py mode change 100755 => 100644 addons/crm/scripts/tinyerp-mailgate/tinyerp-mailgate.py mode change 100755 => 100644 addons/l10n_chart_uk_minimal/__init__.py mode change 100755 => 100644 addons/l10n_chart_uk_minimal/__terp__.py mode change 100755 => 100644 addons/l10n_fr/wizard/__init__.py mode change 100755 => 100644 addons/l10n_fr/wizard/pdf_ext.py mode change 100755 => 100644 addons/l10n_fr/wizard/wizard_chart_report.py mode change 100755 => 100644 addons/stock/report/lot_location.py diff --git a/addons/account/__terp__.py b/addons/account/__terp__.py index 50b94c9af3b..fba702ee046 100644 --- a/addons/account/__terp__.py +++ b/addons/account/__terp__.py @@ -26,51 +26,51 @@ # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ############################################################################### { - "name" : "Accounting and financial management", - "version" : "1.0", - "depends" : ["product", "base"], - "author" : "Tiny", - "description": """Financial and accounting module that covers: - General accounting - Cost / Analytic accounting - Third party accounting - Taxes management - Budgets - """, - "website" : "http://tinyerp.com/module_account.html", - "category" : "Generic Modules/Accounting", - "init_xml" : [ - - ], - "demo_xml" : [ - "account_demo.xml", - "project/project_demo.xml", - "project/analytic_account_demo.xml", - "account_unit_test.xml", - ], - "update_xml" : [ - "account_wizard.xml", - "account_view.xml", - "account_end_fy.xml", - "account_invoice_view.xml", - "account_report.xml", - "partner_view.xml", - "data/account_invoice.xml", - "data/account_data1.xml", - "data/account_minimal.xml", - "data/account_data2.xml", - "account_invoice_workflow.xml", - "project/project_view.xml", - "project/project_report.xml", - "product_data.xml", - "product_view.xml", - "account_security.xml", - "project/project_security.xml", - "account_assert_test.xml", - ], - "translations" : { - "fr": "i18n/french_fr.csv" - }, - "active": False, - "installable": True + "name" : "Accounting and financial management", + "version" : "1.0", + "depends" : ["product", "base"], + "author" : "Tiny", + "description": """Financial and accounting module that covers: + General accounting + Cost / Analytic accounting + Third party accounting + Taxes management + Budgets + """, + "website" : "http://tinyerp.com/module_account.html", + "category" : "Generic Modules/Accounting", + "init_xml" : [ + + ], + "demo_xml" : [ + "account_demo.xml", + "project/project_demo.xml", + "project/analytic_account_demo.xml", + "account_unit_test.xml", + ], + "update_xml" : [ + "account_wizard.xml", + "account_view.xml", + "account_end_fy.xml", + "account_invoice_view.xml", + "account_report.xml", + "partner_view.xml", + "data/account_invoice.xml", + "data/account_data1.xml", + "data/account_minimal.xml", + "data/account_data2.xml", + "account_invoice_workflow.xml", + "project/project_view.xml", + "project/project_report.xml", + "product_data.xml", + "product_view.xml", + "account_security.xml", + "project/project_security.xml", + "account_assert_test.xml", + ], + "translations" : { + "fr": "i18n/french_fr.csv" + }, + "active": False, + "installable": True } diff --git a/addons/account/account.py b/addons/account/account.py index 2e35a30c2ec..1d0b45baeb0 100644 --- a/addons/account/account.py +++ b/addons/account/account.py @@ -39,901 +39,901 @@ from mx.DateTime import RelativeDateTime, now, DateTime, localtime class account_payment_term(osv.osv): - _name = "account.payment.term" - _description = "Payment Term" - _columns = { - 'name': fields.char('Payment Term', size=32, translate=True), - 'active': fields.boolean('Active'), - 'note': fields.text('Description', translate=True), - 'line_ids': fields.one2many('account.payment.term.line', 'payment_id', 'Terms'), - } - _defaults = { - 'active': lambda *a: 1, - } - _order = "name" - def compute(self, cr, uid, id, value, date_ref=False, context={}): - if not date_ref: - date_ref = now().strftime('%Y-%m-%d') - pt = self.browse(cr, uid, id, context) - amount = value - result = [] - for line in pt.line_ids: - if line.value=='fixed': - amt = round(line.value_amount, 2) - elif line.value=='procent': - amt = round(value * line.value_amount, 2) - elif line.value=='balance': - amt = round(amount, 2) - if amt: - next_date = mx.DateTime.strptime(date_ref, '%Y-%m-%d') + RelativeDateTime(days=line.days) - if line.condition == 'end of month': - next_date += RelativeDateTime(day=-1) - result.append( (next_date.strftime('%Y-%m-%d'), amt) ) - amount -= amt - return result + _name = "account.payment.term" + _description = "Payment Term" + _columns = { + 'name': fields.char('Payment Term', size=32, translate=True), + 'active': fields.boolean('Active'), + 'note': fields.text('Description', translate=True), + 'line_ids': fields.one2many('account.payment.term.line', 'payment_id', 'Terms'), + } + _defaults = { + 'active': lambda *a: 1, + } + _order = "name" + def compute(self, cr, uid, id, value, date_ref=False, context={}): + if not date_ref: + date_ref = now().strftime('%Y-%m-%d') + pt = self.browse(cr, uid, id, context) + amount = value + result = [] + for line in pt.line_ids: + if line.value=='fixed': + amt = round(line.value_amount, 2) + elif line.value=='procent': + amt = round(value * line.value_amount, 2) + elif line.value=='balance': + amt = round(amount, 2) + if amt: + next_date = mx.DateTime.strptime(date_ref, '%Y-%m-%d') + RelativeDateTime(days=line.days) + if line.condition == 'end of month': + next_date += RelativeDateTime(day=-1) + result.append( (next_date.strftime('%Y-%m-%d'), amt) ) + amount -= amt + return result account_payment_term() class account_payment_term_line(osv.osv): - _name = "account.payment.term.line" - _description = "Payment Term Line" - _columns = { - 'name': fields.char('Line Name', size=32,required=True), - 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the payment term lines from the lowest sequences to the higher ones"), - 'value': fields.selection([('procent','Percent'),('balance','Balance'),('fixed','Fixed Amount')], 'Value',required=True), - 'value_amount': fields.float('Value Amount'), - 'days': fields.integer('Number of Days',required=True), - 'condition': fields.selection([('net days','Net Days'),('end of month','End of Month')], 'Condition', required=True, help="The payment delay condition id a number of days expressed in 2 ways: net days or end of the month. The 'net days' condition implies that the paiment arrive after 'Number of Days' calendar days. The 'end of the month' condition requires that the paiement arrives before the end of the month that is that is after 'Number of Days' calendar days."), - 'payment_id': fields.many2one('account.payment.term','Payment Term', required=True, select=True), - } - _defaults = { - 'value': lambda *a: 'balance', - 'sequence': lambda *a: 5, - 'condition': lambda *a: 'net days', - } - _order = "sequence" + _name = "account.payment.term.line" + _description = "Payment Term Line" + _columns = { + 'name': fields.char('Line Name', size=32,required=True), + 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the payment term lines from the lowest sequences to the higher ones"), + 'value': fields.selection([('procent','Percent'),('balance','Balance'),('fixed','Fixed Amount')], 'Value',required=True), + 'value_amount': fields.float('Value Amount'), + 'days': fields.integer('Number of Days',required=True), + 'condition': fields.selection([('net days','Net Days'),('end of month','End of Month')], 'Condition', required=True, help="The payment delay condition id a number of days expressed in 2 ways: net days or end of the month. The 'net days' condition implies that the paiment arrive after 'Number of Days' calendar days. The 'end of the month' condition requires that the paiement arrives before the end of the month that is that is after 'Number of Days' calendar days."), + 'payment_id': fields.many2one('account.payment.term','Payment Term', required=True, select=True), + } + _defaults = { + 'value': lambda *a: 'balance', + 'sequence': lambda *a: 5, + 'condition': lambda *a: 'net days', + } + _order = "sequence" account_payment_term_line() class account_account_type(osv.osv): - _name = "account.account.type" - _description = "Account Type" - _columns = { - 'name': fields.char('Acc. Type Name', size=64, required=True, translate=True), - 'code': fields.char('Code', size=32, required=True), - 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of account types."), - 'code_from': fields.char('Code From', size=10, help="Gives the range of account code available for this type of account. These fields are given for information and are not used in any constraint."), - 'code_to': fields.char('Code To', size=10, help="Gives the range of account code available for this type of account. These fields are just given for information and are not used in any constraint."), - 'partner_account': fields.boolean('Partner account'), - 'close_method': fields.selection([('none','None'), ('balance','Balance'), ('detail','Detail'),('unreconciled','Unreconciled')], 'Deferral Method', required=True), - } - _defaults = { - 'close_method': lambda *a: 'none', - 'sequence': lambda *a: 5, - } - _order = "sequence" + _name = "account.account.type" + _description = "Account Type" + _columns = { + 'name': fields.char('Acc. Type Name', size=64, required=True, translate=True), + 'code': fields.char('Code', size=32, required=True), + 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of account types."), + 'code_from': fields.char('Code From', size=10, help="Gives the range of account code available for this type of account. These fields are given for information and are not used in any constraint."), + 'code_to': fields.char('Code To', size=10, help="Gives the range of account code available for this type of account. These fields are just given for information and are not used in any constraint."), + 'partner_account': fields.boolean('Partner account'), + 'close_method': fields.selection([('none','None'), ('balance','Balance'), ('detail','Detail'),('unreconciled','Unreconciled')], 'Deferral Method', required=True), + } + _defaults = { + 'close_method': lambda *a: 'none', + 'sequence': lambda *a: 5, + } + _order = "sequence" account_account_type() def _code_get(self, cr, uid, context={}): - acc_type_obj = self.pool.get('account.account.type') - ids = acc_type_obj.search(cr, uid, []) - res = acc_type_obj.read(cr, uid, ids, ['code', 'name'], context) - return [(r['code'], r['name']) for r in res] + acc_type_obj = self.pool.get('account.account.type') + ids = acc_type_obj.search(cr, uid, []) + res = acc_type_obj.read(cr, uid, ids, ['code', 'name'], context) + return [(r['code'], r['name']) for r in res] #---------------------------------------------------------- # Accounts #---------------------------------------------------------- class account_tax(osv.osv): - _name = 'account.tax' + _name = 'account.tax' account_tax() class account_account(osv.osv): - _order = "code" - _name = "account.account" - _description = "Account" + _order = "code" + _name = "account.account" + _description = "Account" - def search(self, cr, uid, args, offset=0, limit=None, order=None, - context=None, count=False): - if context is None: - context = {} - pos = 0 - while pos id: - res.setdefault(id, 0.0) - if resc[idx]<>resc[id] and resc[idx] and resc[id]: - from_currency_id = rescur[resc[idx]] - res[id] += self.pool.get('res.currency').compute(cr, - uid, from_currency_id, to_currency_id, - res.get(idx, 0.0), context=context) - else: - res[id] += res.get(idx, 0.0) - for id in ids: - res[id] = round(res.get(id,0.0), 2) - return res + for id in ids: + ids3 = self.search(cr, uid, [('parent_id', 'child_of', [id])]) + to_currency_id = rescur[resc[id]] + for idx in ids3: + if idx <> id: + res.setdefault(id, 0.0) + if resc[idx]<>resc[id] and resc[idx] and resc[id]: + from_currency_id = rescur[resc[idx]] + res[id] += self.pool.get('res.currency').compute(cr, + uid, from_currency_id, to_currency_id, + res.get(idx, 0.0), context=context) + else: + res[id] += res.get(idx, 0.0) + for id in ids: + res[id] = round(res.get(id,0.0), 2) + return res - def _get_company_currency(self, cr, uid, ids, field_name, arg, context={}): - result = {} - for rec in self.browse(cr, uid, ids, context): - result[rec.id] = (rec.company_id.currency_id.id,rec.company_id.currency_id.code) - return result + def _get_company_currency(self, cr, uid, ids, field_name, arg, context={}): + result = {} + for rec in self.browse(cr, uid, ids, context): + result[rec.id] = (rec.company_id.currency_id.id,rec.company_id.currency_id.code) + return result - _columns = { - 'name': fields.char('Name', size=128, required=True, select=True), - 'sign': fields.selection([(-1, 'Negative'), (1, 'Positive')], 'Sign', required=True, help='Allows to change the displayed amount of the balance to see positive results instead of negative ones in expenses accounts'), - 'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Force all moves for this account to have this secondary currency."), - 'code': fields.char('Code', size=64), - 'type': fields.selection(_code_get, 'Account Type', required=True), - 'parent_id': fields.many2many('account.account', 'account_account_rel', 'child_id', 'parent_id', 'Parents'), - 'child_id': fields.many2many('account.account', 'account_account_rel', 'parent_id', 'child_id', 'Children'), - 'balance': fields.function(_balance, digits=(16,2), method=True, string='Balance'), - 'credit': fields.function(_credit, digits=(16,2), method=True, string='Credit'), - 'debit': fields.function(_debit, digits=(16,2), method=True, string='Debit'), - 'reconcile': fields.boolean('Reconcile', help="Check this account if the user can make a reconciliation of the entries in this account."), - 'shortcut': fields.char('Shortcut', size=12), - 'close_method': fields.selection([('none','None'), ('balance','Balance'), ('detail','Detail'),('unreconciled','Unreconciled')], 'Deferral Method', required=True, help="Tell Tiny ERP how to process the entries of this account when you close a fiscal year. None removes all entries to start with an empty account for the new fiscal year. Balance creates only one entry to keep the balance for the new fiscal year. Detail keeps the detail of all entries of the preceeding years. Unreconciled keeps the detail of unreconciled entries only."), - 'tax_ids': fields.many2many('account.tax', 'account_account_tax_default_rel', - 'account_id','tax_id', 'Default Taxes'), - 'note': fields.text('Note'), - 'company_currency_id': fields.function(_get_company_currency, method=True, type='many2one', relation='res.currency', string='Company Currency'), - 'company_id': fields.many2one('res.company', 'Company', required=True), - 'active': fields.boolean('Active', select=2), - } + _columns = { + 'name': fields.char('Name', size=128, required=True, select=True), + 'sign': fields.selection([(-1, 'Negative'), (1, 'Positive')], 'Sign', required=True, help='Allows to change the displayed amount of the balance to see positive results instead of negative ones in expenses accounts'), + 'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Force all moves for this account to have this secondary currency."), + 'code': fields.char('Code', size=64), + 'type': fields.selection(_code_get, 'Account Type', required=True), + 'parent_id': fields.many2many('account.account', 'account_account_rel', 'child_id', 'parent_id', 'Parents'), + 'child_id': fields.many2many('account.account', 'account_account_rel', 'parent_id', 'child_id', 'Children'), + 'balance': fields.function(_balance, digits=(16,2), method=True, string='Balance'), + 'credit': fields.function(_credit, digits=(16,2), method=True, string='Credit'), + 'debit': fields.function(_debit, digits=(16,2), method=True, string='Debit'), + 'reconcile': fields.boolean('Reconcile', help="Check this account if the user can make a reconciliation of the entries in this account."), + 'shortcut': fields.char('Shortcut', size=12), + 'close_method': fields.selection([('none','None'), ('balance','Balance'), ('detail','Detail'),('unreconciled','Unreconciled')], 'Deferral Method', required=True, help="Tell Tiny ERP how to process the entries of this account when you close a fiscal year. None removes all entries to start with an empty account for the new fiscal year. Balance creates only one entry to keep the balance for the new fiscal year. Detail keeps the detail of all entries of the preceeding years. Unreconciled keeps the detail of unreconciled entries only."), + 'tax_ids': fields.many2many('account.tax', 'account_account_tax_default_rel', + 'account_id','tax_id', 'Default Taxes'), + 'note': fields.text('Note'), + 'company_currency_id': fields.function(_get_company_currency, method=True, type='many2one', relation='res.currency', string='Company Currency'), + 'company_id': fields.many2one('res.company', 'Company', required=True), + 'active': fields.boolean('Active', select=2), + } - def _default_company(self, cr, uid, context={}): - user = self.pool.get('res.users').browse(cr, uid, uid, context=context) - if user.company_id: - return user.company_id.id - return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] + def _default_company(self, cr, uid, context={}): + user = self.pool.get('res.users').browse(cr, uid, uid, context=context) + if user.company_id: + return user.company_id.id + return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] - _defaults = { - 'sign': lambda *a: 1, - 'type' : lambda *a :'view', - 'reconcile': lambda *a: False, - 'close_method': lambda *a: 'balance', - 'company_id': _default_company, - 'active': lambda *a: True, - } + _defaults = { + 'sign': lambda *a: 1, + 'type' : lambda *a :'view', + 'reconcile': lambda *a: False, + 'close_method': lambda *a: 'balance', + 'company_id': _default_company, + 'active': lambda *a: True, + } - def _check_recursion(self, cr, uid, ids): - level = 100 - while len(ids): - cr.execute('select distinct parent_id from account_account_rel where child_id in ('+','.join(map(str,ids))+')') - ids = filter(None, map(lambda x:x[0], cr.fetchall())) - if not level: - return False - level -= 1 - return True + def _check_recursion(self, cr, uid, ids): + level = 100 + while len(ids): + cr.execute('select distinct parent_id from account_account_rel where child_id in ('+','.join(map(str,ids))+')') + ids = filter(None, map(lambda x:x[0], cr.fetchall())) + if not level: + return False + level -= 1 + return True - _constraints = [ - (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id']) - ] - def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): - if not args: - args=[] - if not context: - context = {} - args = args[:] - ids = [] - try: - if name and str(name).startswith('partner:'): - part_id = int(name.split(':')[1]) - part = self.pool.get('res.partner').browse(cr, user, part_id, context) - args += [('id','in', (part.property_account_payable.id, part.property_account_receivable.id))] - name = False - if name and str(name).startswith('type:'): - type = name.split(':')[1] - args += [('type','=', type)] - name = False - except: - pass - if name: - ids = self.search(cr, user, [('code','=like',name+"%")]+ args, limit=limit) - if not ids: - ids = self.search(cr, user, [('shortcut','=',name)]+ args, limit=limit) - if not ids: - ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit) - else: - ids = self.search(cr, user, args, context=context, limit=limit) - return self.name_get(cr, user, ids, context=context) + _constraints = [ + (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id']) + ] + def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): + if not args: + args=[] + if not context: + context = {} + args = args[:] + ids = [] + try: + if name and str(name).startswith('partner:'): + part_id = int(name.split(':')[1]) + part = self.pool.get('res.partner').browse(cr, user, part_id, context) + args += [('id','in', (part.property_account_payable.id, part.property_account_receivable.id))] + name = False + if name and str(name).startswith('type:'): + type = name.split(':')[1] + args += [('type','=', type)] + name = False + except: + pass + if name: + ids = self.search(cr, user, [('code','=like',name+"%")]+ args, limit=limit) + if not ids: + ids = self.search(cr, user, [('shortcut','=',name)]+ args, limit=limit) + if not ids: + ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit) + else: + ids = self.search(cr, user, args, context=context, limit=limit) + return self.name_get(cr, user, ids, context=context) - def name_get(self, cr, uid, ids, context={}): - if not len(ids): - return [] - reads = self.read(cr, uid, ids, ['name','code'], context) - res = [] - for record in reads: - name = record['name'] - if record['code']: - name = record['code']+' - '+name - res.append((record['id'],name )) - return res + def name_get(self, cr, uid, ids, context={}): + if not len(ids): + return [] + reads = self.read(cr, uid, ids, ['name','code'], context) + res = [] + for record in reads: + name = record['name'] + if record['code']: + name = record['code']+' - '+name + res.append((record['id'],name )) + return res - def copy(self, cr, uid, id, default=None, context={}): - account = self.browse(cr, uid, id, context=context) - new_child_ids = [] - default['parent_id'] = False - if account: - for child in account.child_id: - new_child_ids.append(self.copy(cr, uid, child.id, default, context=context)) - default['child_id'] = [(6, 0, new_child_ids)] - else: - default['child_id'] = False - return super(account_account, self).copy(cr, uid, id, default, context=context) + def copy(self, cr, uid, id, default=None, context={}): + account = self.browse(cr, uid, id, context=context) + new_child_ids = [] + default['parent_id'] = False + if account: + for child in account.child_id: + new_child_ids.append(self.copy(cr, uid, child.id, default, context=context)) + default['child_id'] = [(6, 0, new_child_ids)] + else: + default['child_id'] = False + return super(account_account, self).copy(cr, uid, id, default, context=context) - def write(self, cr, uid, ids, vals, context=None): - if not context: - context={} - if 'active' in vals and not vals['active']: - line_obj = self.pool.get('account.move.line') - account_ids = self.search(cr, uid, [('parent_id', 'child_of', ids)]) - if line_obj.search(cr, uid, [('account_id', 'in', account_ids)]): - vals=vals.copy() - del vals['active'] - return super(account_account, self).write(cr, uid, ids, vals, context=context) + def write(self, cr, uid, ids, vals, context=None): + if not context: + context={} + if 'active' in vals and not vals['active']: + line_obj = self.pool.get('account.move.line') + account_ids = self.search(cr, uid, [('parent_id', 'child_of', ids)]) + if line_obj.search(cr, uid, [('account_id', 'in', account_ids)]): + vals=vals.copy() + del vals['active'] + return super(account_account, self).write(cr, uid, ids, vals, context=context) account_account() class account_journal_view(osv.osv): - _name = "account.journal.view" - _description = "Journal View" - _columns = { - 'name': fields.char('Journal View', size=64, required=True), - 'columns_id': fields.one2many('account.journal.column', 'view_id', 'Columns') - } - _order = "name" + _name = "account.journal.view" + _description = "Journal View" + _columns = { + 'name': fields.char('Journal View', size=64, required=True), + 'columns_id': fields.one2many('account.journal.column', 'view_id', 'Columns') + } + _order = "name" account_journal_view() class account_journal_column(osv.osv): - def _col_get(self, cr, user, context={}): - result = [] - cols = self.pool.get('account.move.line')._columns - for col in cols: - result.append( (col, cols[col].string) ) - result.sort() - return result - _name = "account.journal.column" - _description = "Journal Column" - _columns = { - 'name': fields.char('Column Name', size=64, required=True), - 'field': fields.selection(_col_get, 'Field Name', method=True, required=True, size=32), - 'view_id': fields.many2one('account.journal.view', 'Journal View', select=True), - 'sequence': fields.integer('Sequence'), - 'required': fields.boolean('Required'), - 'readonly': fields.boolean('Readonly'), - } - _order = "sequence" + def _col_get(self, cr, user, context={}): + result = [] + cols = self.pool.get('account.move.line')._columns + for col in cols: + result.append( (col, cols[col].string) ) + result.sort() + return result + _name = "account.journal.column" + _description = "Journal Column" + _columns = { + 'name': fields.char('Column Name', size=64, required=True), + 'field': fields.selection(_col_get, 'Field Name', method=True, required=True, size=32), + 'view_id': fields.many2one('account.journal.view', 'Journal View', select=True), + 'sequence': fields.integer('Sequence'), + 'required': fields.boolean('Required'), + 'readonly': fields.boolean('Readonly'), + } + _order = "sequence" account_journal_column() class account_journal(osv.osv): - _name = "account.journal" - _description = "Journal" - _columns = { - 'name': fields.char('Journal Name', size=64, required=True, translate=True), - 'code': fields.char('Code', size=16), - 'type': fields.selection([('sale','Sale'), ('purchase','Purchase'), ('cash','Cash'), ('general','General'), ('situation','Situation')], 'Type', size=32, required=True), + _name = "account.journal" + _description = "Journal" + _columns = { + 'name': fields.char('Journal Name', size=64, required=True, translate=True), + 'code': fields.char('Code', size=16), + 'type': fields.selection([('sale','Sale'), ('purchase','Purchase'), ('cash','Cash'), ('general','General'), ('situation','Situation')], 'Type', size=32, required=True), - 'type_control_ids': fields.many2many('account.account.type', 'account_journal_type_rel', 'journal_id','type_id', 'Type Controls', domain=[('code','<>','view'), ('code', '<>', 'closed')]), - 'account_control_ids': fields.many2many('account.account', 'account_account_type_rel', 'journal_id','account_id', 'Account', domain=[('type','<>','view'), ('type', '<>', 'closed')]), + 'type_control_ids': fields.many2many('account.account.type', 'account_journal_type_rel', 'journal_id','type_id', 'Type Controls', domain=[('code','<>','view'), ('code', '<>', 'closed')]), + 'account_control_ids': fields.many2many('account.account', 'account_account_type_rel', 'journal_id','account_id', 'Account', domain=[('type','<>','view'), ('type', '<>', 'closed')]), - 'active': fields.boolean('Active'), - 'view_id': fields.many2one('account.journal.view', 'View', required=True, help="Gives the view used when writing or browsing entries in this journal. The view tell Tiny ERP which fields should be visible, required or readonly and in which order. You can create your own view for a faster encoding in each journal."), - 'default_credit_account_id': fields.many2one('account.account', 'Default Credit Account'), - 'default_debit_account_id': fields.many2one('account.account', 'Default Debit Account'), - 'centralisation': fields.boolean('Centralised counterpart', help="Check this box if you want that each entry doesn't create a counterpart but share the same counterpart for each entry of this journal."), - 'update_posted': fields.boolean('Allow Cancelling Entries'), - 'sequence_id': fields.many2one('ir.sequence', 'Entry Sequence', help="The sequence gives the display order for a list of journals", required=True), - 'user_id': fields.many2one('res.users', 'User', help="The responsible user of this journal"), - 'groups_id': fields.many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', 'Groups'), - 'currency': fields.many2one('res.currency', 'Currency', help='The currency used to enter statement'), - } - _defaults = { - 'active': lambda *a: 1, - 'user_id': lambda self,cr,uid,context: uid, - } - def create(self, cr, uid, vals, context={}): - journal_id = super(osv.osv, self).create(cr, uid, vals, context) -# journal_name = self.browse(cr, uid, [journal_id])[0].code -# periods = self.pool.get('account.period') -# ids = periods.search(cr, uid, [('date_stop','>=',time.strftime('%Y-%m-%d'))]) -# for period in periods.browse(cr, uid, ids): -# self.pool.get('account.journal.period').create(cr, uid, { -# 'name': (journal_name or '')+':'+(period.code or ''), -# 'journal_id': journal_id, -# 'period_id': period.id -# }) - return journal_id - def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): - if not args: - args=[] - if not context: - context={} - ids = [] - if name: - ids = self.search(cr, user, [('code','ilike',name)]+ args, limit=limit) - if not ids: - ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit) - return self.name_get(cr, user, ids, context=context) + 'active': fields.boolean('Active'), + 'view_id': fields.many2one('account.journal.view', 'View', required=True, help="Gives the view used when writing or browsing entries in this journal. The view tell Tiny ERP which fields should be visible, required or readonly and in which order. You can create your own view for a faster encoding in each journal."), + 'default_credit_account_id': fields.many2one('account.account', 'Default Credit Account'), + 'default_debit_account_id': fields.many2one('account.account', 'Default Debit Account'), + 'centralisation': fields.boolean('Centralised counterpart', help="Check this box if you want that each entry doesn't create a counterpart but share the same counterpart for each entry of this journal."), + 'update_posted': fields.boolean('Allow Cancelling Entries'), + 'sequence_id': fields.many2one('ir.sequence', 'Entry Sequence', help="The sequence gives the display order for a list of journals", required=True), + 'user_id': fields.many2one('res.users', 'User', help="The responsible user of this journal"), + 'groups_id': fields.many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', 'Groups'), + 'currency': fields.many2one('res.currency', 'Currency', help='The currency used to enter statement'), + } + _defaults = { + 'active': lambda *a: 1, + 'user_id': lambda self,cr,uid,context: uid, + } + def create(self, cr, uid, vals, context={}): + journal_id = super(osv.osv, self).create(cr, uid, vals, context) +# journal_name = self.browse(cr, uid, [journal_id])[0].code +# periods = self.pool.get('account.period') +# ids = periods.search(cr, uid, [('date_stop','>=',time.strftime('%Y-%m-%d'))]) +# for period in periods.browse(cr, uid, ids): +# self.pool.get('account.journal.period').create(cr, uid, { +# 'name': (journal_name or '')+':'+(period.code or ''), +# 'journal_id': journal_id, +# 'period_id': period.id +# }) + return journal_id + def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): + if not args: + args=[] + if not context: + context={} + ids = [] + if name: + ids = self.search(cr, user, [('code','ilike',name)]+ args, limit=limit) + if not ids: + ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit) + return self.name_get(cr, user, ids, context=context) account_journal() class account_fiscalyear(osv.osv): - _name = "account.fiscalyear" - _description = "Fiscal Year" - _columns = { - 'name': fields.char('Fiscal Year', size=64, required=True), - 'code': fields.char('Code', size=6, required=True), - 'date_start': fields.date('Start date', required=True), - 'date_stop': fields.date('End date', required=True), - 'period_ids': fields.one2many('account.period', 'fiscalyear_id', 'Periods'), - 'state': fields.selection([('draft','Draft'), ('done','Done')], 'State', redonly=True), - } + _name = "account.fiscalyear" + _description = "Fiscal Year" + _columns = { + 'name': fields.char('Fiscal Year', size=64, required=True), + 'code': fields.char('Code', size=6, required=True), + 'date_start': fields.date('Start date', required=True), + 'date_stop': fields.date('End date', required=True), + 'period_ids': fields.one2many('account.period', 'fiscalyear_id', 'Periods'), + 'state': fields.selection([('draft','Draft'), ('done','Done')], 'State', redonly=True), + } - _defaults = { - 'state': lambda *a: 'draft', - } - _order = "date_start" - def create_period3(self,cr, uid, ids, context={}): - return self.create_period(cr, uid, ids, context, 3) + _defaults = { + 'state': lambda *a: 'draft', + } + _order = "date_start" + def create_period3(self,cr, uid, ids, context={}): + return self.create_period(cr, uid, ids, context, 3) - def create_period(self,cr, uid, ids, context={}, interval=1): - for fy in self.browse(cr, uid, ids, context): - dt = fy.date_start - ds = mx.DateTime.strptime(fy.date_start, '%Y-%m-%d') - while ds.strftime('%Y-%m-%d')=', dt)]) - if not ids: - if exception: - raise osv.except_osv(_('Error !'), _('No fiscal year defined for this date !\nPlease create one.')) - else: - return False - return ids[0] + def find(self, cr, uid, dt=None, exception=True, context={}): + if not dt: + dt = time.strftime('%Y-%m-%d') + ids = self.search(cr, uid, [('date_start', '<=', dt), ('date_stop', '>=', dt)]) + if not ids: + if exception: + raise osv.except_osv(_('Error !'), _('No fiscal year defined for this date !\nPlease create one.')) + else: + return False + return ids[0] account_fiscalyear() class account_period(osv.osv): - _name = "account.period" - _description = "Account period" - _columns = { - 'name': fields.char('Period Name', size=64, required=True), - 'code': fields.char('Code', size=12), - 'date_start': fields.date('Start of period', required=True, states={'done':[('readonly',True)]}), - 'date_stop': fields.date('End of period', required=True, states={'done':[('readonly',True)]}), - 'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', required=True, states={'done':[('readonly',True)]}, select=True), - 'state': fields.selection([('draft','Draft'), ('done','Done')], 'State', readonly=True) - } - _defaults = { - 'state': lambda *a: 'draft', - } - _order = "date_start" - def next(self, cr, uid, period, step, context={}): - ids = self.search(cr, uid, [('date_start','>',period.date_start)]) - if len(ids)>=step: - return ids[step-1] - return False + _name = "account.period" + _description = "Account period" + _columns = { + 'name': fields.char('Period Name', size=64, required=True), + 'code': fields.char('Code', size=12), + 'date_start': fields.date('Start of period', required=True, states={'done':[('readonly',True)]}), + 'date_stop': fields.date('End of period', required=True, states={'done':[('readonly',True)]}), + 'fiscalyear_id': fields.many2one('account.fiscalyear', 'Fiscal Year', required=True, states={'done':[('readonly',True)]}, select=True), + 'state': fields.selection([('draft','Draft'), ('done','Done')], 'State', readonly=True) + } + _defaults = { + 'state': lambda *a: 'draft', + } + _order = "date_start" + def next(self, cr, uid, period, step, context={}): + ids = self.search(cr, uid, [('date_start','>',period.date_start)]) + if len(ids)>=step: + return ids[step-1] + return False - def find(self, cr, uid, dt=None, context={}): - if not dt: - dt = time.strftime('%Y-%m-%d') + def find(self, cr, uid, dt=None, context={}): + if not dt: + dt = time.strftime('%Y-%m-%d') #CHECKME: shouldn't we check the state of the period? - ids = self.search(cr, uid, [('date_start','<=',dt),('date_stop','>=',dt)]) - if not ids: - raise osv.except_osv(_('Error !'), _('No period defined for this date !\nPlease create a fiscal year.')) - return ids + ids = self.search(cr, uid, [('date_start','<=',dt),('date_stop','>=',dt)]) + if not ids: + raise osv.except_osv(_('Error !'), _('No period defined for this date !\nPlease create a fiscal year.')) + return ids account_period() class account_journal_period(osv.osv): - _name = "account.journal.period" - _description = "Journal - Period" + _name = "account.journal.period" + _description = "Journal - Period" - def _icon_get(self, cr, uid, ids, field_name, arg=None, context={}): - result = {}.fromkeys(ids, 'STOCK_NEW') - for r in self.read(cr, uid, ids, ['state']): - result[r['id']] = { - 'draft': 'STOCK_NEW', - 'printed': 'STOCK_PRINT_PREVIEW', - 'done': 'STOCK_DIALOG_AUTHENTICATION', - }.get(r['state'], 'STOCK_NEW') - return result + def _icon_get(self, cr, uid, ids, field_name, arg=None, context={}): + result = {}.fromkeys(ids, 'STOCK_NEW') + for r in self.read(cr, uid, ids, ['state']): + result[r['id']] = { + 'draft': 'STOCK_NEW', + 'printed': 'STOCK_PRINT_PREVIEW', + 'done': 'STOCK_DIALOG_AUTHENTICATION', + }.get(r['state'], 'STOCK_NEW') + return result - _columns = { - 'name': fields.char('Journal-Period Name', size=64, required=True), - 'journal_id': fields.many2one('account.journal', 'Journal', required=True, ondelete="cascade"), - 'period_id': fields.many2one('account.period', 'Period', required=True, ondelete="cascade"), - 'icon': fields.function(_icon_get, method=True, string='Icon', type='string'), - 'active': fields.boolean('Active', required=True), - 'state': fields.selection([('draft','Draft'), ('printed','Printed'), ('done','Done')], 'State', required=True, readonly=True) - } + _columns = { + 'name': fields.char('Journal-Period Name', size=64, required=True), + 'journal_id': fields.many2one('account.journal', 'Journal', required=True, ondelete="cascade"), + 'period_id': fields.many2one('account.period', 'Period', required=True, ondelete="cascade"), + 'icon': fields.function(_icon_get, method=True, string='Icon', type='string'), + 'active': fields.boolean('Active', required=True), + 'state': fields.selection([('draft','Draft'), ('printed','Printed'), ('done','Done')], 'State', required=True, readonly=True) + } - def _check(self, cr, uid, ids, context={}): - for obj in self.browse(cr, uid, ids, context): - cr.execute('select * from account_move_line where journal_id=%d and period_id=%d limit 1', (obj.journal_id.id, obj.period_id.id)) - res = cr.fetchall() - if res: - raise osv.except_osv(_('Error !'), _('You can not modify/delete a journal with entries for this period !')) - return True + def _check(self, cr, uid, ids, context={}): + for obj in self.browse(cr, uid, ids, context): + cr.execute('select * from account_move_line where journal_id=%d and period_id=%d limit 1', (obj.journal_id.id, obj.period_id.id)) + res = cr.fetchall() + if res: + raise osv.except_osv(_('Error !'), _('You can not modify/delete a journal with entries for this period !')) + return True - def write(self, cr, uid, ids, vals, context={}): - self._check(cr, uid, ids, context) - return super(account_journal_period, self).write(cr, uid, ids, vals, context) + def write(self, cr, uid, ids, vals, context={}): + self._check(cr, uid, ids, context) + return super(account_journal_period, self).write(cr, uid, ids, vals, context) - def create(self, cr, uid, vals, context={}): - period_id=vals.get('period_id',False) - if period_id: - period = self.pool.get('account.period').browse(cr, uid,period_id) - vals['state']=period.state - return super(account_journal_period, self).create(cr, uid, vals, context) + def create(self, cr, uid, vals, context={}): + period_id=vals.get('period_id',False) + if period_id: + period = self.pool.get('account.period').browse(cr, uid,period_id) + vals['state']=period.state + return super(account_journal_period, self).create(cr, uid, vals, context) - def unlink(self, cr, uid, ids, context={}): - self._check(cr, uid, ids, context) - return super(account_journal_period, self).unlink(cr, uid, ids, context) + def unlink(self, cr, uid, ids, context={}): + self._check(cr, uid, ids, context) + return super(account_journal_period, self).unlink(cr, uid, ids, context) - _defaults = { - 'state': lambda *a: 'draft', - 'active': lambda *a: True, - } - _order = "period_id" + _defaults = { + 'state': lambda *a: 'draft', + 'active': lambda *a: True, + } + _order = "period_id" account_journal_period() class account_fiscalyear(osv.osv): - _inherit = "account.fiscalyear" - _description = "Fiscal Year" - _columns = { - 'start_journal_period_id':fields.many2one('account.journal.period','New Entries Journal'), - 'end_journal_period_id':fields.many2one('account.journal.period','End of Year Entries Journal', readonly=True), - } + _inherit = "account.fiscalyear" + _description = "Fiscal Year" + _columns = { + 'start_journal_period_id':fields.many2one('account.journal.period','New Entries Journal'), + 'end_journal_period_id':fields.many2one('account.journal.period','End of Year Entries Journal', readonly=True), + } account_fiscalyear() #---------------------------------------------------------- # Entries #---------------------------------------------------------- class account_move(osv.osv): - _name = "account.move" - _description = "Account Entry" + _name = "account.move" + _description = "Account Entry" - def name_get(self, cursor, user, ids, context=None): - if not len(ids): - return [] - res=[] - data_move = self.pool.get('account.move').browse(cursor,user,ids) - for move in data_move: - if move.state=='draft': - name = '*' + move.name - else: - name = move.name - res.append((move.id, name)) - return res + def name_get(self, cursor, user, ids, context=None): + if not len(ids): + return [] + res=[] + data_move = self.pool.get('account.move').browse(cursor,user,ids) + for move in data_move: + if move.state=='draft': + name = '*' + move.name + else: + name = move.name + res.append((move.id, name)) + return res - def _get_period(self, cr, uid, context): - periods = self.pool.get('account.period').find(cr, uid) - if periods: - return periods[0] - else: - return False - _columns = { - 'name': fields.char('Entry Name', size=64, required=True), - 'ref': fields.char('Ref', size=64), - 'period_id': fields.many2one('account.period', 'Period', required=True, states={'posted':[('readonly',True)]}), - 'journal_id': fields.many2one('account.journal', 'Journal', required=True, states={'posted':[('readonly',True)]}), - 'state': fields.selection([('draft','Draft'), ('posted','Posted')], 'State', required=True, readonly=True), - 'line_id': fields.one2many('account.move.line', 'move_id', 'Entries', states={'posted':[('readonly',True)]}), - } - _defaults = { - 'state': lambda *a: 'draft', - 'period_id': _get_period, - } + def _get_period(self, cr, uid, context): + periods = self.pool.get('account.period').find(cr, uid) + if periods: + return periods[0] + else: + return False + _columns = { + 'name': fields.char('Entry Name', size=64, required=True), + 'ref': fields.char('Ref', size=64), + 'period_id': fields.many2one('account.period', 'Period', required=True, states={'posted':[('readonly',True)]}), + 'journal_id': fields.many2one('account.journal', 'Journal', required=True, states={'posted':[('readonly',True)]}), + 'state': fields.selection([('draft','Draft'), ('posted','Posted')], 'State', required=True, readonly=True), + 'line_id': fields.one2many('account.move.line', 'move_id', 'Entries', states={'posted':[('readonly',True)]}), + } + _defaults = { + 'state': lambda *a: 'draft', + 'period_id': _get_period, + } - def _check_centralisation(self, cursor, user, ids): - for move in self.browse(cursor, user, ids): - if move.journal_id.centralisation: - move_ids = self.search(cursor, user, [ - ('period_id', '=', move.period_id.id), - ('journal_id', '=', move.journal_id.id), - ]) - if len(move_ids) > 1: - return False - return True + def _check_centralisation(self, cursor, user, ids): + for move in self.browse(cursor, user, ids): + if move.journal_id.centralisation: + move_ids = self.search(cursor, user, [ + ('period_id', '=', move.period_id.id), + ('journal_id', '=', move.journal_id.id), + ]) + if len(move_ids) > 1: + return False + return True - def _check_period_journal(self, cursor, user, ids): - for move in self.browse(cursor, user, ids): - for line in move.line_id: - if line.period_id.id != move.period_id.id: - return False - if line.journal_id.id != move.journal_id.id: - return False - return True + def _check_period_journal(self, cursor, user, ids): + for move in self.browse(cursor, user, ids): + for line in move.line_id: + if line.period_id.id != move.period_id.id: + return False + if line.journal_id.id != move.journal_id.id: + return False + return True - _constraints = [ - (_check_centralisation, - 'You can not create more than one move per period on centralized journal', - ['journal_id']), - (_check_period_journal, - 'You can not create entries on different period/journal in the same move', - ['line_id']), - ] - def post(self, cr, uid, ids, context=None): - if self.validate(cr, uid, ids, context) and len(ids): - cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('posted',)) - else: - raise osv.except_osv(_('Integrity Error !'), _('You can not validate a non balanced entry !')) - return True + _constraints = [ + (_check_centralisation, + 'You can not create more than one move per period on centralized journal', + ['journal_id']), + (_check_period_journal, + 'You can not create entries on different period/journal in the same move', + ['line_id']), + ] + def post(self, cr, uid, ids, context=None): + if self.validate(cr, uid, ids, context) and len(ids): + cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('posted',)) + else: + raise osv.except_osv(_('Integrity Error !'), _('You can not validate a non balanced entry !')) + return True - def button_validate(self, cursor, user, ids, context=None): - return self.post(cursor, user, ids, context=context) + def button_validate(self, cursor, user, ids, context=None): + return self.post(cursor, user, ids, context=context) - def button_cancel(self, cr, uid, ids, context={}): - for line in self.browse(cr, uid, ids, context): - if not line.journal_id.update_posted: - raise osv.except_osv(_('Error !'), _('You can not modify a posted entry of this journal !')) - if len(ids): - cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('draft',)) - return True + def button_cancel(self, cr, uid, ids, context={}): + for line in self.browse(cr, uid, ids, context): + if not line.journal_id.update_posted: + raise osv.except_osv(_('Error !'), _('You can not modify a posted entry of this journal !')) + if len(ids): + cr.execute('update account_move set state=%s where id in ('+','.join(map(str,ids))+')', ('draft',)) + return True - def write(self, cr, uid, ids, vals, context={}): - c = context.copy() - c['novalidate'] = True - result = super(osv.osv, self).write(cr, uid, ids, vals, c) - self.validate(cr, uid, ids, context) - return result + def write(self, cr, uid, ids, vals, context={}): + c = context.copy() + c['novalidate'] = True + result = super(osv.osv, self).write(cr, uid, ids, vals, c) + self.validate(cr, uid, ids, context) + return result - # - # TODO: Check if period is closed ! - # - def create(self, cr, uid, vals, context={}): - if 'line_id' in vals: - if 'journal_id' in vals: - for l in vals['line_id']: - if not l[0]: - l[2]['journal_id'] = vals['journal_id'] - context['journal_id'] = vals['journal_id'] - if 'period_id' in vals: - for l in vals['line_id']: - if not l[0]: - l[2]['period_id'] = vals['period_id'] - context['period_id'] = vals['period_id'] - else: - default_period = self._get_period(cr, uid, context) - for l in vals['line_id']: - if not l[0]: - l[2]['period_id'] = default_period - context['period_id'] = default_period + # + # TODO: Check if period is closed ! + # + def create(self, cr, uid, vals, context={}): + if 'line_id' in vals: + if 'journal_id' in vals: + for l in vals['line_id']: + if not l[0]: + l[2]['journal_id'] = vals['journal_id'] + context['journal_id'] = vals['journal_id'] + if 'period_id' in vals: + for l in vals['line_id']: + if not l[0]: + l[2]['period_id'] = vals['period_id'] + context['period_id'] = vals['period_id'] + else: + default_period = self._get_period(cr, uid, context) + for l in vals['line_id']: + if not l[0]: + l[2]['period_id'] = default_period + context['period_id'] = default_period - if not 'name' in vals: - journal = self.pool.get('account.journal').browse(cr, uid, context.get('journal_id', vals.get('journal_id', False))) - if journal.sequence_id: - vals['name'] = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) - else: - raise osv.except_osv(_('Error'), _('No sequence defined in the journal !')) - if 'line_id' in vals: - c = context.copy() - c['novalidate'] = True - result = super(account_move, self).create(cr, uid, vals, c) - self.validate(cr, uid, [result], context) - else: - result = super(account_move, self).create(cr, uid, vals, context) - return result + if not 'name' in vals: + journal = self.pool.get('account.journal').browse(cr, uid, context.get('journal_id', vals.get('journal_id', False))) + if journal.sequence_id: + vals['name'] = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) + else: + raise osv.except_osv(_('Error'), _('No sequence defined in the journal !')) + if 'line_id' in vals: + c = context.copy() + c['novalidate'] = True + result = super(account_move, self).create(cr, uid, vals, c) + self.validate(cr, uid, [result], context) + else: + result = super(account_move, self).create(cr, uid, vals, context) + return result - def unlink(self, cr, uid, ids, context={}, check=True): - toremove = [] - for move in self.browse(cr, uid, ids, context): - if move['state'] <> 'draft': - raise osv.except_osv(_('UserError'), - _('You can not delete posted movement: "%s"!') % \ - move['name']) - line_ids = map(lambda x: x.id, move.line_id) - context['journal_id'] = move.journal_id.id - context['period_id'] = move.period_id.id - self.pool.get('account.move.line')._update_check(cr, uid, line_ids, context) - toremove.append(move.id) - result = super(account_move, self).unlink(cr, uid, toremove, context) - return result + def unlink(self, cr, uid, ids, context={}, check=True): + toremove = [] + for move in self.browse(cr, uid, ids, context): + if move['state'] <> 'draft': + raise osv.except_osv(_('UserError'), + _('You can not delete posted movement: "%s"!') % \ + move['name']) + line_ids = map(lambda x: x.id, move.line_id) + context['journal_id'] = move.journal_id.id + context['period_id'] = move.period_id.id + self.pool.get('account.move.line')._update_check(cr, uid, line_ids, context) + toremove.append(move.id) + result = super(account_move, self).unlink(cr, uid, toremove, context) + return result - def _compute_balance(self, cr, uid, id, context={}): - move = self.browse(cr, uid, [id])[0] - amount = 0 - for line in move.line_id: - amount+= (line.debit - line.credit) - return amount + def _compute_balance(self, cr, uid, id, context={}): + move = self.browse(cr, uid, [id])[0] + amount = 0 + for line in move.line_id: + amount+= (line.debit - line.credit) + return amount - def _centralise(self, cr, uid, move, mode): - if mode=='credit': - account_id = move.journal_id.default_debit_account_id.id - mode2 = 'debit' - if not account_id: - raise osv.except_osv(_('UserError'), - _('There is no default default debit account defined \n' \ - 'on journal "%s"') % move.journal_id.name) - else: - account_id = move.journal_id.default_credit_account_id.id - mode2 = 'credit' - if not account_id: - raise osv.except_osv(_('UserError'), - _('There is no default default credit account defined \n' \ - 'on journal "%s"') % move.journal_id.name) + def _centralise(self, cr, uid, move, mode): + if mode=='credit': + account_id = move.journal_id.default_debit_account_id.id + mode2 = 'debit' + if not account_id: + raise osv.except_osv(_('UserError'), + _('There is no default default debit account defined \n' \ + 'on journal "%s"') % move.journal_id.name) + else: + account_id = move.journal_id.default_credit_account_id.id + mode2 = 'credit' + if not account_id: + raise osv.except_osv(_('UserError'), + _('There is no default default credit account defined \n' \ + 'on journal "%s"') % move.journal_id.name) - # find the first line of this move with the current mode - # or create it if it doesn't exist - cr.execute('select id from account_move_line where move_id=%d and centralisation=%s limit 1', (move.id, mode)) - res = cr.fetchone() - if res: - line_id = res[0] - else: - line_id = self.pool.get('account.move.line').create(cr, uid, { - 'name': 'Centralisation '+mode, - 'centralisation': mode, - 'account_id': account_id, - 'move_id': move.id, - 'journal_id': move.journal_id.id, - 'period_id': move.period_id.id, - 'date': move.period_id.date_stop, - 'debit': 0.0, - 'credit': 0.0, - }, {'journal_id': move.journal_id.id, 'period_id': move.period_id.id}) + # find the first line of this move with the current mode + # or create it if it doesn't exist + cr.execute('select id from account_move_line where move_id=%d and centralisation=%s limit 1', (move.id, mode)) + res = cr.fetchone() + if res: + line_id = res[0] + else: + line_id = self.pool.get('account.move.line').create(cr, uid, { + 'name': 'Centralisation '+mode, + 'centralisation': mode, + 'account_id': account_id, + 'move_id': move.id, + 'journal_id': move.journal_id.id, + 'period_id': move.period_id.id, + 'date': move.period_id.date_stop, + 'debit': 0.0, + 'credit': 0.0, + }, {'journal_id': move.journal_id.id, 'period_id': move.period_id.id}) - # find the first line of this move with the other mode - # so that we can exclude it from our calculation - cr.execute('select id from account_move_line where move_id=%d and centralisation=%s limit 1', (move.id, mode2)) - res = cr.fetchone() - if res: - line_id2 = res[0] - else: - line_id2 = 0 + # find the first line of this move with the other mode + # so that we can exclude it from our calculation + cr.execute('select id from account_move_line where move_id=%d and centralisation=%s limit 1', (move.id, mode2)) + res = cr.fetchone() + if res: + line_id2 = res[0] + else: + line_id2 = 0 - cr.execute('select sum('+mode+') from account_move_line where move_id=%d and id<>%d', (move.id, line_id2)) - result = cr.fetchone()[0] or 0.0 - cr.execute('update account_move_line set '+mode2+'=%f where id=%d', (result, line_id)) - return True + cr.execute('select sum('+mode+') from account_move_line where move_id=%d and id<>%d', (move.id, line_id2)) + result = cr.fetchone()[0] or 0.0 + cr.execute('update account_move_line set '+mode2+'=%f where id=%d', (result, line_id)) + return True - # - # Validate a balanced move. If it is a centralised journal, create a move. - # - def validate(self, cr, uid, ids, context={}): - ok = True - for move in self.browse(cr, uid, ids, context): - journal = move.journal_id - amount = 0 - line_ids = [] - line_draft_ids = [] - company_id=None - for line in move.line_id: - amount += line.debit - line.credit - line_ids.append(line.id) - if line.state=='draft': - line_draft_ids.append(line.id) + # + # Validate a balanced move. If it is a centralised journal, create a move. + # + def validate(self, cr, uid, ids, context={}): + ok = True + for move in self.browse(cr, uid, ids, context): + journal = move.journal_id + amount = 0 + line_ids = [] + line_draft_ids = [] + company_id=None + for line in move.line_id: + amount += line.debit - line.credit + line_ids.append(line.id) + if line.state=='draft': + line_draft_ids.append(line.id) - if not company_id: - company_id = line.account_id.company_id.id - if not company_id == line.account_id.company_id.id: - raise osv.except_osv(_('Error'), _('Couldn\'t create move between different companies')) + if not company_id: + company_id = line.account_id.company_id.id + if not company_id == line.account_id.company_id.id: + raise osv.except_osv(_('Error'), _('Couldn\'t create move between different companies')) - if line.account_id.currency_id: - if line.account_id.currency_id.id != line.currency_id.id and (line.account_id.currency_id.id != line.account_id.company_id.currency_id.id or line.currency_id): - raise osv.except_osv(_('Error'), _('Couldn\'t create move with currency different than the secondary currency of the account')) + if line.account_id.currency_id: + if line.account_id.currency_id.id != line.currency_id.id and (line.account_id.currency_id.id != line.account_id.company_id.currency_id.id or line.currency_id): + raise osv.except_osv(_('Error'), _('Couldn\'t create move with currency different than the secondary currency of the account')) - if abs(amount) < 0.0001: - if not len(line_draft_ids): - continue - self.pool.get('account.move.line').write(cr, uid, line_draft_ids, { - 'journal_id': move.journal_id.id, - 'period_id': move.period_id.id, - 'state': 'valid' - }, context, check=False) - todo = [] - account = {} - account2 = {} - if journal.type not in ('purchase','sale'): - continue + if abs(amount) < 0.0001: + if not len(line_draft_ids): + continue + self.pool.get('account.move.line').write(cr, uid, line_draft_ids, { + 'journal_id': move.journal_id.id, + 'period_id': move.period_id.id, + 'state': 'valid' + }, context, check=False) + todo = [] + account = {} + account2 = {} + if journal.type not in ('purchase','sale'): + continue - for line in move.line_id: - if move.journal_id.type == 'sale': - if line.debit: - field_base = 'ref_' - key = 'account_paid_id' - else: - field_base = '' - key = 'account_collected_id' - else: - if line.debit: - field_base = '' - key = 'account_collected_id' - else: - field_base = 'ref_' - key = 'account_paid_id' - if line.account_id.tax_ids: - code = amount = False - for tax in line.account_id.tax_ids: - if tax.tax_code_id: - acc = getattr(tax, key).id - account[acc] = (getattr(tax, - field_base + 'tax_code_id').id, - getattr(tax, field_base + 'tax_sign')) - account2[(acc,getattr(tax, - field_base + 'tax_code_id').id)] = (getattr(tax, - field_base + 'tax_code_id').id, - getattr(tax, field_base + 'tax_sign')) - code = getattr(tax, field_base + 'base_code_id').id - amount = getattr(tax, field_base+'base_sign') * \ - (line.debit + line.credit) - break - if code and not (line.tax_code_id or line.tax_amount): - self.pool.get('account.move.line').write(cr, uid, - [line.id], { - 'tax_code_id': code, - 'tax_amount': amount - }, context=context, check=False) - else: - todo.append(line) - for line in todo: - code = amount = 0 - key = (line.account_id.id, line.tax_code_id.id) - if key in account2: - code = account2[key][0] - amount = account2[key][1] * (line.debit + line.credit) - elif line.account_id.id in account: - code = account[line.account_id.id][0] - amount = account[line.account_id.id][1] * (line.debit + line.credit) - if (code or amount) and not (line.tax_code_id or line.tax_amount): - self.pool.get('account.move.line').write(cr, uid, [line.id], { - 'tax_code_id': code, - 'tax_amount': amount - }, context, check=False) - # - # Compute VAT - # - continue - if journal.centralisation: - self._centralise(cr, uid, move, 'debit') - self._centralise(cr, uid, move, 'credit') - self.pool.get('account.move.line').write(cr, uid, line_draft_ids, { - 'state': 'valid' - }, context, check=False) - continue - else: - self.pool.get('account.move.line').write(cr, uid, line_ids, { - 'journal_id': move.journal_id.id, - 'period_id': move.period_id.id, - #'tax_code_id': False, - #'tax_amount': False, - 'state': 'draft' - }, context, check=False) - ok = False - return ok + for line in move.line_id: + if move.journal_id.type == 'sale': + if line.debit: + field_base = 'ref_' + key = 'account_paid_id' + else: + field_base = '' + key = 'account_collected_id' + else: + if line.debit: + field_base = '' + key = 'account_collected_id' + else: + field_base = 'ref_' + key = 'account_paid_id' + if line.account_id.tax_ids: + code = amount = False + for tax in line.account_id.tax_ids: + if tax.tax_code_id: + acc = getattr(tax, key).id + account[acc] = (getattr(tax, + field_base + 'tax_code_id').id, + getattr(tax, field_base + 'tax_sign')) + account2[(acc,getattr(tax, + field_base + 'tax_code_id').id)] = (getattr(tax, + field_base + 'tax_code_id').id, + getattr(tax, field_base + 'tax_sign')) + code = getattr(tax, field_base + 'base_code_id').id + amount = getattr(tax, field_base+'base_sign') * \ + (line.debit + line.credit) + break + if code and not (line.tax_code_id or line.tax_amount): + self.pool.get('account.move.line').write(cr, uid, + [line.id], { + 'tax_code_id': code, + 'tax_amount': amount + }, context=context, check=False) + else: + todo.append(line) + for line in todo: + code = amount = 0 + key = (line.account_id.id, line.tax_code_id.id) + if key in account2: + code = account2[key][0] + amount = account2[key][1] * (line.debit + line.credit) + elif line.account_id.id in account: + code = account[line.account_id.id][0] + amount = account[line.account_id.id][1] * (line.debit + line.credit) + if (code or amount) and not (line.tax_code_id or line.tax_amount): + self.pool.get('account.move.line').write(cr, uid, [line.id], { + 'tax_code_id': code, + 'tax_amount': amount + }, context, check=False) + # + # Compute VAT + # + continue + if journal.centralisation: + self._centralise(cr, uid, move, 'debit') + self._centralise(cr, uid, move, 'credit') + self.pool.get('account.move.line').write(cr, uid, line_draft_ids, { + 'state': 'valid' + }, context, check=False) + continue + else: + self.pool.get('account.move.line').write(cr, uid, line_ids, { + 'journal_id': move.journal_id.id, + 'period_id': move.period_id.id, + #'tax_code_id': False, + #'tax_amount': False, + 'state': 'draft' + }, context, check=False) + ok = False + return ok account_move() class account_move_reconcile(osv.osv): - _name = "account.move.reconcile" - _description = "Account Reconciliation" - _columns = { - 'name': fields.char('Name', size=64, required=True), - 'type': fields.char('Type', size=16, required=True), - 'line_id': fields.one2many('account.move.line', 'reconcile_id', 'Entry lines'), - 'line_partial_ids': fields.one2many('account.move.line', 'reconcile_partial_id', 'Partial Entry lines'), - 'create_date': fields.date('Creation date', readonly=True), - } - _defaults = { - 'name': lambda self,cr,uid,ctx={}: self.pool.get('ir.sequence').get(cr, uid, 'account.reconcile') or '/', - } - def reconcile_partial_check(self, cr, uid, ids, type='auto', context={}): - for rec in self.pool.get('account.move.reconcile').browse(cr, uid, ids): - total = 0.0 - for line in rec.line_partial_ids: - total += (line.debit or 0.0) - (line.credit or 0.0) - if not total: - self.write(cr,uid, map(lambda x: x.id, rec.line_partial_ids), {'reconcile_id': rec.id }) - for line in rec.line_partial_ids: - total += (line.debit or 0.0) - (line.credit or 0.0) - return True - def name_get(self, cr, uid, ids, context=None): - result = {} - for r in self.browse(cr, uid, ids, context): - total = reduce(lambda y,t: (t.debit or 0.0) - (t.credit or 0.0) + y, r.line_partial_ids, 0.0) - if total: - result[r.id] = '%s (%.2f)' % (r.name, total) - else: - result[r.id] = r.name - return result + _name = "account.move.reconcile" + _description = "Account Reconciliation" + _columns = { + 'name': fields.char('Name', size=64, required=True), + 'type': fields.char('Type', size=16, required=True), + 'line_id': fields.one2many('account.move.line', 'reconcile_id', 'Entry lines'), + 'line_partial_ids': fields.one2many('account.move.line', 'reconcile_partial_id', 'Partial Entry lines'), + 'create_date': fields.date('Creation date', readonly=True), + } + _defaults = { + 'name': lambda self,cr,uid,ctx={}: self.pool.get('ir.sequence').get(cr, uid, 'account.reconcile') or '/', + } + def reconcile_partial_check(self, cr, uid, ids, type='auto', context={}): + for rec in self.pool.get('account.move.reconcile').browse(cr, uid, ids): + total = 0.0 + for line in rec.line_partial_ids: + total += (line.debit or 0.0) - (line.credit or 0.0) + if not total: + self.write(cr,uid, map(lambda x: x.id, rec.line_partial_ids), {'reconcile_id': rec.id }) + for line in rec.line_partial_ids: + total += (line.debit or 0.0) - (line.credit or 0.0) + return True + def name_get(self, cr, uid, ids, context=None): + result = {} + for r in self.browse(cr, uid, ids, context): + total = reduce(lambda y,t: (t.debit or 0.0) - (t.credit or 0.0) + y, r.line_partial_ids, 0.0) + if total: + result[r.id] = '%s (%.2f)' % (r.name, total) + else: + result[r.id] = r.name + return result account_move_reconcile() #---------------------------------------------------------- @@ -944,382 +944,382 @@ a documenter child_depend: la taxe depend des taxes filles """ class account_tax_code(osv.osv): - """ - A code for the tax object. + """ + A code for the tax object. - This code is used for some tax declarations. - """ - def _sum(self, cr, uid, ids, name, args, context, where =''): - ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)]) - acc_set = ",".join(map(str, ids2)) - if context.get('based_on', 'invoices') == 'payments': - cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \ - FROM account_move_line AS line, \ - account_move AS move \ - LEFT JOIN account_invoice invoice ON \ - (invoice.move_id = move.id) \ - WHERE line.tax_code_id in ('+acc_set+') '+where+' \ - AND move.id = line.move_id \ - AND ((invoice.state = \'paid\') \ - OR (invoice.id IS NULL)) \ - GROUP BY line.tax_code_id') - else: - cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \ - FROM account_move_line AS line \ - WHERE line.tax_code_id in ('+acc_set+') '+where+' \ - GROUP BY line.tax_code_id') - res=dict(cr.fetchall()) - for record in self.browse(cr, uid, ids, context): - def _rec_get(record): - amount = res.get(record.id, 0.0) - for rec in record.child_ids: - amount += _rec_get(rec) * rec.sign - return amount - res[record.id] = round(_rec_get(record), 2) - return res + This code is used for some tax declarations. + """ + def _sum(self, cr, uid, ids, name, args, context, where =''): + ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)]) + acc_set = ",".join(map(str, ids2)) + if context.get('based_on', 'invoices') == 'payments': + cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \ + FROM account_move_line AS line, \ + account_move AS move \ + LEFT JOIN account_invoice invoice ON \ + (invoice.move_id = move.id) \ + WHERE line.tax_code_id in ('+acc_set+') '+where+' \ + AND move.id = line.move_id \ + AND ((invoice.state = \'paid\') \ + OR (invoice.id IS NULL)) \ + GROUP BY line.tax_code_id') + else: + cr.execute('SELECT line.tax_code_id, sum(line.tax_amount) \ + FROM account_move_line AS line \ + WHERE line.tax_code_id in ('+acc_set+') '+where+' \ + GROUP BY line.tax_code_id') + res=dict(cr.fetchall()) + for record in self.browse(cr, uid, ids, context): + def _rec_get(record): + amount = res.get(record.id, 0.0) + for rec in record.child_ids: + amount += _rec_get(rec) * rec.sign + return amount + res[record.id] = round(_rec_get(record), 2) + return res - def _sum_period(self, cr, uid, ids, name, args, context): - if not 'period_id' in context: - period_id = self.pool.get('account.period').find(cr, uid) - if not len(period_id): - return dict.fromkeys(ids, 0.0) - period_id = period_id[0] - else: - period_id = context['period_id'] - return self._sum(cr, uid, ids, name, args, context, - where=' and line.period_id='+str(period_id)) + def _sum_period(self, cr, uid, ids, name, args, context): + if not 'period_id' in context: + period_id = self.pool.get('account.period').find(cr, uid) + if not len(period_id): + return dict.fromkeys(ids, 0.0) + period_id = period_id[0] + else: + period_id = context['period_id'] + return self._sum(cr, uid, ids, name, args, context, + where=' and line.period_id='+str(period_id)) - _name = 'account.tax.code' - _description = 'Tax Code' - _columns = { - 'name': fields.char('Tax Case Name', size=64, required=True), - 'code': fields.char('Case Code', size=16), - 'info': fields.text('Description'), - 'sum': fields.function(_sum, method=True, string="Year Sum"), - 'sum_period': fields.function(_sum_period, method=True, string="Period Sum"), - 'parent_id': fields.many2one('account.tax.code', 'Parent Code', select=True), - 'child_ids': fields.one2many('account.tax.code', 'parent_id', 'Childs Codes'), - 'line_ids': fields.one2many('account.move.line', 'tax_code_id', 'Lines'), - 'company_id': fields.many2one('res.company', 'Company', required=True), - 'sign': fields.float('Sign for parent', required=True), - } + _name = 'account.tax.code' + _description = 'Tax Code' + _columns = { + 'name': fields.char('Tax Case Name', size=64, required=True), + 'code': fields.char('Case Code', size=16), + 'info': fields.text('Description'), + 'sum': fields.function(_sum, method=True, string="Year Sum"), + 'sum_period': fields.function(_sum_period, method=True, string="Period Sum"), + 'parent_id': fields.many2one('account.tax.code', 'Parent Code', select=True), + 'child_ids': fields.one2many('account.tax.code', 'parent_id', 'Childs Codes'), + 'line_ids': fields.one2many('account.move.line', 'tax_code_id', 'Lines'), + 'company_id': fields.many2one('res.company', 'Company', required=True), + 'sign': fields.float('Sign for parent', required=True), + } - def name_get(self, cr, uid, ids, context=None): - if not len(ids): - return [] - if isinstance(ids, (int, long)): - ids = [ids] - reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write') - return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \ - for x in reads] + def name_get(self, cr, uid, ids, context=None): + if not len(ids): + return [] + if isinstance(ids, (int, long)): + ids = [ids] + reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write') + return [(x['id'], (x['code'] and x['code'] + ' - ' or '') + x['name']) \ + for x in reads] - def _default_company(self, cr, uid, context={}): - user = self.pool.get('res.users').browse(cr, uid, uid, context=context) - if user.company_id: - return user.company_id.id - return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] - _defaults = { - 'company_id': _default_company, - 'sign': lambda *args: 1.0, - } - def _check_recursion(self, cr, uid, ids): - level = 100 - while len(ids): - cr.execute('select distinct parent_id from account_tax_code where id in ('+','.join(map(str,ids))+')') - ids = filter(None, map(lambda x:x[0], cr.fetchall())) - if not level: - return False - level -= 1 - return True + def _default_company(self, cr, uid, context={}): + user = self.pool.get('res.users').browse(cr, uid, uid, context=context) + if user.company_id: + return user.company_id.id + return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] + _defaults = { + 'company_id': _default_company, + 'sign': lambda *args: 1.0, + } + def _check_recursion(self, cr, uid, ids): + level = 100 + while len(ids): + cr.execute('select distinct parent_id from account_tax_code where id in ('+','.join(map(str,ids))+')') + ids = filter(None, map(lambda x:x[0], cr.fetchall())) + if not level: + return False + level -= 1 + return True - _constraints = [ - (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id']) - ] - _order = 'code,name' + _constraints = [ + (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id']) + ] + _order = 'code,name' account_tax_code() class account_tax(osv.osv): - """ - A tax object. + """ + A tax object. - Type: percent, fixed, none, code - PERCENT: tax = price * amount - FIXED: tax = price + amount - NONE: no tax line - CODE: execute python code. localcontext = {'price_unit':pu, 'address':address_object} - return result in the context - Ex: result=round(price_unit*0.21,4) - """ - _name = 'account.tax' - _description = 'Tax' - _columns = { - 'name': fields.char('Tax Name', size=64, required=True, help="This name will be used to be displayed on reports"), - 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the taxes lines from the lowest sequences to the higher ones. The order is important if you have a tax that have several tax childs. In this case, the evaluation order is important."), - 'amount': fields.float('Amount', required=True, digits=(14,4)), - 'active': fields.boolean('Active'), - 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code')], 'Tax Type', required=True), - 'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True), - 'domain':fields.char('Domain', size=32, help="This field is only used if you develop your own module allowing developpers to create specific taxes in a custom domain."), - 'account_collected_id':fields.many2one('account.account', 'Invoice Tax Account'), - 'account_paid_id':fields.many2one('account.account', 'Refund Tax Account'), - 'parent_id':fields.many2one('account.tax', 'Parent Tax Account', select=True), - 'child_ids':fields.one2many('account.tax', 'parent_id', 'Childs Tax Account'), - 'child_depend':fields.boolean('Tax on Childs', help="Indicate if the tax computation is based on the value computed for the computation of child taxes or based on the total amount."), - 'python_compute':fields.text('Python Code'), - 'python_compute_inv':fields.text('Python Code (reverse)'), - 'python_applicable':fields.text('Python Code'), - 'tax_group': fields.selection([('vat','VAT'),('other','Other')], 'Tax Group', help="If a default tax if given in the partner it only override taxes from account (or product) of the same group."), + Type: percent, fixed, none, code + PERCENT: tax = price * amount + FIXED: tax = price + amount + NONE: no tax line + CODE: execute python code. localcontext = {'price_unit':pu, 'address':address_object} + return result in the context + Ex: result=round(price_unit*0.21,4) + """ + _name = 'account.tax' + _description = 'Tax' + _columns = { + 'name': fields.char('Tax Name', size=64, required=True, help="This name will be used to be displayed on reports"), + 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the taxes lines from the lowest sequences to the higher ones. The order is important if you have a tax that have several tax childs. In this case, the evaluation order is important."), + 'amount': fields.float('Amount', required=True, digits=(14,4)), + 'active': fields.boolean('Active'), + 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code')], 'Tax Type', required=True), + 'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True), + 'domain':fields.char('Domain', size=32, help="This field is only used if you develop your own module allowing developpers to create specific taxes in a custom domain."), + 'account_collected_id':fields.many2one('account.account', 'Invoice Tax Account'), + 'account_paid_id':fields.many2one('account.account', 'Refund Tax Account'), + 'parent_id':fields.many2one('account.tax', 'Parent Tax Account', select=True), + 'child_ids':fields.one2many('account.tax', 'parent_id', 'Childs Tax Account'), + 'child_depend':fields.boolean('Tax on Childs', help="Indicate if the tax computation is based on the value computed for the computation of child taxes or based on the total amount."), + 'python_compute':fields.text('Python Code'), + 'python_compute_inv':fields.text('Python Code (reverse)'), + 'python_applicable':fields.text('Python Code'), + 'tax_group': fields.selection([('vat','VAT'),('other','Other')], 'Tax Group', help="If a default tax if given in the partner it only override taxes from account (or product) of the same group."), - # - # Fields used for the VAT declaration - # - 'base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."), - 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."), - 'base_sign': fields.float('Base Code Sign', help="Usualy 1 or -1."), - 'tax_sign': fields.float('Tax Code Sign', help="Usualy 1 or -1."), + # + # Fields used for the VAT declaration + # + 'base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."), + 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."), + 'base_sign': fields.float('Base Code Sign', help="Usualy 1 or -1."), + 'tax_sign': fields.float('Tax Code Sign', help="Usualy 1 or -1."), - # Same fields for refund invoices + # Same fields for refund invoices - 'ref_base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."), - 'ref_tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."), - 'ref_base_sign': fields.float('Base Code Sign', help="Usualy 1 or -1."), - 'ref_tax_sign': fields.float('Tax Code Sign', help="Usualy 1 or -1."), - 'include_base_amount': fields.boolean('Include in base amount', help="Indicate if the amount of tax must be included in the base amount for the computation of the next taxes"), - 'company_id': fields.many2one('res.company', 'Company', required=True), - 'description': fields.char('Internal Name', 32), - } + 'ref_base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."), + 'ref_tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."), + 'ref_base_sign': fields.float('Base Code Sign', help="Usualy 1 or -1."), + 'ref_tax_sign': fields.float('Tax Code Sign', help="Usualy 1 or -1."), + 'include_base_amount': fields.boolean('Include in base amount', help="Indicate if the amount of tax must be included in the base amount for the computation of the next taxes"), + 'company_id': fields.many2one('res.company', 'Company', required=True), + 'description': fields.char('Internal Name', 32), + } - def name_get(self, cr, uid, ids, context={}): - if not len(ids): - return [] - res = [] - for record in self.read(cr, uid, ids, ['description','name'], context): - name = record['description'] and record['description'] or record['name'] - res.append((record['id'],name )) - return res + def name_get(self, cr, uid, ids, context={}): + if not len(ids): + return [] + res = [] + for record in self.read(cr, uid, ids, ['description','name'], context): + name = record['description'] and record['description'] or record['name'] + res.append((record['id'],name )) + return res - def _default_company(self, cr, uid, context={}): - user = self.pool.get('res.users').browse(cr, uid, uid, context=context) - if user.company_id: - return user.company_id.id - return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] - _defaults = { - 'python_compute': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or None\n# partner : res.partner object or None\n\nresult = price_unit * 0.10''', - 'python_compute_inv': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or False\n\nresult = price_unit * 0.10''', - 'applicable_type': lambda *a: 'true', - 'type': lambda *a: 'percent', - 'amount': lambda *a: 0, - 'active': lambda *a: 1, - 'sequence': lambda *a: 1, - 'tax_group': lambda *a: 'vat', - 'ref_tax_sign': lambda *a: 1, - 'ref_base_sign': lambda *a: 1, - 'tax_sign': lambda *a: 1, - 'base_sign': lambda *a: 1, - 'include_base_amount': lambda *a: False, - 'company_id': _default_company, - } - _order = 'sequence' + def _default_company(self, cr, uid, context={}): + user = self.pool.get('res.users').browse(cr, uid, uid, context=context) + if user.company_id: + return user.company_id.id + return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] + _defaults = { + 'python_compute': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or None\n# partner : res.partner object or None\n\nresult = price_unit * 0.10''', + 'python_compute_inv': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or False\n\nresult = price_unit * 0.10''', + 'applicable_type': lambda *a: 'true', + 'type': lambda *a: 'percent', + 'amount': lambda *a: 0, + 'active': lambda *a: 1, + 'sequence': lambda *a: 1, + 'tax_group': lambda *a: 'vat', + 'ref_tax_sign': lambda *a: 1, + 'ref_base_sign': lambda *a: 1, + 'tax_sign': lambda *a: 1, + 'base_sign': lambda *a: 1, + 'include_base_amount': lambda *a: False, + 'company_id': _default_company, + } + _order = 'sequence' - def _applicable(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None): - res = [] - for tax in taxes: - if tax.applicable_type=='code': - localdict = {'price_unit':price_unit, 'address':self.pool.get('res.partner.address').browse(cr, uid, address_id), 'product':product, 'partner':partner} - exec tax.python_applicable in localdict - if localdict.get('result', False): - res.append(tax) - else: - res.append(tax) - return res + def _applicable(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None): + res = [] + for tax in taxes: + if tax.applicable_type=='code': + localdict = {'price_unit':price_unit, 'address':self.pool.get('res.partner.address').browse(cr, uid, address_id), 'product':product, 'partner':partner} + exec tax.python_applicable in localdict + if localdict.get('result', False): + res.append(tax) + else: + res.append(tax) + return res - def _unit_compute(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None): - taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner) + def _unit_compute(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None): + taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner) - res = [] - cur_price_unit=price_unit - for tax in taxes: - # we compute the amount for the current tax object and append it to the result + res = [] + cur_price_unit=price_unit + for tax in taxes: + # we compute the amount for the current tax object and append it to the result - if tax.type=='percent': - amount = cur_price_unit * tax.amount - res.append({'id':tax.id, - 'name':tax.name, - 'amount':amount, - 'account_collected_id':tax.account_collected_id.id, - 'account_paid_id':tax.account_paid_id.id, - 'base_code_id': tax.base_code_id.id, - 'ref_base_code_id': tax.ref_base_code_id.id, - 'sequence': tax.sequence, - 'base_sign': tax.base_sign, - 'tax_sign': tax.tax_sign, - 'ref_base_sign': tax.ref_base_sign, - 'ref_tax_sign': tax.ref_tax_sign, - 'price_unit': cur_price_unit, - 'tax_code_id': tax.tax_code_id.id, - 'ref_tax_code_id': tax.ref_tax_code_id.id, - }) + if tax.type=='percent': + amount = cur_price_unit * tax.amount + res.append({'id':tax.id, + 'name':tax.name, + 'amount':amount, + 'account_collected_id':tax.account_collected_id.id, + 'account_paid_id':tax.account_paid_id.id, + 'base_code_id': tax.base_code_id.id, + 'ref_base_code_id': tax.ref_base_code_id.id, + 'sequence': tax.sequence, + 'base_sign': tax.base_sign, + 'tax_sign': tax.tax_sign, + 'ref_base_sign': tax.ref_base_sign, + 'ref_tax_sign': tax.ref_tax_sign, + 'price_unit': cur_price_unit, + 'tax_code_id': tax.tax_code_id.id, + 'ref_tax_code_id': tax.ref_tax_code_id.id, + }) - elif tax.type=='fixed': - res.append({'id':tax.id, - 'name':tax.name, - 'amount':tax.amount, - 'account_collected_id':tax.account_collected_id.id, - 'account_paid_id':tax.account_paid_id.id, - 'base_code_id': tax.base_code_id.id, - 'ref_base_code_id': tax.ref_base_code_id.id, - 'sequence': tax.sequence, - 'base_sign': tax.base_sign, - 'tax_sign': tax.tax_sign, - 'ref_base_sign': tax.ref_base_sign, - 'ref_tax_sign': tax.ref_tax_sign, - 'price_unit': 1, - 'tax_code_id': tax.tax_code_id.id, - 'ref_tax_code_id': tax.ref_tax_code_id.id,}) - elif tax.type=='code': - address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None - localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner} - exec tax.python_compute in localdict - amount = localdict['result'] - res.append({ - 'id': tax.id, - 'name': tax.name, - 'amount': amount, - 'account_collected_id': tax.account_collected_id.id, - 'account_paid_id': tax.account_paid_id.id, - 'base_code_id': tax.base_code_id.id, - 'ref_base_code_id': tax.ref_base_code_id.id, - 'sequence': tax.sequence, - 'base_sign': tax.base_sign, - 'tax_sign': tax.tax_sign, - 'ref_base_sign': tax.ref_base_sign, - 'ref_tax_sign': tax.ref_tax_sign, - 'price_unit': cur_price_unit, - 'tax_code_id': tax.tax_code_id.id, - 'ref_tax_code_id': tax.ref_tax_code_id.id, - }) - amount2 = res[-1]['amount'] - if len(tax.child_ids): - if tax.child_depend: - del res[-1] - amount = amount2 - child_tax = self._unit_compute(cr, uid, tax.child_ids, amount, address_id, product, partner) - res.extend(child_tax) - if tax.include_base_amount: - cur_price_unit+=amount2 - return res + elif tax.type=='fixed': + res.append({'id':tax.id, + 'name':tax.name, + 'amount':tax.amount, + 'account_collected_id':tax.account_collected_id.id, + 'account_paid_id':tax.account_paid_id.id, + 'base_code_id': tax.base_code_id.id, + 'ref_base_code_id': tax.ref_base_code_id.id, + 'sequence': tax.sequence, + 'base_sign': tax.base_sign, + 'tax_sign': tax.tax_sign, + 'ref_base_sign': tax.ref_base_sign, + 'ref_tax_sign': tax.ref_tax_sign, + 'price_unit': 1, + 'tax_code_id': tax.tax_code_id.id, + 'ref_tax_code_id': tax.ref_tax_code_id.id,}) + elif tax.type=='code': + address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None + localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner} + exec tax.python_compute in localdict + amount = localdict['result'] + res.append({ + 'id': tax.id, + 'name': tax.name, + 'amount': amount, + 'account_collected_id': tax.account_collected_id.id, + 'account_paid_id': tax.account_paid_id.id, + 'base_code_id': tax.base_code_id.id, + 'ref_base_code_id': tax.ref_base_code_id.id, + 'sequence': tax.sequence, + 'base_sign': tax.base_sign, + 'tax_sign': tax.tax_sign, + 'ref_base_sign': tax.ref_base_sign, + 'ref_tax_sign': tax.ref_tax_sign, + 'price_unit': cur_price_unit, + 'tax_code_id': tax.tax_code_id.id, + 'ref_tax_code_id': tax.ref_tax_code_id.id, + }) + amount2 = res[-1]['amount'] + if len(tax.child_ids): + if tax.child_depend: + del res[-1] + amount = amount2 + child_tax = self._unit_compute(cr, uid, tax.child_ids, amount, address_id, product, partner) + res.extend(child_tax) + if tax.include_base_amount: + cur_price_unit+=amount2 + return res - def compute(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None): + def compute(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None): - """ - Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID. + """ + Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID. - RETURN: - [ tax ] - tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2} - one tax for each tax id in IDS and their childs - """ - res = self._unit_compute(cr, uid, taxes, price_unit, address_id, product, partner) - for r in res: - r['amount'] *= quantity - return res + RETURN: + [ tax ] + tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2} + one tax for each tax id in IDS and their childs + """ + res = self._unit_compute(cr, uid, taxes, price_unit, address_id, product, partner) + for r in res: + r['amount'] *= quantity + return res - def _unit_compute_inv(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None): - taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner) + def _unit_compute_inv(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None): + taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner) - res = [] - taxes.reverse() - cur_price_unit=price_unit - for tax in taxes: - # we compute the amount for the current tax object and append it to the result + res = [] + taxes.reverse() + cur_price_unit=price_unit + for tax in taxes: + # we compute the amount for the current tax object and append it to the result - if tax.type=='percent': - amount = cur_price_unit - (cur_price_unit / (1 + tax.amount)) - res.append({'id':tax.id, - 'name':tax.name, - 'amount':amount, - 'account_collected_id':tax.account_collected_id.id, - 'account_paid_id':tax.account_paid_id.id, - 'base_code_id': tax.base_code_id.id, - 'ref_base_code_id': tax.ref_base_code_id.id, - 'sequence': tax.sequence, - 'base_sign': tax.base_sign, - 'tax_sign': tax.tax_sign, - 'ref_base_sign': tax.ref_base_sign, - 'ref_tax_sign': tax.ref_tax_sign, - 'price_unit': cur_price_unit - amount, - 'tax_code_id': tax.tax_code_id.id, - 'ref_tax_code_id': tax.ref_tax_code_id.id,}) + if tax.type=='percent': + amount = cur_price_unit - (cur_price_unit / (1 + tax.amount)) + res.append({'id':tax.id, + 'name':tax.name, + 'amount':amount, + 'account_collected_id':tax.account_collected_id.id, + 'account_paid_id':tax.account_paid_id.id, + 'base_code_id': tax.base_code_id.id, + 'ref_base_code_id': tax.ref_base_code_id.id, + 'sequence': tax.sequence, + 'base_sign': tax.base_sign, + 'tax_sign': tax.tax_sign, + 'ref_base_sign': tax.ref_base_sign, + 'ref_tax_sign': tax.ref_tax_sign, + 'price_unit': cur_price_unit - amount, + 'tax_code_id': tax.tax_code_id.id, + 'ref_tax_code_id': tax.ref_tax_code_id.id,}) - elif tax.type=='fixed': - res.append({'id':tax.id, - 'name':tax.name, - 'amount':tax.amount, - 'account_collected_id':tax.account_collected_id.id, - 'account_paid_id':tax.account_paid_id.id, - 'base_code_id': tax.base_code_id.id, - 'ref_base_code_id': tax.ref_base_code_id.id, - 'sequence': tax.sequence, - 'base_sign': tax.base_sign, - 'tax_sign': tax.tax_sign, - 'ref_base_sign': tax.ref_base_sign, - 'ref_tax_sign': tax.ref_tax_sign, - 'price_unit': 1, - 'tax_code_id': tax.tax_code_id.id, - 'ref_tax_code_id': tax.ref_tax_code_id.id,}) + elif tax.type=='fixed': + res.append({'id':tax.id, + 'name':tax.name, + 'amount':tax.amount, + 'account_collected_id':tax.account_collected_id.id, + 'account_paid_id':tax.account_paid_id.id, + 'base_code_id': tax.base_code_id.id, + 'ref_base_code_id': tax.ref_base_code_id.id, + 'sequence': tax.sequence, + 'base_sign': tax.base_sign, + 'tax_sign': tax.tax_sign, + 'ref_base_sign': tax.ref_base_sign, + 'ref_tax_sign': tax.ref_tax_sign, + 'price_unit': 1, + 'tax_code_id': tax.tax_code_id.id, + 'ref_tax_code_id': tax.ref_tax_code_id.id,}) - elif tax.type=='code': - address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None - localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner} - exec tax.python_compute_inv in localdict - amount = localdict['result'] - res.append({ - 'id': tax.id, - 'name': tax.name, - 'amount': amount, - 'account_collected_id': tax.account_collected_id.id, - 'account_paid_id': tax.account_paid_id.id, - 'base_code_id': tax.base_code_id.id, - 'ref_base_code_id': tax.ref_base_code_id.id, - 'sequence': tax.sequence, - 'base_sign': tax.base_sign, - 'tax_sign': tax.tax_sign, - 'ref_base_sign': tax.ref_base_sign, - 'ref_tax_sign': tax.ref_tax_sign, - 'price_unit': cur_price_unit - amount, - 'tax_code_id': tax.tax_code_id.id, - 'ref_tax_code_id': tax.ref_tax_code_id.id, - }) + elif tax.type=='code': + address = address_id and self.pool.get('res.partner.address').browse(cr, uid, address_id) or None + localdict = {'price_unit':cur_price_unit, 'address':address, 'product':product, 'partner':partner} + exec tax.python_compute_inv in localdict + amount = localdict['result'] + res.append({ + 'id': tax.id, + 'name': tax.name, + 'amount': amount, + 'account_collected_id': tax.account_collected_id.id, + 'account_paid_id': tax.account_paid_id.id, + 'base_code_id': tax.base_code_id.id, + 'ref_base_code_id': tax.ref_base_code_id.id, + 'sequence': tax.sequence, + 'base_sign': tax.base_sign, + 'tax_sign': tax.tax_sign, + 'ref_base_sign': tax.ref_base_sign, + 'ref_tax_sign': tax.ref_tax_sign, + 'price_unit': cur_price_unit - amount, + 'tax_code_id': tax.tax_code_id.id, + 'ref_tax_code_id': tax.ref_tax_code_id.id, + }) - amount2 = res[-1]['amount'] - if len(tax.child_ids): - if tax.child_depend: - del res[-1] - amount = price_unit - else: - amount = amount2 - for t in tax.child_ids: - parent_tax = self._unit_compute_inv(cr, uid, [t], amount, address_id, product, partner) - res.extend(parent_tax) - if tax.include_base_amount: - cur_price_unit-=amount - taxes.reverse() - return res + amount2 = res[-1]['amount'] + if len(tax.child_ids): + if tax.child_depend: + del res[-1] + amount = price_unit + else: + amount = amount2 + for t in tax.child_ids: + parent_tax = self._unit_compute_inv(cr, uid, [t], amount, address_id, product, partner) + res.extend(parent_tax) + if tax.include_base_amount: + cur_price_unit-=amount + taxes.reverse() + return res - def compute_inv(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None): - """ - Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID. - Price Unit is a VAT included price + def compute_inv(self, cr, uid, taxes, price_unit, quantity, address_id=None, product=None, partner=None): + """ + Compute tax values for given PRICE_UNIT, QUANTITY and a buyer/seller ADDRESS_ID. + Price Unit is a VAT included price - RETURN: - [ tax ] - tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2} - one tax for each tax id in IDS and their childs - """ - res = self._unit_compute_inv(cr, uid, taxes, price_unit, address_id, product, partner=None) - for r in res: - r['amount'] *= quantity - return res + RETURN: + [ tax ] + tax = {'name':'', 'amount':0.0, 'account_collected_id':1, 'account_paid_id':2} + one tax for each tax id in IDS and their childs + """ + res = self._unit_compute_inv(cr, uid, taxes, price_unit, address_id, product, partner=None) + for r in res: + r['amount'] *= quantity + return res account_tax() # --------------------------------------------------------- @@ -1327,41 +1327,41 @@ account_tax() # --------------------------------------------------------- class account_budget_post(osv.osv): - _name = 'account.budget.post' - _description = 'Budget item' - _columns = { - 'code': fields.char('Code', size=64, required=True), - 'name': fields.char('Name', size=256, required=True), - 'dotation_ids': fields.one2many('account.budget.post.dotation', 'post_id', 'Expenses'), - 'account_ids': fields.many2many('account.account', 'account_budget_rel', 'budget_id', 'account_id', 'Accounts'), - } - _defaults = { - } + _name = 'account.budget.post' + _description = 'Budget item' + _columns = { + 'code': fields.char('Code', size=64, required=True), + 'name': fields.char('Name', size=256, required=True), + 'dotation_ids': fields.one2many('account.budget.post.dotation', 'post_id', 'Expenses'), + 'account_ids': fields.many2many('account.account', 'account_budget_rel', 'budget_id', 'account_id', 'Accounts'), + } + _defaults = { + } - def spread(self, cr, uid, ids, fiscalyear_id=False, amount=0.0): - dobj = self.pool.get('account.budget.post.dotation') - for o in self.browse(cr, uid, ids): - # delete dotations for this post - dobj.unlink(cr, uid, dobj.search(cr, uid, [('post_id','=',o.id)])) + def spread(self, cr, uid, ids, fiscalyear_id=False, amount=0.0): + dobj = self.pool.get('account.budget.post.dotation') + for o in self.browse(cr, uid, ids): + # delete dotations for this post + dobj.unlink(cr, uid, dobj.search(cr, uid, [('post_id','=',o.id)])) - # create one dotation per period in the fiscal year, and spread the total amount/quantity over those dotations - fy = self.pool.get('account.fiscalyear').browse(cr, uid, [fiscalyear_id])[0] - num = len(fy.period_ids) - for p in fy.period_ids: - dobj.create(cr, uid, {'post_id': o.id, 'period_id': p.id, 'amount': amount/num}) - return True + # create one dotation per period in the fiscal year, and spread the total amount/quantity over those dotations + fy = self.pool.get('account.fiscalyear').browse(cr, uid, [fiscalyear_id])[0] + num = len(fy.period_ids) + for p in fy.period_ids: + dobj.create(cr, uid, {'post_id': o.id, 'period_id': p.id, 'amount': amount/num}) + return True account_budget_post() class account_budget_post_dotation(osv.osv): - _name = 'account.budget.post.dotation' - _description = "Budget item endowment" - _columns = { - 'name': fields.char('Name', size=64), - 'post_id': fields.many2one('account.budget.post', 'Item', select=True), - 'period_id': fields.many2one('account.period', 'Period'), -# 'quantity': fields.float('Quantity', digits=(16,2)), - 'amount': fields.float('Amount', digits=(16,2)), - } + _name = 'account.budget.post.dotation' + _description = "Budget item endowment" + _columns = { + 'name': fields.char('Name', size=64), + 'post_id': fields.many2one('account.budget.post', 'Item', select=True), + 'period_id': fields.many2one('account.period', 'Period'), +# 'quantity': fields.float('Quantity', digits=(16,2)), + 'amount': fields.float('Amount', digits=(16,2)), + } account_budget_post_dotation() @@ -1370,53 +1370,53 @@ account_budget_post_dotation() # --------------------------------------------------------- class account_model(osv.osv): - _name = "account.model" - _description = "Account Model" - _columns = { - 'name': fields.char('Model Name', size=64, required=True, help="This is a model for recurring accounting entries"), - 'ref': fields.char('Ref', size=64), - 'journal_id': fields.many2one('account.journal', 'Journal', required=True), - 'lines_id': fields.one2many('account.model.line', 'model_id', 'Model Entries'), - 'legend' :fields.text('Legend',readonly=True,size=100), - } + _name = "account.model" + _description = "Account Model" + _columns = { + 'name': fields.char('Model Name', size=64, required=True, help="This is a model for recurring accounting entries"), + 'ref': fields.char('Ref', size=64), + 'journal_id': fields.many2one('account.journal', 'Journal', required=True), + 'lines_id': fields.one2many('account.model.line', 'model_id', 'Model Entries'), + 'legend' :fields.text('Legend',readonly=True,size=100), + } - _defaults = { - 'legend':lambda *a:'''You can specify year, month and date in the name of the model using the following labels:\n\n%(year)s : To Specify Year \n%(month)s : To Specify Month \n%(date)s : Current Date\n\ne.g. My model on %(date)s''', - } + _defaults = { + 'legend':lambda *a:'''You can specify year, month and date in the name of the model using the following labels:\n\n%(year)s : To Specify Year \n%(month)s : To Specify Month \n%(date)s : Current Date\n\ne.g. My model on %(date)s''', + } account_model() class account_model_line(osv.osv): - _name = "account.model.line" - _description = "Account Model Entries" - _columns = { - 'name': fields.char('Name', size=64, required=True), - 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the resources from the lowest sequences to the higher ones"), - 'quantity': fields.float('Quantity', digits=(16,2), help="The optionnal quantity on entries"), - 'debit': fields.float('Debit', digits=(16,2)), - 'credit': fields.float('Credit', digits=(16,2)), + _name = "account.model.line" + _description = "Account Model Entries" + _columns = { + 'name': fields.char('Name', size=64, required=True), + 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the resources from the lowest sequences to the higher ones"), + 'quantity': fields.float('Quantity', digits=(16,2), help="The optionnal quantity on entries"), + 'debit': fields.float('Debit', digits=(16,2)), + 'credit': fields.float('Credit', digits=(16,2)), - 'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade"), + 'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade"), - 'model_id': fields.many2one('account.model', 'Model', required=True, ondelete="cascade", select=True), + 'model_id': fields.many2one('account.model', 'Model', required=True, ondelete="cascade", select=True), - 'ref': fields.char('Ref.', size=16), + 'ref': fields.char('Ref.', size=16), - 'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optionnal other currency."), - 'currency_id': fields.many2one('res.currency', 'Currency'), + 'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optionnal other currency."), + 'currency_id': fields.many2one('res.currency', 'Currency'), - 'partner_id': fields.many2one('res.partner', 'Partner Ref.'), - 'date_maturity': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Maturity date', help="The maturity date of the generated entries for this model. You can chosse between the date of the creation action or the the date of the creation of the entries plus the partner payment terms."), - 'date': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Current Date', required=True, help="The date of the generated entries"), - } - _defaults = { - 'date': lambda *a: 'today' - } - _order = 'sequence' - _sql_constraints = [ - ('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in model !'), - ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in model !'), - ] + 'partner_id': fields.many2one('res.partner', 'Partner Ref.'), + 'date_maturity': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Maturity date', help="The maturity date of the generated entries for this model. You can chosse between the date of the creation action or the the date of the creation of the entries plus the partner payment terms."), + 'date': fields.selection([('today','Date of the day'), ('partner','Partner Payment Term')], 'Current Date', required=True, help="The date of the generated entries"), + } + _defaults = { + 'date': lambda *a: 'today' + } + _order = 'sequence' + _sql_constraints = [ + ('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in model !'), + ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in model !'), + ] account_model_line() # --------------------------------------------------------- @@ -1425,348 +1425,348 @@ account_model_line() class account_subscription(osv.osv): - _name = "account.subscription" - _description = "Account Subscription" - _columns = { - 'name': fields.char('Name', size=64, required=True), - 'ref': fields.char('Ref.', size=16), - 'model_id': fields.many2one('account.model', 'Model', required=True), + _name = "account.subscription" + _description = "Account Subscription" + _columns = { + 'name': fields.char('Name', size=64, required=True), + 'ref': fields.char('Ref.', size=16), + 'model_id': fields.many2one('account.model', 'Model', required=True), - 'date_start': fields.date('Starting date', required=True), - 'period_total': fields.integer('Number of period', required=True), - 'period_nbr': fields.integer('Period', required=True), - 'period_type': fields.selection([('day','days'),('month','month'),('year','year')], 'Period Type', required=True), - 'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'State', required=True, readonly=True), + 'date_start': fields.date('Starting date', required=True), + 'period_total': fields.integer('Number of period', required=True), + 'period_nbr': fields.integer('Period', required=True), + 'period_type': fields.selection([('day','days'),('month','month'),('year','year')], 'Period Type', required=True), + 'state': fields.selection([('draft','Draft'),('running','Running'),('done','Done')], 'State', required=True, readonly=True), - 'lines_id': fields.one2many('account.subscription.line', 'subscription_id', 'Subscription Lines') - } - _defaults = { - 'date_start': lambda *a: time.strftime('%Y-%m-%d'), - 'period_type': lambda *a: 'month', - 'period_total': lambda *a: 12, - 'period_nbr': lambda *a: 1, - 'state': lambda *a: 'draft', - } - def state_draft(self, cr, uid, ids, context={}): - self.write(cr, uid, ids, {'state':'draft'}) - return False + 'lines_id': fields.one2many('account.subscription.line', 'subscription_id', 'Subscription Lines') + } + _defaults = { + 'date_start': lambda *a: time.strftime('%Y-%m-%d'), + 'period_type': lambda *a: 'month', + 'period_total': lambda *a: 12, + 'period_nbr': lambda *a: 1, + 'state': lambda *a: 'draft', + } + def state_draft(self, cr, uid, ids, context={}): + self.write(cr, uid, ids, {'state':'draft'}) + return False - def check(self, cr, uid, ids, context={}): - todone = [] - for sub in self.browse(cr, uid, ids, context): - ok = True - for line in sub.lines_id: - if not line.move_id.id: - ok = False - break - if ok: - todone.append(sub.id) - if len(todone): - self.write(cr, uid, todone, {'state':'done'}) - return False + def check(self, cr, uid, ids, context={}): + todone = [] + for sub in self.browse(cr, uid, ids, context): + ok = True + for line in sub.lines_id: + if not line.move_id.id: + ok = False + break + if ok: + todone.append(sub.id) + if len(todone): + self.write(cr, uid, todone, {'state':'done'}) + return False - def remove_line(self, cr, uid, ids, context={}): - toremove = [] - for sub in self.browse(cr, uid, ids, context): - for line in sub.lines_id: - if not line.move_id.id: - toremove.append(line.id) - if len(toremove): - self.pool.get('account.subscription.line').unlink(cr, uid, toremove) - self.write(cr, uid, ids, {'state':'draft'}) - return False + def remove_line(self, cr, uid, ids, context={}): + toremove = [] + for sub in self.browse(cr, uid, ids, context): + for line in sub.lines_id: + if not line.move_id.id: + toremove.append(line.id) + if len(toremove): + self.pool.get('account.subscription.line').unlink(cr, uid, toremove) + self.write(cr, uid, ids, {'state':'draft'}) + return False - def compute(self, cr, uid, ids, context={}): - for sub in self.browse(cr, uid, ids, context): - ds = sub.date_start - for i in range(sub.period_total): - self.pool.get('account.subscription.line').create(cr, uid, { - 'date': ds, - 'subscription_id': sub.id, - }) - if sub.period_type=='day': - ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(days=sub.period_nbr)).strftime('%Y-%m-%d') - if sub.period_type=='month': - ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(months=sub.period_nbr)).strftime('%Y-%m-%d') - if sub.period_type=='year': - ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(years=sub.period_nbr)).strftime('%Y-%m-%d') - self.write(cr, uid, ids, {'state':'running'}) - return True + def compute(self, cr, uid, ids, context={}): + for sub in self.browse(cr, uid, ids, context): + ds = sub.date_start + for i in range(sub.period_total): + self.pool.get('account.subscription.line').create(cr, uid, { + 'date': ds, + 'subscription_id': sub.id, + }) + if sub.period_type=='day': + ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(days=sub.period_nbr)).strftime('%Y-%m-%d') + if sub.period_type=='month': + ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(months=sub.period_nbr)).strftime('%Y-%m-%d') + if sub.period_type=='year': + ds = (mx.DateTime.strptime(ds, '%Y-%m-%d') + RelativeDateTime(years=sub.period_nbr)).strftime('%Y-%m-%d') + self.write(cr, uid, ids, {'state':'running'}) + return True account_subscription() class account_subscription_line(osv.osv): - _name = "account.subscription.line" - _description = "Account Subscription Line" - _columns = { - 'subscription_id': fields.many2one('account.subscription', 'Subscription', required=True, select=True), - 'date': fields.date('Date', required=True), - 'move_id': fields.many2one('account.move', 'Entry'), - } - _defaults = { - } - def move_create(self, cr, uid, ids, context={}): - tocheck = {} - for line in self.browse(cr, uid, ids, context): - datas = { - 'date': line.date, - } - ids = self.pool.get('account.model').generate(cr, uid, [line.subscription_id.model_id.id], datas, context) - tocheck[line.subscription_id.id] = True - self.write(cr, uid, [line.id], {'move_id':ids[0]}) - if tocheck: - self.pool.get('account.subscription').check(cr, uid, tocheck.keys(), context) - return True - _rec_name = 'date' + _name = "account.subscription.line" + _description = "Account Subscription Line" + _columns = { + 'subscription_id': fields.many2one('account.subscription', 'Subscription', required=True, select=True), + 'date': fields.date('Date', required=True), + 'move_id': fields.many2one('account.move', 'Entry'), + } + _defaults = { + } + def move_create(self, cr, uid, ids, context={}): + tocheck = {} + for line in self.browse(cr, uid, ids, context): + datas = { + 'date': line.date, + } + ids = self.pool.get('account.model').generate(cr, uid, [line.subscription_id.model_id.id], datas, context) + tocheck[line.subscription_id.id] = True + self.write(cr, uid, [line.id], {'move_id':ids[0]}) + if tocheck: + self.pool.get('account.subscription').check(cr, uid, tocheck.keys(), context) + return True + _rec_name = 'date' account_subscription_line() class account_config_fiscalyear(osv.osv_memory): - _name = 'account.config.fiscalyear' - _columns = { - 'name':fields.char('Name', required=True,size=64), - 'code':fields.char('Code', required=True,size=64), - 'date1': fields.date('Starting Date', required=True), - 'date2': fields.date('Ending Date', required=True), - } - _defaults = { - 'code': lambda *a: time.strftime('%Y'), - 'date1': lambda *a: time.strftime('%Y-01-01'), - 'date2': lambda *a: time.strftime('%Y-12-31'), - } - def action_cancel(self,cr,uid,ids,conect=None): - return { - 'view_type': 'form', - "view_mode": 'form', - 'res_model': 'ir.module.module.configuration.wizard', - 'type': 'ir.actions.act_window', - 'target':'new', - } - def action_create(self, cr, uid,ids, context=None): - res=self.read(cr,uid,ids)[0] - if 'date1' in res and 'date2' in res: - res_obj = self.pool.get('account.fiscalyear') - start_date=res['date1'] - end_date=res['date2'] - name=res['name']#DateTime.strptime(start_date, '%Y-%m-%d').strftime('%m.%Y') + '-' + DateTime.strptime(end_date, '%Y-%m-%d').strftime('%m.%Y') - vals={ - 'name':name, - 'code':name, - 'date_start':start_date, - 'date_stop':end_date, - } - new_id=res_obj.create(cr, uid, vals, context=context) - return { - 'view_type': 'form', - "view_mode": 'form', - 'res_model': 'ir.module.module.configuration.wizard', - 'type': 'ir.actions.act_window', - 'target':'new', - } + _name = 'account.config.fiscalyear' + _columns = { + 'name':fields.char('Name', required=True,size=64), + 'code':fields.char('Code', required=True,size=64), + 'date1': fields.date('Starting Date', required=True), + 'date2': fields.date('Ending Date', required=True), + } + _defaults = { + 'code': lambda *a: time.strftime('%Y'), + 'date1': lambda *a: time.strftime('%Y-01-01'), + 'date2': lambda *a: time.strftime('%Y-12-31'), + } + def action_cancel(self,cr,uid,ids,conect=None): + return { + 'view_type': 'form', + "view_mode": 'form', + 'res_model': 'ir.module.module.configuration.wizard', + 'type': 'ir.actions.act_window', + 'target':'new', + } + def action_create(self, cr, uid,ids, context=None): + res=self.read(cr,uid,ids)[0] + if 'date1' in res and 'date2' in res: + res_obj = self.pool.get('account.fiscalyear') + start_date=res['date1'] + end_date=res['date2'] + name=res['name']#DateTime.strptime(start_date, '%Y-%m-%d').strftime('%m.%Y') + '-' + DateTime.strptime(end_date, '%Y-%m-%d').strftime('%m.%Y') + vals={ + 'name':name, + 'code':name, + 'date_start':start_date, + 'date_stop':end_date, + } + new_id=res_obj.create(cr, uid, vals, context=context) + return { + 'view_type': 'form', + "view_mode": 'form', + 'res_model': 'ir.module.module.configuration.wizard', + 'type': 'ir.actions.act_window', + 'target':'new', + } account_config_fiscalyear() class account_config_journal_bank_accounts(osv.osv_memory): - _name='account.config.journal.bank.account' - _columns = { - 'name':fields.char('Journal Name', size=64), - 'lines_id': fields.one2many('account.config.journal.bank.account.line', 'journal_id', 'Journal Lines'), - } + _name='account.config.journal.bank.account' + _columns = { + 'name':fields.char('Journal Name', size=64), + 'lines_id': fields.one2many('account.config.journal.bank.account.line', 'journal_id', 'Journal Lines'), + } - def action_cancel(self,cr,uid,ids,conect=None): - return { - 'view_type': 'form', - "view_mode": 'form', - 'res_model': 'ir.module.module.configuration.wizard', - 'type': 'ir.actions.act_window', - 'target':'new', - } + def action_cancel(self,cr,uid,ids,conect=None): + return { + 'view_type': 'form', + "view_mode": 'form', + 'res_model': 'ir.module.module.configuration.wizard', + 'type': 'ir.actions.act_window', + 'target':'new', + } - def action_create(self, cr, uid, ids, context=None): - config_res=self.read(cr,uid,ids)[0] - res_obj = self.pool.get('account.journal') - line_obj=self.pool.get('account.config.journal.bank.account.line') - if 'lines_id' in config_res and config_res['lines_id']: - lines=line_obj.read(cr,uid,config_res['lines_id']) - for res in lines: - sequence_ids=self.pool.get('ir.sequence').search(cr,uid,[('name','=','Account Journal')]) - if 'name' in res and 'bank_account_id' in res and 'view_id' in res and sequence_ids and len(sequence_ids): - vals={ - 'name':res['name'], - 'type':'cash', - 'view_id':res['view_id'], - 'default_credit_account_id':res['bank_account_id'], - 'default_debit_account_id':res['bank_account_id'], - 'sequence_id':sequence_ids[0] - } - res_obj.create(cr, uid, vals, context=context) - return { - 'view_type': 'form', - "view_mode": 'form', - 'res_model': 'ir.module.module.configuration.wizard', - 'type': 'ir.actions.act_window', - 'target':'new', - } + def action_create(self, cr, uid, ids, context=None): + config_res=self.read(cr,uid,ids)[0] + res_obj = self.pool.get('account.journal') + line_obj=self.pool.get('account.config.journal.bank.account.line') + if 'lines_id' in config_res and config_res['lines_id']: + lines=line_obj.read(cr,uid,config_res['lines_id']) + for res in lines: + sequence_ids=self.pool.get('ir.sequence').search(cr,uid,[('name','=','Account Journal')]) + if 'name' in res and 'bank_account_id' in res and 'view_id' in res and sequence_ids and len(sequence_ids): + vals={ + 'name':res['name'], + 'type':'cash', + 'view_id':res['view_id'], + 'default_credit_account_id':res['bank_account_id'], + 'default_debit_account_id':res['bank_account_id'], + 'sequence_id':sequence_ids[0] + } + res_obj.create(cr, uid, vals, context=context) + return { + 'view_type': 'form', + "view_mode": 'form', + 'res_model': 'ir.module.module.configuration.wizard', + 'type': 'ir.actions.act_window', + 'target':'new', + } account_config_journal_bank_accounts() class account_config_journal_bank_accounts_line(osv.osv_memory): - _name='account.config.journal.bank.account.line' - def _journal_view_get(self, cr, uid, context={}): - journal_obj = self.pool.get('account.journal.view') - ids = journal_obj.search(cr, uid, []) - res = journal_obj.read(cr, uid, ids, ['id', 'name'], context) - return [(r['id'], r['name']) for r in res] - _columns = { - 'name':fields.char('Journal Name', size=64,required=True), - 'bank_account_id':fields.many2one('account.account', 'Bank Account', required=True, domain=[('type','=','cash')]), - 'view_id':fields.selection(_journal_view_get, 'Journal View', required=True), - 'journal_id':fields.many2one('account.config.journal.bank.account', 'Journal', required=True), - } + _name='account.config.journal.bank.account.line' + def _journal_view_get(self, cr, uid, context={}): + journal_obj = self.pool.get('account.journal.view') + ids = journal_obj.search(cr, uid, []) + res = journal_obj.read(cr, uid, ids, ['id', 'name'], context) + return [(r['id'], r['name']) for r in res] + _columns = { + 'name':fields.char('Journal Name', size=64,required=True), + 'bank_account_id':fields.many2one('account.account', 'Bank Account', required=True, domain=[('type','=','cash')]), + 'view_id':fields.selection(_journal_view_get, 'Journal View', required=True), + 'journal_id':fields.many2one('account.config.journal.bank.account', 'Journal', required=True), + } account_config_journal_bank_accounts_line() # ---------------------------------------------- -# Account Templates : Account, Tax and charts. +# Account Templates : Account, Tax and charts. # ---------------------------------------------- class account_tax_template(osv.osv): - _name = 'account.tax.template' + _name = 'account.tax.template' account_tax() class account_account_template(osv.osv): - _name='account.account.template' - _description ='Templates for Accounts' - _order = "code" - _columns = { - 'name': fields.char('Name', size=128, required=True, select=True), - 'sign': fields.selection([(-1, 'Negative'), (1, 'Positive')], 'Sign', required=True, help='Allows to change the displayed amount of the balance to see positive results instead of negative ones in expenses accounts.'), - 'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Force all moves for this account to have this secondary currency."), - 'code': fields.char('Code', size=64), - 'type': fields.selection(_code_get, 'Account Type', required=True), - 'reconcile': fields.boolean('Reconcile', help="Check this option if the user can make a reconciliation of the entries in this account."), - 'shortcut': fields.char('Shortcut', size=12), - 'note': fields.text('Note'), - } + _name='account.account.template' + _description ='Templates for Accounts' + _order = "code" + _columns = { + 'name': fields.char('Name', size=128, required=True, select=True), + 'sign': fields.selection([(-1, 'Negative'), (1, 'Positive')], 'Sign', required=True, help='Allows to change the displayed amount of the balance to see positive results instead of negative ones in expenses accounts.'), + 'currency_id': fields.many2one('res.currency', 'Secondary Currency', help="Force all moves for this account to have this secondary currency."), + 'code': fields.char('Code', size=64), + 'type': fields.selection(_code_get, 'Account Type', required=True), + 'reconcile': fields.boolean('Reconcile', help="Check this option if the user can make a reconciliation of the entries in this account."), + 'shortcut': fields.char('Shortcut', size=12), + 'note': fields.text('Note'), + } - _defaults = { - 'sign': lambda *a: 1, - 'reconcile': lambda *a: False, - 'type' : lambda *a :'view', - } + _defaults = { + 'sign': lambda *a: 1, + 'reconcile': lambda *a: False, + 'type' : lambda *a :'view', + } - def _check_recursion(self, cr, uid, ids): - level = 100 - while len(ids): - cr.execute('select distinct parent_id from account_account_template_rel where child_id in ('+','.join(map(str,ids))+')') - ids = filter(None, map(lambda x:x[0], cr.fetchall())) - if not level: - return False - level -= 1 - return True + def _check_recursion(self, cr, uid, ids): + level = 100 + while len(ids): + cr.execute('select distinct parent_id from account_account_template_rel where child_id in ('+','.join(map(str,ids))+')') + ids = filter(None, map(lambda x:x[0], cr.fetchall())) + if not level: + return False + level -= 1 + return True - _constraints = [ - (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id']) - ] + _constraints = [ + (_check_recursion, 'Error ! You can not create recursive accounts.', ['parent_id']) + ] - def name_get(self, cr, uid, ids, context={}): - if not len(ids): - return [] - reads = self.read(cr, uid, ids, ['name','code'], context) - res = [] - for record in reads: - name = record['name'] - if record['code']: - name = record['code']+' - '+name - res.append((record['id'],name )) - return res + def name_get(self, cr, uid, ids, context={}): + if not len(ids): + return [] + reads = self.read(cr, uid, ids, ['name','code'], context) + res = [] + for record in reads: + name = record['name'] + if record['code']: + name = record['code']+' - '+name + res.append((record['id'],name )) + return res account_account_template() class account_tax_template(osv.osv): - _name = 'account.tax.template' - _description = 'Templates for Taxes' + _name = 'account.tax.template' + _description = 'Templates for Taxes' - _columns = { - 'name': fields.char('Tax Name', size=64, required=True), - 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the taxes lines from the lowest sequences to the higher ones. The order is important if you have a tax that have several tax children. In this case, the evaluation order is important."), -# 'amount': fields.float('Amount', required=True, digits=(14,4)), -# 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code')], 'Tax Type', required=True), - 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None')],'Tax Type', required=True), -# 'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True), - 'domain':fields.char('Domain', size=32, help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."), -# 'account_collected_id':fields.many2one('account.account.template', 'Invoice Tax Account'), -# 'account_paid_id':fields.many2one('account.account.template', 'Refund Tax Account'), -# 'parent_id':fields.many2one('account.tax.template', 'Parent Tax Account', select=True), -# 'child_ids':fields.one2many('account.tax.template', 'parent_id', 'Childs Tax Account'), -# 'child_depend':fields.boolean('Tax on Childs', help="Indicate if the tax computation is based on the value computed for the computation of child taxes or based on the total amount."), -# 'python_compute':fields.text('Python Code'), -# 'python_compute_inv':fields.text('Python Code (reverse)'), -# 'python_applicable':fields.text('Python Code'), - 'tax_group': fields.selection([('vat','VAT'),('other','Other')], 'Tax Group', help="If a default tax if given in the partner it only override taxes from account (or product) of the same group."), + _columns = { + 'name': fields.char('Tax Name', size=64, required=True), + 'sequence': fields.integer('Sequence', required=True, help="The sequence field is used to order the taxes lines from the lowest sequences to the higher ones. The order is important if you have a tax that have several tax children. In this case, the evaluation order is important."), +# 'amount': fields.float('Amount', required=True, digits=(14,4)), +# 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None'), ('code','Python Code')], 'Tax Type', required=True), + 'type': fields.selection( [('percent','Percent'), ('fixed','Fixed'), ('none','None')],'Tax Type', required=True), +# 'applicable_type': fields.selection( [('true','True'), ('code','Python Code')], 'Applicable Type', required=True), + 'domain':fields.char('Domain', size=32, help="This field is only used if you develop your own module allowing developers to create specific taxes in a custom domain."), +# 'account_collected_id':fields.many2one('account.account.template', 'Invoice Tax Account'), +# 'account_paid_id':fields.many2one('account.account.template', 'Refund Tax Account'), +# 'parent_id':fields.many2one('account.tax.template', 'Parent Tax Account', select=True), +# 'child_ids':fields.one2many('account.tax.template', 'parent_id', 'Childs Tax Account'), +# 'child_depend':fields.boolean('Tax on Childs', help="Indicate if the tax computation is based on the value computed for the computation of child taxes or based on the total amount."), +# 'python_compute':fields.text('Python Code'), +# 'python_compute_inv':fields.text('Python Code (reverse)'), +# 'python_applicable':fields.text('Python Code'), + 'tax_group': fields.selection([('vat','VAT'),('other','Other')], 'Tax Group', help="If a default tax if given in the partner it only override taxes from account (or product) of the same group."), - # - # Fields used for the VAT declaration - # -# 'base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."), -# 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."), -# 'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."), -# 'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."), + # + # Fields used for the VAT declaration + # +# 'base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."), +# 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."), +# 'base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."), +# 'tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."), - # Same fields for refund invoices + # Same fields for refund invoices -# 'ref_base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."), -# 'ref_tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."), -# 'ref_base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."), -# 'ref_tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."), -# 'include_base_amount': fields.boolean('Include in base amount', help="Indicate if the amount of tax must be included in the base amount for the computation of the next taxes."), - 'description': fields.char('Internal Name', size=32), - } +# 'ref_base_code_id': fields.many2one('account.tax.code', 'Base Code', help="Use this code for the VAT declaration."), +# 'ref_tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="Use this code for the VAT declaration."), +# 'ref_base_sign': fields.float('Base Code Sign', help="Usually 1 or -1."), +# 'ref_tax_sign': fields.float('Tax Code Sign', help="Usually 1 or -1."), +# 'include_base_amount': fields.boolean('Include in base amount', help="Indicate if the amount of tax must be included in the base amount for the computation of the next taxes."), + 'description': fields.char('Internal Name', size=32), + } - def name_get(self, cr, uid, ids, context={}): - if not len(ids): - return [] - res = [] - for record in self.read(cr, uid, ids, ['description','name'], context): - name = record['description'] and record['description'] or record['name'] - res.append((record['id'],name )) - return res + def name_get(self, cr, uid, ids, context={}): + if not len(ids): + return [] + res = [] + for record in self.read(cr, uid, ids, ['description','name'], context): + name = record['description'] and record['description'] or record['name'] + res.append((record['id'],name )) + return res - _defaults = { -# 'python_compute': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or None\n# partner : res.partner object or None\n\nresult = price_unit * 0.10''', -# 'python_compute_inv': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or False\n\nresult = price_unit * 0.10''', -# 'applicable_type': lambda *a: 'true', - 'type': lambda *a: 'percent', -# 'amount': lambda *a: 0, - 'sequence': lambda *a: 1, - 'tax_group': lambda *a: 'vat', -# 'ref_tax_sign': lambda *a: 1, -# 'ref_base_sign': lambda *a: 1, -# 'tax_sign': lambda *a: 1, -# 'base_sign': lambda *a: 1, -# 'include_base_amount': lambda *a: False, -# 'company_id': _default_company, - } - _order = 'sequence' + _defaults = { +# 'python_compute': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or None\n# partner : res.partner object or None\n\nresult = price_unit * 0.10''', +# 'python_compute_inv': lambda *a: '''# price_unit\n# address : res.partner.address object or False\n# product : product.product object or False\n\nresult = price_unit * 0.10''', +# 'applicable_type': lambda *a: 'true', + 'type': lambda *a: 'percent', +# 'amount': lambda *a: 0, + 'sequence': lambda *a: 1, + 'tax_group': lambda *a: 'vat', +# 'ref_tax_sign': lambda *a: 1, +# 'ref_base_sign': lambda *a: 1, +# 'tax_sign': lambda *a: 1, +# 'base_sign': lambda *a: 1, +# 'include_base_amount': lambda *a: False, +# 'company_id': _default_company, + } + _order = 'sequence' account_tax_template() class account_chart_template(osv.osv): - _name="account.chart.template" - _description= "Templates for Account Chart" + _name="account.chart.template" + _description= "Templates for Account Chart" - _columns={ - 'name': fields.char('Name', size=64, required=True), - 'account_root_id': fields.many2one('account.account.template','Root Account',required=True), - 'bank_account_view_id': fields.many2one('account.account.template','Bank Account',required=True), - 'property_receivable_id': fields.many2one('account.account.template','Receivable Account'), - 'property_payable_id': fields.many2one('account.account.template','Payable Account'), - 'property_account_expense_categ_id': fields.many2one('account.account.template','Expense Category Account'), - 'property_account_income_categ_id': fields.many2one('account.account.template','Income Category Account'), - } + _columns={ + 'name': fields.char('Name', size=64, required=True), + 'account_root_id': fields.many2one('account.account.template','Root Account',required=True), + 'bank_account_view_id': fields.many2one('account.account.template','Bank Account',required=True), + 'property_receivable_id': fields.many2one('account.account.template','Receivable Account'), + 'property_payable_id': fields.many2one('account.account.template','Payable Account'), + 'property_account_expense_categ_id': fields.many2one('account.account.template','Expense Category Account'), + 'property_account_income_categ_id': fields.many2one('account.account.template','Income Category Account'), + } account_chart_template() diff --git a/addons/account/account_analytic_line.py b/addons/account/account_analytic_line.py index 3dd06187bf2..c3cd2c6aa5f 100644 --- a/addons/account/account_analytic_line.py +++ b/addons/account/account_analytic_line.py @@ -35,97 +35,97 @@ from osv import osv from tools.translate import _ class account_analytic_line(osv.osv): - _name = 'account.analytic.line' - _description = 'Analytic lines' - _columns = { - 'name' : fields.char('Description', size=256, required=True), - 'date' : fields.date('Date', required=True), - 'amount' : fields.float('Amount', required=True), - 'unit_amount' : fields.float('Quantity'), - 'product_uom_id' : fields.many2one('product.uom', 'UoM'), - 'product_id' : fields.many2one('product.product', 'Product'), - 'account_id' : fields.many2one('account.analytic.account', 'Analytic Account', required=True, ondelete='cascade', select=True), - 'general_account_id' : fields.many2one('account.account', 'General account', required=True, ondelete='cascade'), - 'move_id' : fields.many2one('account.move.line', 'General entry', ondelete='cascade', select=True), - 'journal_id' : fields.many2one('account.analytic.journal', 'Analytic journal', required=True, ondelete='cascade', select=True), - 'code' : fields.char('Code', size=8), - 'user_id' : fields.many2one('res.users', 'User',), - 'ref': fields.char('Ref.', size=32), - } - _defaults = { - 'date': lambda *a: time.strftime('%Y-%m-%d'), - } - _order = 'date' - def _check_company(self, cr, uid, ids): - lines = self.browse(cr, uid, ids) - for l in lines: - if l.move_id and not l.account_id.company_id.id == l.move_id.account_id.company_id.id: - return False - return True - _constraints = [ - (_check_company, 'You can not create analytic line that is not in the same company than the account line', ['account_id']) - ] - - def on_change_unit_amount(self, cr, uid, id, prod_id, unit_amount, - unit=False, context=None): - uom_obj = self.pool.get('product.uom') - product_obj = self.pool.get('product.product') - if unit_amount and prod_id: - prod = product_obj.browse(cr, uid, prod_id) - a = prod.product_tmpl_id.property_account_expense.id - if not a: - a = prod.categ_id.property_account_expense_categ.id - if not a: - raise osv.except_osv(_('Error !'), - _('There is no expense account define ' \ - 'for this product: "%s" (id:%d)') % \ - (prod.name, prod.id,)) - amount = unit_amount * uom_obj._compute_price(cr, uid, - prod.uom_id.id, prod.standard_price, unit) - return {'value': { - 'amount': - round(amount, 2), - 'general_account_id': a, - }} - return {} + _name = 'account.analytic.line' + _description = 'Analytic lines' + _columns = { + 'name' : fields.char('Description', size=256, required=True), + 'date' : fields.date('Date', required=True), + 'amount' : fields.float('Amount', required=True), + 'unit_amount' : fields.float('Quantity'), + 'product_uom_id' : fields.many2one('product.uom', 'UoM'), + 'product_id' : fields.many2one('product.product', 'Product'), + 'account_id' : fields.many2one('account.analytic.account', 'Analytic Account', required=True, ondelete='cascade', select=True), + 'general_account_id' : fields.many2one('account.account', 'General account', required=True, ondelete='cascade'), + 'move_id' : fields.many2one('account.move.line', 'General entry', ondelete='cascade', select=True), + 'journal_id' : fields.many2one('account.analytic.journal', 'Analytic journal', required=True, ondelete='cascade', select=True), + 'code' : fields.char('Code', size=8), + 'user_id' : fields.many2one('res.users', 'User',), + 'ref': fields.char('Ref.', size=32), + } + _defaults = { + 'date': lambda *a: time.strftime('%Y-%m-%d'), + } + _order = 'date' + def _check_company(self, cr, uid, ids): + lines = self.browse(cr, uid, ids) + for l in lines: + if l.move_id and not l.account_id.company_id.id == l.move_id.account_id.company_id.id: + return False + return True + _constraints = [ + (_check_company, 'You can not create analytic line that is not in the same company than the account line', ['account_id']) + ] + + def on_change_unit_amount(self, cr, uid, id, prod_id, unit_amount, + unit=False, context=None): + uom_obj = self.pool.get('product.uom') + product_obj = self.pool.get('product.product') + if unit_amount and prod_id: + prod = product_obj.browse(cr, uid, prod_id) + a = prod.product_tmpl_id.property_account_expense.id + if not a: + a = prod.categ_id.property_account_expense_categ.id + if not a: + raise osv.except_osv(_('Error !'), + _('There is no expense account define ' \ + 'for this product: "%s" (id:%d)') % \ + (prod.name, prod.id,)) + amount = unit_amount * uom_obj._compute_price(cr, uid, + prod.uom_id.id, prod.standard_price, unit) + return {'value': { + 'amount': - round(amount, 2), + 'general_account_id': a, + }} + return {} account_analytic_line() class timesheet_invoice(osv.osv): - _name = "report.hr.timesheet.invoice.journal" - _description = "Analytic account costs and revenues" - _auto = False - _columns = { - 'name': fields.date('Month', readonly=True), - 'account_id':fields.many2one('account.analytic.account', 'Analytic Account', readonly=True, select=True), - 'journal_id': fields.many2one('account.analytic.journal', 'Journal', readonly=True), - 'quantity': fields.float('Quantities', readonly=True), - 'cost': fields.float('Credit', readonly=True), - 'revenue': fields.float('Debit', readonly=True) - } - _order = 'name desc, account_id' - def init(self, cr): - cr.execute(""" - create or replace view report_hr_timesheet_invoice_journal as ( - select - min(l.id) as id, - date_trunc('month', l.date)::date as name, - sum( - CASE WHEN l.amount>0 THEN 0 ELSE l.amount - END - ) as cost, - sum( - CASE WHEN l.amount>0 THEN l.amount ELSE 0 - END - ) as revenue, - sum(l.unit_amount* COALESCE(u.factor, 1)) as quantity, - journal_id, - account_id - from account_analytic_line l - LEFT OUTER join product_uom u on (u.id=l.product_uom_id) - group by - date_trunc('month', l.date), - journal_id, - account_id - )""") + _name = "report.hr.timesheet.invoice.journal" + _description = "Analytic account costs and revenues" + _auto = False + _columns = { + 'name': fields.date('Month', readonly=True), + 'account_id':fields.many2one('account.analytic.account', 'Analytic Account', readonly=True, select=True), + 'journal_id': fields.many2one('account.analytic.journal', 'Journal', readonly=True), + 'quantity': fields.float('Quantities', readonly=True), + 'cost': fields.float('Credit', readonly=True), + 'revenue': fields.float('Debit', readonly=True) + } + _order = 'name desc, account_id' + def init(self, cr): + cr.execute(""" + create or replace view report_hr_timesheet_invoice_journal as ( + select + min(l.id) as id, + date_trunc('month', l.date)::date as name, + sum( + CASE WHEN l.amount>0 THEN 0 ELSE l.amount + END + ) as cost, + sum( + CASE WHEN l.amount>0 THEN l.amount ELSE 0 + END + ) as revenue, + sum(l.unit_amount* COALESCE(u.factor, 1)) as quantity, + journal_id, + account_id + from account_analytic_line l + LEFT OUTER join product_uom u on (u.id=l.product_uom_id) + group by + date_trunc('month', l.date), + journal_id, + account_id + )""") timesheet_invoice() diff --git a/addons/account/account_bank_statement.py b/addons/account/account_bank_statement.py index 3f50255c416..ad01d223fa5 100644 --- a/addons/account/account_bank_statement.py +++ b/addons/account/account_bank_statement.py @@ -39,545 +39,545 @@ from mx.DateTime import RelativeDateTime, now, DateTime, localtime class account_bank_statement(osv.osv): - def _default_journal_id(self, cr, uid, context={}): - if context.get('journal_id', False): - return context['journal_id'] - return False + def _default_journal_id(self, cr, uid, context={}): + if context.get('journal_id', False): + return context['journal_id'] + return False - def _default_balance_start(self, cr, uid, context={}): - cr.execute('select id from account_bank_statement where journal_id=%d order by date desc limit 1', (1,)) - res = cr.fetchone() - if res: - return self.browse(cr, uid, [res[0]], context)[0].balance_end - return 0.0 + def _default_balance_start(self, cr, uid, context={}): + cr.execute('select id from account_bank_statement where journal_id=%d order by date desc limit 1', (1,)) + res = cr.fetchone() + if res: + return self.browse(cr, uid, [res[0]], context)[0].balance_end + return 0.0 - def _end_balance(self, cursor, user, ids, name, attr, context=None): - res_currency_obj = self.pool.get('res.currency') - res_users_obj = self.pool.get('res.users') + def _end_balance(self, cursor, user, ids, name, attr, context=None): + res_currency_obj = self.pool.get('res.currency') + res_users_obj = self.pool.get('res.users') - res = {} + res = {} - company_currency_id = res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id + company_currency_id = res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id - statements = self.browse(cursor, user, ids, context=context) - for statement in statements: - res[statement.id] = statement.balance_start - currency_id = statement.currency.id - for line in statement.move_line_ids: - if line.debit > 0: - if line.account_id.id == \ - statement.journal_id.default_debit_account_id.id: - res[statement.id] += res_currency_obj.compute(cursor, - user, company_currency_id, currency_id, - line.debit, context=context) - else: - if line.account_id.id == \ - statement.journal_id.default_credit_account_id.id: - res[statement.id] += res_currency_obj.compute(cursor, - user, company_currency_id, currency_id, - line.credit, context=context) - if statement.state == 'draft': - for line in statement.line_ids: - res[statement.id] += line.amount - for r in res: - res[r] = round(res[r], 2) - return res + statements = self.browse(cursor, user, ids, context=context) + for statement in statements: + res[statement.id] = statement.balance_start + currency_id = statement.currency.id + for line in statement.move_line_ids: + if line.debit > 0: + if line.account_id.id == \ + statement.journal_id.default_debit_account_id.id: + res[statement.id] += res_currency_obj.compute(cursor, + user, company_currency_id, currency_id, + line.debit, context=context) + else: + if line.account_id.id == \ + statement.journal_id.default_credit_account_id.id: + res[statement.id] += res_currency_obj.compute(cursor, + user, company_currency_id, currency_id, + line.credit, context=context) + if statement.state == 'draft': + for line in statement.line_ids: + res[statement.id] += line.amount + for r in res: + res[r] = round(res[r], 2) + return res - def _get_period(self, cr, uid, context={}): - periods = self.pool.get('account.period').find(cr, uid) - if periods: - return periods[0] - else: - return False + def _get_period(self, cr, uid, context={}): + periods = self.pool.get('account.period').find(cr, uid) + if periods: + return periods[0] + else: + return False - def _currency(self, cursor, user, ids, name, args, context=None): - res = {} - res_currency_obj = self.pool.get('res.currency') - res_users_obj = self.pool.get('res.users') - default_currency = res_users_obj.browse(cursor, user, - user, context=context).company_id.currency_id - for statement in self.browse(cursor, user, ids, context=context): - currency = statement.journal_id.currency - if not currency: - currency = default_currency - res[statement.id] = currency.id - currency_names = {} - for currency_id, currency_name in res_currency_obj.name_get(cursor, - user, [x for x in res.values()], context=context): - currency_names[currency_id] = currency_name - for statement_id in res.keys(): - currency_id = res[statement_id] - res[statement_id] = (currency_id, currency_names[currency_id]) - return res + def _currency(self, cursor, user, ids, name, args, context=None): + res = {} + res_currency_obj = self.pool.get('res.currency') + res_users_obj = self.pool.get('res.users') + default_currency = res_users_obj.browse(cursor, user, + user, context=context).company_id.currency_id + for statement in self.browse(cursor, user, ids, context=context): + currency = statement.journal_id.currency + if not currency: + currency = default_currency + res[statement.id] = currency.id + currency_names = {} + for currency_id, currency_name in res_currency_obj.name_get(cursor, + user, [x for x in res.values()], context=context): + currency_names[currency_id] = currency_name + for statement_id in res.keys(): + currency_id = res[statement_id] + res[statement_id] = (currency_id, currency_names[currency_id]) + return res - _order = "date desc" - _name = "account.bank.statement" - _description = "Bank Statement" - _columns = { - 'name': fields.char('Name', size=64, required=True), - 'date': fields.date('Date', required=True, - states={'confirm': [('readonly', True)]}), - 'journal_id': fields.many2one('account.journal', 'Journal', required=True, - states={'confirm': [('readonly', True)]}, domain=[('type', '=', 'cash')]), - 'period_id': fields.many2one('account.period', 'Period', required=True, - states={'confirm':[('readonly', True)]}), - 'balance_start': fields.float('Starting Balance', digits=(16,2), - states={'confirm':[('readonly',True)]}), - 'balance_end_real': fields.float('Ending Balance', digits=(16,2), - states={'confirm':[('readonly', True)]}), - 'balance_end': fields.function(_end_balance, method=True, string='Balance'), - 'line_ids': fields.one2many('account.bank.statement.line', - 'statement_id', 'Statement lines', - states={'confirm':[('readonly', True)]}), - 'move_line_ids': fields.one2many('account.move.line', 'statement_id', - 'Entry lines', states={'confirm':[('readonly',True)]}), - 'state': fields.selection([('draft', 'Draft'),('confirm', 'Confirm')], - 'State', required=True, - states={'confirm': [('readonly', True)]}, readonly="1"), - 'currency': fields.function(_currency, method=True, string='Currency', - type='many2one', relation='res.currency'), - } - - _defaults = { - 'name': lambda self, cr, uid, context=None: \ - self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement'), - 'date': lambda *a: time.strftime('%Y-%m-%d'), - 'state': lambda *a: 'draft', - 'balance_start': _default_balance_start, - 'journal_id': _default_journal_id, - 'period_id': _get_period, - } + _order = "date desc" + _name = "account.bank.statement" + _description = "Bank Statement" + _columns = { + 'name': fields.char('Name', size=64, required=True), + 'date': fields.date('Date', required=True, + states={'confirm': [('readonly', True)]}), + 'journal_id': fields.many2one('account.journal', 'Journal', required=True, + states={'confirm': [('readonly', True)]}, domain=[('type', '=', 'cash')]), + 'period_id': fields.many2one('account.period', 'Period', required=True, + states={'confirm':[('readonly', True)]}), + 'balance_start': fields.float('Starting Balance', digits=(16,2), + states={'confirm':[('readonly',True)]}), + 'balance_end_real': fields.float('Ending Balance', digits=(16,2), + states={'confirm':[('readonly', True)]}), + 'balance_end': fields.function(_end_balance, method=True, string='Balance'), + 'line_ids': fields.one2many('account.bank.statement.line', + 'statement_id', 'Statement lines', + states={'confirm':[('readonly', True)]}), + 'move_line_ids': fields.one2many('account.move.line', 'statement_id', + 'Entry lines', states={'confirm':[('readonly',True)]}), + 'state': fields.selection([('draft', 'Draft'),('confirm', 'Confirm')], + 'State', required=True, + states={'confirm': [('readonly', True)]}, readonly="1"), + 'currency': fields.function(_currency, method=True, string='Currency', + type='many2one', relation='res.currency'), + } + + _defaults = { + 'name': lambda self, cr, uid, context=None: \ + self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement'), + 'date': lambda *a: time.strftime('%Y-%m-%d'), + 'state': lambda *a: 'draft', + 'balance_start': _default_balance_start, + 'journal_id': _default_journal_id, + 'period_id': _get_period, + } - def button_confirm(self, cr, uid, ids, context=None): - done = [] - res_currency_obj = self.pool.get('res.currency') - res_users_obj = self.pool.get('res.users') - account_move_obj = self.pool.get('account.move') - account_move_line_obj = self.pool.get('account.move.line') - account_bank_statement_line_obj = \ - self.pool.get('account.bank.statement.line') + def button_confirm(self, cr, uid, ids, context=None): + done = [] + res_currency_obj = self.pool.get('res.currency') + res_users_obj = self.pool.get('res.users') + account_move_obj = self.pool.get('account.move') + account_move_line_obj = self.pool.get('account.move.line') + account_bank_statement_line_obj = \ + self.pool.get('account.bank.statement.line') - company_currency_id = res_users_obj.browse(cr, uid, uid, - context=context).company_id.currency_id.id + company_currency_id = res_users_obj.browse(cr, uid, uid, + context=context).company_id.currency_id.id - for st in self.browse(cr, uid, ids, context): - if not st.state=='draft': - continue + for st in self.browse(cr, uid, ids, context): + if not st.state=='draft': + continue - if not (abs(st.balance_end - st.balance_end_real) < 0.0001): - raise osv.except_osv(_('Error !'), - _('The statement balance is incorrect !\n' - 'Check that the ending balance equals the computed one.')) - if (not st.journal_id.default_credit_account_id) \ - or (not st.journal_id.default_debit_account_id): - raise osv.except_osv(_('Configration Error !'), - _('Please verify that an account is defined in the journal.')) + if not (abs(st.balance_end - st.balance_end_real) < 0.0001): + raise osv.except_osv(_('Error !'), + _('The statement balance is incorrect !\n' + 'Check that the ending balance equals the computed one.')) + if (not st.journal_id.default_credit_account_id) \ + or (not st.journal_id.default_debit_account_id): + raise osv.except_osv(_('Configration Error !'), + _('Please verify that an account is defined in the journal.')) - for line in st.move_line_ids: - if line.state <> 'valid': - raise osv.except_osv(_('Error !'), - _('The account entries lines are not valid.')) + for line in st.move_line_ids: + if line.state <> 'valid': + raise osv.except_osv(_('Error !'), + _('The account entries lines are not valid.')) - for move in st.line_ids: - move_id = account_move_obj.create(cr, uid, { - 'journal_id': st.journal_id.id, - 'period_id': st.period_id.id, - }, context=context) - account_bank_statement_line_obj.write(cr, uid, [move.id], { - 'move_ids': [(4,move_id, False)] - }) - if not move.amount: - continue + for move in st.line_ids: + move_id = account_move_obj.create(cr, uid, { + 'journal_id': st.journal_id.id, + 'period_id': st.period_id.id, + }, context=context) + account_bank_statement_line_obj.write(cr, uid, [move.id], { + 'move_ids': [(4,move_id, False)] + }) + if not move.amount: + continue - torec = [] - amount = res_currency_obj.compute(cr, uid, st.currency.id, - company_currency_id, move.amount, context=context) - if move.reconcile_id and move.reconcile_id.line_new_ids: - for newline in move.reconcile_id.line_new_ids: - amount += newline.amount + torec = [] + amount = res_currency_obj.compute(cr, uid, st.currency.id, + company_currency_id, move.amount, context=context) + if move.reconcile_id and move.reconcile_id.line_new_ids: + for newline in move.reconcile_id.line_new_ids: + amount += newline.amount - val = { - 'name': move.name, - 'date': move.date, - 'ref': move.ref, - 'move_id': move_id, - 'partner_id': ((move.partner_id) and move.partner_id.id) or False, - 'account_id': (move.account_id) and move.account_id.id, - 'credit': ((amount>0) and amount) or 0.0, - 'debit': ((amount<0) and -amount) or 0.0, - 'statement_id': st.id, - 'journal_id': st.journal_id.id, - 'period_id': st.period_id.id, - 'currency_id': st.currency.id, - } + val = { + 'name': move.name, + 'date': move.date, + 'ref': move.ref, + 'move_id': move_id, + 'partner_id': ((move.partner_id) and move.partner_id.id) or False, + 'account_id': (move.account_id) and move.account_id.id, + 'credit': ((amount>0) and amount) or 0.0, + 'debit': ((amount<0) and -amount) or 0.0, + 'statement_id': st.id, + 'journal_id': st.journal_id.id, + 'period_id': st.period_id.id, + 'currency_id': st.currency.id, + } - amount = res_currency_obj.compute(cr, uid, st.currency.id, - company_currency_id, move.amount, context=context) + amount = res_currency_obj.compute(cr, uid, st.currency.id, + company_currency_id, move.amount, context=context) - if move.account_id and move.account_id.currency_id: - val['currency_id'] = move.account_id.currency_id.id - if company_currency_id==move.account_id.currency_id.id: - amount_cur = move.amount - else: - amount_cur = res_currency_obj.compute(cr, uid, company_currency_id, - move.account_id.currency_id.id, amount, context=context) - val['amount_currency'] = amount_cur + if move.account_id and move.account_id.currency_id: + val['currency_id'] = move.account_id.currency_id.id + if company_currency_id==move.account_id.currency_id.id: + amount_cur = move.amount + else: + amount_cur = res_currency_obj.compute(cr, uid, company_currency_id, + move.account_id.currency_id.id, amount, context=context) + val['amount_currency'] = amount_cur - torec.append(account_move_line_obj.create(cr, uid, val , context=context)) + torec.append(account_move_line_obj.create(cr, uid, val , context=context)) - if move.reconcile_id and move.reconcile_id.line_new_ids: - for newline in move.reconcile_id.line_new_ids: - account_move_line_obj.create(cr, uid, { - 'name': newline.name or move.name, - 'date': move.date, - 'ref': move.ref, - 'move_id': move_id, - 'partner_id': ((move.partner_id) and move.partner_id.id) or False, - 'account_id': (newline.account_id) and newline.account_id.id, - 'debit': newline.amount>0 and newline.amount or 0.0, - 'credit': newline.amount<0 and -newline.amount or 0.0, - 'statement_id': st.id, - 'journal_id': st.journal_id.id, - 'period_id': st.period_id.id, - }, context=context) + if move.reconcile_id and move.reconcile_id.line_new_ids: + for newline in move.reconcile_id.line_new_ids: + account_move_line_obj.create(cr, uid, { + 'name': newline.name or move.name, + 'date': move.date, + 'ref': move.ref, + 'move_id': move_id, + 'partner_id': ((move.partner_id) and move.partner_id.id) or False, + 'account_id': (newline.account_id) and newline.account_id.id, + 'debit': newline.amount>0 and newline.amount or 0.0, + 'credit': newline.amount<0 and -newline.amount or 0.0, + 'statement_id': st.id, + 'journal_id': st.journal_id.id, + 'period_id': st.period_id.id, + }, context=context) - if amount >= 0: - account_id = st.journal_id.default_credit_account_id.id - else: - account_id = st.journal_id.default_debit_account_id.id + if amount >= 0: + account_id = st.journal_id.default_credit_account_id.id + else: + account_id = st.journal_id.default_debit_account_id.id - # Fill the secondary amount/currency - # if currency is not the same than the company - amount_currency = False - currency_id = False - if st.currency.id <> company_currency_id: - amount_currency = move.amount - currency_id = st.currency.id + # Fill the secondary amount/currency + # if currency is not the same than the company + amount_currency = False + currency_id = False + if st.currency.id <> company_currency_id: + amount_currency = move.amount + currency_id = st.currency.id - account_move_line_obj.create(cr, uid, { - 'name': move.name, - 'date': move.date, - 'ref': move.ref, - 'move_id': move_id, - 'partner_id': ((move.partner_id) and move.partner_id.id) or False, - 'account_id': account_id, - 'credit': ((amount < 0) and -amount) or 0.0, - 'debit': ((amount > 0) and amount) or 0.0, - 'statement_id': st.id, - 'journal_id': st.journal_id.id, - 'period_id': st.period_id.id, - 'amount_currency': amount_currency, - 'currency_id': currency_id, - }, context=context) + account_move_line_obj.create(cr, uid, { + 'name': move.name, + 'date': move.date, + 'ref': move.ref, + 'move_id': move_id, + 'partner_id': ((move.partner_id) and move.partner_id.id) or False, + 'account_id': account_id, + 'credit': ((amount < 0) and -amount) or 0.0, + 'debit': ((amount > 0) and amount) or 0.0, + 'statement_id': st.id, + 'journal_id': st.journal_id.id, + 'period_id': st.period_id.id, + 'amount_currency': amount_currency, + 'currency_id': currency_id, + }, context=context) - for line in account_move_line_obj.browse(cr, uid, [x.id for x in - account_move_obj.browse(cr, uid, move_id, - context=context).line_id], - context=context): - if line.state <> 'valid': - raise osv.except_osv(_('Error !'), - _('Account move line "%s" is not valid') % line.name) + for line in account_move_line_obj.browse(cr, uid, [x.id for x in + account_move_obj.browse(cr, uid, move_id, + context=context).line_id], + context=context): + if line.state <> 'valid': + raise osv.except_osv(_('Error !'), + _('Account move line "%s" is not valid') % line.name) - if move.reconcile_id and move.reconcile_id.line_ids: - torec += map(lambda x: x.id, move.reconcile_id.line_ids) - try: - if abs(move.reconcile_amount-move.amount)<0.0001: - account_move_line_obj.reconcile(cr, uid, torec, 'statement', context) - else: - account_move_line_obj.reconcile_partial(cr, uid, torec, 'statement', context) - except: - raise osv.except_osv(_('Error !'), _('Unable to reconcile entry "%s": %.2f') % (move.name, move.amount)) + if move.reconcile_id and move.reconcile_id.line_ids: + torec += map(lambda x: x.id, move.reconcile_id.line_ids) + try: + if abs(move.reconcile_amount-move.amount)<0.0001: + account_move_line_obj.reconcile(cr, uid, torec, 'statement', context) + else: + account_move_line_obj.reconcile_partial(cr, uid, torec, 'statement', context) + except: + raise osv.except_osv(_('Error !'), _('Unable to reconcile entry "%s": %.2f') % (move.name, move.amount)) - done.append(st.id) - self.write(cr, uid, done, {'state':'confirm'}, context=context) - return True + done.append(st.id) + self.write(cr, uid, done, {'state':'confirm'}, context=context) + return True - def button_cancel(self, cr, uid, ids, context={}): - done = [] - for st in self.browse(cr, uid, ids, context): - if st.state=='draft': - continue - ids = [] - for line in st.line_ids: - ids += [x.id for x in line.move_ids] - self.pool.get('account.move').unlink(cr, uid, ids, context) - done.append(st.id) - self.write(cr, uid, done, {'state':'draft'}, context=context) - return True + def button_cancel(self, cr, uid, ids, context={}): + done = [] + for st in self.browse(cr, uid, ids, context): + if st.state=='draft': + continue + ids = [] + for line in st.line_ids: + ids += [x.id for x in line.move_ids] + self.pool.get('account.move').unlink(cr, uid, ids, context) + done.append(st.id) + self.write(cr, uid, done, {'state':'draft'}, context=context) + return True - def onchange_journal_id(self, cursor, user, statement_id, journal_id, context=None): - if not journal_id: - return {'value': {'currency': False}} + def onchange_journal_id(self, cursor, user, statement_id, journal_id, context=None): + if not journal_id: + return {'value': {'currency': False}} - account_journal_obj = self.pool.get('account.journal') - res_users_obj = self.pool.get('res.users') - res_currency_obj = self.pool.get('res.currency') + account_journal_obj = self.pool.get('account.journal') + res_users_obj = self.pool.get('res.users') + res_currency_obj = self.pool.get('res.currency') - cursor.execute('SELECT balance_end_real \ - FROM account_bank_statement \ - WHERE journal_id = %d \ - ORDER BY date DESC LIMIT 1', (journal_id,)) - res = cursor.fetchone() - balance_start = res and res[0] or 0.0 + cursor.execute('SELECT balance_end_real \ + FROM account_bank_statement \ + WHERE journal_id = %d \ + ORDER BY date DESC LIMIT 1', (journal_id,)) + res = cursor.fetchone() + balance_start = res and res[0] or 0.0 - currency_id = account_journal_obj.browse(cursor, user, journal_id, - context=context).currency.id - if not currency_id: - currency_id = res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id - currency = res_currency_obj.name_get(cursor, user, [currency_id], - context=context)[0] - return {'value': {'balance_start': balance_start, 'currency': currency}} + currency_id = account_journal_obj.browse(cursor, user, journal_id, + context=context).currency.id + if not currency_id: + currency_id = res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id + currency = res_currency_obj.name_get(cursor, user, [currency_id], + context=context)[0] + return {'value': {'balance_start': balance_start, 'currency': currency}} account_bank_statement() class account_bank_statement_reconcile(osv.osv): - _name = "account.bank.statement.reconcile" - _description = "Statement reconcile" + _name = "account.bank.statement.reconcile" + _description = "Statement reconcile" - def _total_entry(self, cursor, user, ids, name, attr, context=None): - result = {} - for o in self.browse(cursor, user, ids, context=context): - result[o.id] = 0.0 - for line in o.line_ids: - result[o.id] += line.debit - line.credit - return result + def _total_entry(self, cursor, user, ids, name, attr, context=None): + result = {} + for o in self.browse(cursor, user, ids, context=context): + result[o.id] = 0.0 + for line in o.line_ids: + result[o.id] += line.debit - line.credit + return result - def _total_new(self, cursor, user, ids, name, attr, context=None): - result = {} - for o in self.browse(cursor, user, ids, context=context): - result[o.id] = 0.0 - for line in o.line_new_ids: - result[o.id] += line.amount - return result + def _total_new(self, cursor, user, ids, name, attr, context=None): + result = {} + for o in self.browse(cursor, user, ids, context=context): + result[o.id] = 0.0 + for line in o.line_new_ids: + result[o.id] += line.amount + return result - def _total_balance(self, cursor, user, ids, name, attr, context=None): - result = {} - for o in self.browse(cursor, user, ids, context=context): - result[o.id] = o.total_new - o.total_entry + o.total_amount - return result + def _total_balance(self, cursor, user, ids, name, attr, context=None): + result = {} + for o in self.browse(cursor, user, ids, context=context): + result[o.id] = o.total_new - o.total_entry + o.total_amount + return result - def _total_amount(self, cursor, user, ids, name, attr, context=None): - res = {} - res_currency_obj = self.pool.get('res.currency') - res_users_obj = self.pool.get('res.users') + def _total_amount(self, cursor, user, ids, name, attr, context=None): + res = {} + res_currency_obj = self.pool.get('res.currency') + res_users_obj = self.pool.get('res.users') - company_currency_id = res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id - currency_id = context.get('currency_id', company_currency_id) + company_currency_id = res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id + currency_id = context.get('currency_id', company_currency_id) - for reconcile_id in ids: - res[reconcile_id] = res_currency_obj.compute(cursor, user, - currency_id, company_currency_id, - context.get('amount', 0.0), context=context) - return res + for reconcile_id in ids: + res[reconcile_id] = res_currency_obj.compute(cursor, user, + currency_id, company_currency_id, + context.get('amount', 0.0), context=context) + return res - def _default_amount(self, cursor, user, context=None): - if context is None: - context = {} - res_currency_obj = self.pool.get('res.currency') - res_users_obj = self.pool.get('res.users') + def _default_amount(self, cursor, user, context=None): + if context is None: + context = {} + res_currency_obj = self.pool.get('res.currency') + res_users_obj = self.pool.get('res.users') - company_currency_id = res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id - currency_id = context.get('currency_id', company_currency_id) + company_currency_id = res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id + currency_id = context.get('currency_id', company_currency_id) - return res_currency_obj.compute(cursor, user, - currency_id, company_currency_id, - context.get('amount', 0.0), context=context) + return res_currency_obj.compute(cursor, user, + currency_id, company_currency_id, + context.get('amount', 0.0), context=context) - def _total_currency(self, cursor, user, ids, name, attrs, context=None): - res = {} - res_users_obj = self.pool.get('res.users') + def _total_currency(self, cursor, user, ids, name, attrs, context=None): + res = {} + res_users_obj = self.pool.get('res.users') - company_currency_id = res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id + company_currency_id = res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id - for reconcile_id in ids: - res[reconcile_id] = company_currency_id - return res + for reconcile_id in ids: + res[reconcile_id] = company_currency_id + return res - def _default_currency(self, cursor, user, context=None): - res_users_obj = self.pool.get('res.users') + def _default_currency(self, cursor, user, context=None): + res_users_obj = self.pool.get('res.users') - return res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id + return res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id - def _total_second_amount(self, cursor, user, ids, name, attr, - context=None): - res = {} - for reconcile_id in ids: - res[reconcile_id] = context.get('amount', 0.0) - return res + def _total_second_amount(self, cursor, user, ids, name, attr, + context=None): + res = {} + for reconcile_id in ids: + res[reconcile_id] = context.get('amount', 0.0) + return res - def _total_second_currency(self, cursor, user, ids, name, attr, context=None): - res = {} - for reconcile_id in ids: - res[reconcile_id] = context.get('currency_id', False) - return res + def _total_second_currency(self, cursor, user, ids, name, attr, context=None): + res = {} + for reconcile_id in ids: + res[reconcile_id] = context.get('currency_id', False) + return res - def name_get(self, cursor, user, ids, context=None): - res= [] - res_currency_obj = self.pool.get('res.currency') - res_users_obj = self.pool.get('res.users') + def name_get(self, cursor, user, ids, context=None): + res= [] + res_currency_obj = self.pool.get('res.currency') + res_users_obj = self.pool.get('res.users') - company_currency_id = res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id + company_currency_id = res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id - for o in self.browse(cursor, user, ids, context=context): - td = '' - if o.statement_line: - currency_id = o.statement_line[0].statement_id.currency.id - if abs(o.statement_line[0].amount - (o.total_entry - o.total_new))>0.01: - td = 'P ' - else: - currency_id = company_currency_id - res.append((o.id, '%s[%.2f/%.2f]' % (td, - res_currency_obj.compute(cursor, user, company_currency_id, - currency_id, o.total_entry, context=context), - res_currency_obj.compute(cursor, user, company_currency_id, - currency_id, o.total_new, context=context)))) - return res + for o in self.browse(cursor, user, ids, context=context): + td = '' + if o.statement_line: + currency_id = o.statement_line[0].statement_id.currency.id + if abs(o.statement_line[0].amount - (o.total_entry - o.total_new))>0.01: + td = 'P ' + else: + currency_id = company_currency_id + res.append((o.id, '%s[%.2f/%.2f]' % (td, + res_currency_obj.compute(cursor, user, company_currency_id, + currency_id, o.total_entry, context=context), + res_currency_obj.compute(cursor, user, company_currency_id, + currency_id, o.total_new, context=context)))) + return res - _columns = { - 'name': fields.char('Date', size=64, required=True), - 'partner_id': fields.many2one('res.partner', 'Partner', readonly=True), - 'line_new_ids': fields.one2many('account.bank.statement.reconcile.line', - 'line_id', 'Write-Off'), - 'total_entry': fields.function(_total_entry, method=True, - string='Total entries'), - 'total_new': fields.function(_total_new, method=True, - string='Total write-off'), - 'total_second_amount': fields.function(_total_second_amount, - method=True, string='Payment amount', - help='The amount in the currency of the journal'), - 'total_second_currency': fields.function(_total_second_currency, method=True, - string='Currency', type='many2one', relation='res.currency', - help='The currency of the journal'), - 'total_amount': fields.function(_total_amount, method=True, - string='Payment amount'), - 'total_currency': fields.function(_total_currency, method=True, - string='Currency', type='many2one', relation='res.currency'), - 'total_balance': fields.function(_total_balance, method=True, - string='Balance'), - #line_ids define in account.py - 'statement_line': fields.one2many('account.bank.statement.line', - 'reconcile_id', 'Bank Statement Line'), - } - _defaults = { - 'name': lambda *a: time.strftime('%Y-%m-%d'), - 'partner_id': lambda obj, cursor, user, context=None: \ - context.get('partner', False), - 'total_amount': _default_amount, - 'total_currency': _default_currency, - 'total_second_amount': lambda obj, cursor, user, context=None: \ - context.get('amount', 0.0), - 'total_second_currency': lambda obj, cursor, user, context=None: \ - context.get('currency_id', False), - 'total_balance': _default_amount, - } + _columns = { + 'name': fields.char('Date', size=64, required=True), + 'partner_id': fields.many2one('res.partner', 'Partner', readonly=True), + 'line_new_ids': fields.one2many('account.bank.statement.reconcile.line', + 'line_id', 'Write-Off'), + 'total_entry': fields.function(_total_entry, method=True, + string='Total entries'), + 'total_new': fields.function(_total_new, method=True, + string='Total write-off'), + 'total_second_amount': fields.function(_total_second_amount, + method=True, string='Payment amount', + help='The amount in the currency of the journal'), + 'total_second_currency': fields.function(_total_second_currency, method=True, + string='Currency', type='many2one', relation='res.currency', + help='The currency of the journal'), + 'total_amount': fields.function(_total_amount, method=True, + string='Payment amount'), + 'total_currency': fields.function(_total_currency, method=True, + string='Currency', type='many2one', relation='res.currency'), + 'total_balance': fields.function(_total_balance, method=True, + string='Balance'), + #line_ids define in account.py + 'statement_line': fields.one2many('account.bank.statement.line', + 'reconcile_id', 'Bank Statement Line'), + } + _defaults = { + 'name': lambda *a: time.strftime('%Y-%m-%d'), + 'partner_id': lambda obj, cursor, user, context=None: \ + context.get('partner', False), + 'total_amount': _default_amount, + 'total_currency': _default_currency, + 'total_second_amount': lambda obj, cursor, user, context=None: \ + context.get('amount', 0.0), + 'total_second_currency': lambda obj, cursor, user, context=None: \ + context.get('currency_id', False), + 'total_balance': _default_amount, + } account_bank_statement_reconcile() class account_bank_statement_reconcile_line(osv.osv): - _name = "account.bank.statement.reconcile.line" - _description = "Statement reconcile line" - _columns = { - 'name': fields.char('Description', size=64), - 'account_id': fields.many2one('account.account', 'Account', required=True), - 'line_id': fields.many2one('account.bank.statement.reconcile', 'Reconcile'), - 'amount': fields.float('Amount', required=True), - } + _name = "account.bank.statement.reconcile.line" + _description = "Statement reconcile line" + _columns = { + 'name': fields.char('Description', size=64), + 'account_id': fields.many2one('account.account', 'Account', required=True), + 'line_id': fields.many2one('account.bank.statement.reconcile', 'Reconcile'), + 'amount': fields.float('Amount', required=True), + } account_bank_statement_reconcile_line() class account_bank_statement_line(osv.osv): - def onchange_partner_id(self, cursor, user, line_id, partner_id, type, currency_id, - context={}): - if not partner_id: - return {} - res_currency_obj = self.pool.get('res.currency') - res_users_obj = self.pool.get('res.users') + def onchange_partner_id(self, cursor, user, line_id, partner_id, type, currency_id, + context={}): + if not partner_id: + return {} + res_currency_obj = self.pool.get('res.currency') + res_users_obj = self.pool.get('res.users') - company_currency_id = res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id + company_currency_id = res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id - if not currency_id: - currency_id = company_currency_id + if not currency_id: + currency_id = company_currency_id - part = self.pool.get('res.partner').browse(cursor, user, partner_id, - context=context) - if type == 'supplier': - account_id = part.property_account_payable.id - else: - account_id = part.property_account_receivable.id + part = self.pool.get('res.partner').browse(cursor, user, partner_id, + context=context) + if type == 'supplier': + account_id = part.property_account_payable.id + else: + account_id = part.property_account_receivable.id - cursor.execute('SELECT sum(debit-credit) \ - FROM account_move_line \ - WHERE (reconcile_id is null) \ - AND partner_id = %d \ - AND account_id=%d', (partner_id, account_id)) - res = cursor.fetchone() - balance = res and res[0] or 0.0 + cursor.execute('SELECT sum(debit-credit) \ + FROM account_move_line \ + WHERE (reconcile_id is null) \ + AND partner_id = %d \ + AND account_id=%d', (partner_id, account_id)) + res = cursor.fetchone() + balance = res and res[0] or 0.0 - balance = res_currency_obj.compute(cursor, user, company_currency_id, - currency_id, balance, context=context) - return {'value': {'amount': balance, 'account_id': account_id}} + balance = res_currency_obj.compute(cursor, user, company_currency_id, + currency_id, balance, context=context) + return {'value': {'amount': balance, 'account_id': account_id}} - def _reconcile_amount(self, cursor, user, ids, name, args, context=None): - if not ids: - return {} - res_currency_obj = self.pool.get('res.currency') - res_users_obj = self.pool.get('res.users') + def _reconcile_amount(self, cursor, user, ids, name, args, context=None): + if not ids: + return {} + res_currency_obj = self.pool.get('res.currency') + res_users_obj = self.pool.get('res.users') - res = {} - company_currency_id = res_users_obj.browse(cursor, user, user, - context=context).company_id.currency_id.id + res = {} + company_currency_id = res_users_obj.browse(cursor, user, user, + context=context).company_id.currency_id.id - for line in self.browse(cursor, user, ids, context=context): - if line.reconcile_id: - res[line.id] = res_currency_obj.compute(cursor, user, - company_currency_id, line.statement_id.currency.id, - line.reconcile_id.total_entry, context=context) - else: - res[line.id] = 0.0 - return res + for line in self.browse(cursor, user, ids, context=context): + if line.reconcile_id: + res[line.id] = res_currency_obj.compute(cursor, user, + company_currency_id, line.statement_id.currency.id, + line.reconcile_id.total_entry, context=context) + else: + res[line.id] = 0.0 + return res - _order = "date,name desc" - _name = "account.bank.statement.line" - _description = "Bank Statement Line" - _columns = { - 'name': fields.char('Name', size=64, required=True), - 'date': fields.date('Date', required=True), - 'amount': fields.float('Amount'), - 'type': fields.selection([ - ('supplier','Supplier'), - ('customer','Customer'), - ('general','General') - ], 'Type', required=True), - 'partner_id': fields.many2one('res.partner', 'Partner'), - 'account_id': fields.many2one('account.account','Account', - required=True), - 'statement_id': fields.many2one('account.bank.statement', 'Statement', - select=True, required=True), - 'reconcile_id': fields.many2one('account.bank.statement.reconcile', - 'Reconcile', states={'confirm':[('readonly',True)]}), - 'move_ids': fields.many2many('account.move', - 'account_bank_statement_line_move_rel', 'move_id','statement_id', - 'Moves'), - 'ref': fields.char('Ref.', size=32), - 'note': fields.text('Notes'), - 'reconcile_amount': fields.function(_reconcile_amount, - string='Amount reconciled', method=True, type='float'), - } - _defaults = { - 'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'), - 'date': lambda *a: time.strftime('%Y-%m-%d'), - 'type': lambda *a: 'general', - } + _order = "date,name desc" + _name = "account.bank.statement.line" + _description = "Bank Statement Line" + _columns = { + 'name': fields.char('Name', size=64, required=True), + 'date': fields.date('Date', required=True), + 'amount': fields.float('Amount'), + 'type': fields.selection([ + ('supplier','Supplier'), + ('customer','Customer'), + ('general','General') + ], 'Type', required=True), + 'partner_id': fields.many2one('res.partner', 'Partner'), + 'account_id': fields.many2one('account.account','Account', + required=True), + 'statement_id': fields.many2one('account.bank.statement', 'Statement', + select=True, required=True), + 'reconcile_id': fields.many2one('account.bank.statement.reconcile', + 'Reconcile', states={'confirm':[('readonly',True)]}), + 'move_ids': fields.many2many('account.move', + 'account_bank_statement_line_move_rel', 'move_id','statement_id', + 'Moves'), + 'ref': fields.char('Ref.', size=32), + 'note': fields.text('Notes'), + 'reconcile_amount': fields.function(_reconcile_amount, + string='Amount reconciled', method=True, type='float'), + } + _defaults = { + 'name': lambda self,cr,uid,context={}: self.pool.get('ir.sequence').get(cr, uid, 'account.bank.statement.line'), + 'date': lambda *a: time.strftime('%Y-%m-%d'), + 'type': lambda *a: 'general', + } account_bank_statement_line() diff --git a/addons/account/account_move_line.py b/addons/account/account_move_line.py index 418ff1f56a9..616750dd5c2 100644 --- a/addons/account/account_move_line.py +++ b/addons/account/account_move_line.py @@ -34,721 +34,721 @@ from osv import fields, osv from tools.translate import _ class account_move_line(osv.osv): - _name = "account.move.line" - _description = "Entry lines" + _name = "account.move.line" + _description = "Entry lines" - def _query_get(self, cr, uid, obj='l', context={}): - fiscalyear_obj = self.pool.get('account.fiscalyear') - if not context.get('fiscalyear', False): - fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')]) - fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0' - else: - fiscalyear_clause = '%s' % context['fiscalyear'] - if context.get('periods', False): - ids = ','.join([str(x) for x in context['periods']]) - return obj+".active AND "+obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) AND id in (%s))" % (fiscalyear_clause, ids) - else: - return obj+".active AND "+obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s))" % (fiscalyear_clause,) + def _query_get(self, cr, uid, obj='l', context={}): + fiscalyear_obj = self.pool.get('account.fiscalyear') + if not context.get('fiscalyear', False): + fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')]) + fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0' + else: + fiscalyear_clause = '%s' % context['fiscalyear'] + if context.get('periods', False): + ids = ','.join([str(x) for x in context['periods']]) + return obj+".active AND "+obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) AND id in (%s))" % (fiscalyear_clause, ids) + else: + return obj+".active AND "+obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s))" % (fiscalyear_clause,) - def default_get(self, cr, uid, fields, context={}): - data = self._default_get(cr, uid, fields, context) - for f in data.keys(): - if f not in fields: - del data[f] - return data + def default_get(self, cr, uid, fields, context={}): + data = self._default_get(cr, uid, fields, context) + for f in data.keys(): + if f not in fields: + del data[f] + return data - def _default_get(self, cr, uid, fields, context={}): - # Compute simple values - data = super(account_move_line, self).default_get(cr, uid, fields, context) + def _default_get(self, cr, uid, fields, context={}): + # Compute simple values + data = super(account_move_line, self).default_get(cr, uid, fields, context) - if not 'move_id' in fields: #we are not in manual entry - return data + if not 'move_id' in fields: #we are not in manual entry + return data - period_obj = self.pool.get('account.period') + period_obj = self.pool.get('account.period') - # Compute the current move - move_id = False - partner_id = False - if context.get('journal_id',False) and context.get('period_id',False): - if 'move_id' in fields: - cr.execute('select move_id \ - from \ - account_move_line \ - where \ - journal_id=%d and period_id=%d and create_uid=%d and state=%s \ - order by id desc limit 1', - (context['journal_id'], context['period_id'], uid, 'draft')) - res = cr.fetchone() - move_id = (res and res[0]) or False - if not move_id: - return data - else: - data['move_id'] = move_id - if 'date' in fields: - cr.execute('select date \ - from \ - account_move_line \ - where \ - journal_id=%d and period_id=%d and create_uid=%d \ - order by id desc', - (context['journal_id'], context['period_id'], uid)) - res = cr.fetchone() - if res: - data['date'] = res[0] - else: - period = period_obj.browse(cr, uid, context['period_id'], - context=context) - data['date'] = period.date_start + # Compute the current move + move_id = False + partner_id = False + if context.get('journal_id',False) and context.get('period_id',False): + if 'move_id' in fields: + cr.execute('select move_id \ + from \ + account_move_line \ + where \ + journal_id=%d and period_id=%d and create_uid=%d and state=%s \ + order by id desc limit 1', + (context['journal_id'], context['period_id'], uid, 'draft')) + res = cr.fetchone() + move_id = (res and res[0]) or False + if not move_id: + return data + else: + data['move_id'] = move_id + if 'date' in fields: + cr.execute('select date \ + from \ + account_move_line \ + where \ + journal_id=%d and period_id=%d and create_uid=%d \ + order by id desc', + (context['journal_id'], context['period_id'], uid)) + res = cr.fetchone() + if res: + data['date'] = res[0] + else: + period = period_obj.browse(cr, uid, context['period_id'], + context=context) + data['date'] = period.date_start - if not move_id: - return data + if not move_id: + return data - total = 0 - ref_id = False - taxes = {} - move = self.pool.get('account.move').browse(cr, uid, move_id, context) - for l in move.line_id: - partner_id = partner_id or l.partner_id.id - ref_id = ref_id or l.ref - total += (l.debit - l.credit) - for tax in l.account_id.tax_ids: - if move.journal_id.type == 'sale': - if l.debit: - code = tax.ref_tax_code_id.id - acc = tax.account_paid_id.id - else: - code = tax.tax_code_id.id - acc = tax.account_collected_id.id - else: - if l.debit: - code = tax.tax_code_id.id - acc = tax.account_collected_id.id - else: - code = tax.ref_tax_code_id.id - acc = tax.account_paid_id.id - taxes.setdefault((acc, code), False) - taxes[(l.account_id.id, l.tax_code_id.id)] = True - if 'name' in fields: - data.setdefault('name', l.name) + total = 0 + ref_id = False + taxes = {} + move = self.pool.get('account.move').browse(cr, uid, move_id, context) + for l in move.line_id: + partner_id = partner_id or l.partner_id.id + ref_id = ref_id or l.ref + total += (l.debit - l.credit) + for tax in l.account_id.tax_ids: + if move.journal_id.type == 'sale': + if l.debit: + code = tax.ref_tax_code_id.id + acc = tax.account_paid_id.id + else: + code = tax.tax_code_id.id + acc = tax.account_collected_id.id + else: + if l.debit: + code = tax.tax_code_id.id + acc = tax.account_collected_id.id + else: + code = tax.ref_tax_code_id.id + acc = tax.account_paid_id.id + taxes.setdefault((acc, code), False) + taxes[(l.account_id.id, l.tax_code_id.id)] = True + if 'name' in fields: + data.setdefault('name', l.name) - if 'ref' in fields: - data['ref'] = ref_id - if 'partner_id' in fields: - data['partner_id'] = partner_id + if 'ref' in fields: + data['ref'] = ref_id + if 'partner_id' in fields: + data['partner_id'] = partner_id - if move.journal_id.type in ('purchase', 'sale'): - for t in taxes: - if not taxes[t] and t[0]: - s = 0 - tax_amount = 0 - for l in move.line_id: - if move.journal_id.type == 'sale': - if l.debit: - field_base = 'ref_' - key = 'account_paid_id' - else: - field_base = '' - key = 'account_collected_id' - else: - if l.debit: - field_base = '' - key = 'account_collected_id' - else: - field_base = 'ref_' - key = 'account_paid_id' - for tax in self.pool.get('account.tax').compute(cr, uid, - l.account_id.tax_ids, l.debit or l.credit, 1, False): - if (tax[key] == t[0]) \ - and (tax[field_base + 'tax_code_id'] == t[1]): - if l.debit: - s += tax['amount'] - else: - s -= tax['amount'] - tax_amount += tax['amount'] * \ - tax[field_base + 'tax_sign'] - if ('debit' in fields) or ('credit' in fields): - data['debit'] = s>0 and s or 0.0 - data['credit'] = s<0 and -s or 0.0 + if move.journal_id.type in ('purchase', 'sale'): + for t in taxes: + if not taxes[t] and t[0]: + s = 0 + tax_amount = 0 + for l in move.line_id: + if move.journal_id.type == 'sale': + if l.debit: + field_base = 'ref_' + key = 'account_paid_id' + else: + field_base = '' + key = 'account_collected_id' + else: + if l.debit: + field_base = '' + key = 'account_collected_id' + else: + field_base = 'ref_' + key = 'account_paid_id' + for tax in self.pool.get('account.tax').compute(cr, uid, + l.account_id.tax_ids, l.debit or l.credit, 1, False): + if (tax[key] == t[0]) \ + and (tax[field_base + 'tax_code_id'] == t[1]): + if l.debit: + s += tax['amount'] + else: + s -= tax['amount'] + tax_amount += tax['amount'] * \ + tax[field_base + 'tax_sign'] + if ('debit' in fields) or ('credit' in fields): + data['debit'] = s>0 and s or 0.0 + data['credit'] = s<0 and -s or 0.0 - if 'tax_code_id' in fields: - data['tax_code_id'] = t[1] - if 'account_id' in fields: - data['account_id'] = t[0] - if 'tax_amount' in fields: - data['tax_amount'] = tax_amount - # - # Compute line for tax T - # - return data + if 'tax_code_id' in fields: + data['tax_code_id'] = t[1] + if 'account_id' in fields: + data['account_id'] = t[0] + if 'tax_amount' in fields: + data['tax_amount'] = tax_amount + # + # Compute line for tax T + # + return data - # - # Compute latest line - # - if ('debit' in fields) or ('credit' in fields): - data['credit'] = total>0 and total - data['debit'] = total<0 and -total - if 'account_id' in fields: - if total >= 0: - data['account_id'] = move.journal_id.default_credit_account_id.id or False - else: - data['account_id'] = move.journal_id.default_debit_account_id.id or False - if 'account_id' in fields and data['account_id']: - account = self.pool.get('account.account').browse(cr, uid, data['account_id']) - data['tax_code_id'] = self._default_get_tax(cr, uid, account ) - return data + # + # Compute latest line + # + if ('debit' in fields) or ('credit' in fields): + data['credit'] = total>0 and total + data['debit'] = total<0 and -total + if 'account_id' in fields: + if total >= 0: + data['account_id'] = move.journal_id.default_credit_account_id.id or False + else: + data['account_id'] = move.journal_id.default_debit_account_id.id or False + if 'account_id' in fields and data['account_id']: + account = self.pool.get('account.account').browse(cr, uid, data['account_id']) + data['tax_code_id'] = self._default_get_tax(cr, uid, account ) + return data - def _default_get_tax(self, cr, uid, account, debit=0, credit=0, context={}): - if account.tax_ids: - return account.tax_ids[0].base_code_id.id - return False + def _default_get_tax(self, cr, uid, account, debit=0, credit=0, context={}): + if account.tax_ids: + return account.tax_ids[0].base_code_id.id + return False - def _on_create_write(self, cr, uid, id, context={}): - ml = self.browse(cr, uid, id, context) - return map(lambda x: x.id, ml.move_id.line_id) + def _on_create_write(self, cr, uid, id, context={}): + ml = self.browse(cr, uid, id, context) + return map(lambda x: x.id, ml.move_id.line_id) - def _balance(self, cr, uid, ids, prop, unknow_none, unknow_dict): - res={} - # TODO group the foreach in sql - for id in ids: - cr.execute('SELECT date,account_id FROM account_move_line WHERE id=%d', (id,)) - dt, acc = cr.fetchone() - cr.execute('SELECT SUM(debit-credit) FROM account_move_line WHERE account_id=%d AND (date<%s OR (date=%s AND id<=%d)) and active', (acc,dt,dt,id)) - res[id] = cr.fetchone()[0] - return res + def _balance(self, cr, uid, ids, prop, unknow_none, unknow_dict): + res={} + # TODO group the foreach in sql + for id in ids: + cr.execute('SELECT date,account_id FROM account_move_line WHERE id=%d', (id,)) + dt, acc = cr.fetchone() + cr.execute('SELECT SUM(debit-credit) FROM account_move_line WHERE account_id=%d AND (date<%s OR (date=%s AND id<=%d)) and active', (acc,dt,dt,id)) + res[id] = cr.fetchone()[0] + return res - def _invoice(self, cursor, user, ids, name, arg, context=None): - invoice_obj = self.pool.get('account.invoice') - res = {} - for line_id in ids: - res[line_id] = False - cursor.execute('SELECT l.id, i.id ' \ - 'FROM account_move_line l, account_invoice i ' \ - 'WHERE l.move_id = i.move_id ' \ - 'AND l.id in (' + ','.join([str(x) for x in ids]) + ')') - invoice_ids = [] - for line_id, invoice_id in cursor.fetchall(): - res[line_id] = invoice_id - invoice_ids.append(invoice_id) - invoice_names = {False: ''} - for invoice_id, name in invoice_obj.name_get(cursor, user, - invoice_ids, context=context): - invoice_names[invoice_id] = name - for line_id in res.keys(): - invoice_id = res[line_id] - res[line_id] = (invoice_id, invoice_names[invoice_id]) - return res + def _invoice(self, cursor, user, ids, name, arg, context=None): + invoice_obj = self.pool.get('account.invoice') + res = {} + for line_id in ids: + res[line_id] = False + cursor.execute('SELECT l.id, i.id ' \ + 'FROM account_move_line l, account_invoice i ' \ + 'WHERE l.move_id = i.move_id ' \ + 'AND l.id in (' + ','.join([str(x) for x in ids]) + ')') + invoice_ids = [] + for line_id, invoice_id in cursor.fetchall(): + res[line_id] = invoice_id + invoice_ids.append(invoice_id) + invoice_names = {False: ''} + for invoice_id, name in invoice_obj.name_get(cursor, user, + invoice_ids, context=context): + invoice_names[invoice_id] = name + for line_id in res.keys(): + invoice_id = res[line_id] + res[line_id] = (invoice_id, invoice_names[invoice_id]) + return res - def name_get(self, cr, uid, ids, context={}): - if not len(ids): - return [] - result = [] - for line in self.browse(cr, uid, ids, context): - if line.ref: - result.append((line.id, (line.name or '')+' ('+line.ref+')')) - else: - result.append((line.id, line.name)) - return result + def name_get(self, cr, uid, ids, context={}): + if not len(ids): + return [] + result = [] + for line in self.browse(cr, uid, ids, context): + if line.ref: + result.append((line.id, (line.name or '')+' ('+line.ref+')')) + else: + result.append((line.id, line.name)) + return result - def _invoice_search(self, cursor, user, obj, name, args): - if not len(args): - return [] - invoice_obj = self.pool.get('account.invoice') + def _invoice_search(self, cursor, user, obj, name, args): + if not len(args): + return [] + invoice_obj = self.pool.get('account.invoice') - i = 0 - while i < len(args): - fargs = args[i][0].split('.', 1) - if len(fargs) > 1: - args[i] = (frags[0], 'in', invoice_obj.search(cursor, user, - [(fargs[1], args[i][1], args[i][2])])) - i += 1 - continue - if isinstance(args[i][2], basestring): - res_ids = invoice_obj.name_search(cursor, user, args[i][2], [], - args[i][1]) - args[i] = (args[i][0], 'in', [x[0] for x in res_ids]) - i += 1 - qu1, qu2 = [], [] - for x in args: - if x[1] != 'in': - if (x[2] is False) and (x[1] == '='): - qu1.append('(i.id IS NULL)') - elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='): - qu1.append('(i.id IS NOT NULL)') - else: - qu1.append('(i.id %s %s)' % (x[1], '%d')) - qu2.append(x[2]) - elif x[1] == 'in': - if len(x[2]) > 0: - qu1.append('(i.id in (%s))' % (','.join(['%d'] * len(x[2])))) - qu2 += x[2] - else: - qu1.append(' (False)') - if len(qu1): - qu1 = ' AND' + ' AND'.join(qu1) - else: - qu1 = '' - cursor.execute('SELECT l.id ' \ - 'FROM account_move_line l, account_invoice i ' \ - 'WHERE l.move_id = i.move_id ' + qu1, qu2) - res = cursor.fetchall() - if not len(res): - return [('id', '=', '0')] - return [('id', 'in', [x[0] for x in res])] + i = 0 + while i < len(args): + fargs = args[i][0].split('.', 1) + if len(fargs) > 1: + args[i] = (frags[0], 'in', invoice_obj.search(cursor, user, + [(fargs[1], args[i][1], args[i][2])])) + i += 1 + continue + if isinstance(args[i][2], basestring): + res_ids = invoice_obj.name_search(cursor, user, args[i][2], [], + args[i][1]) + args[i] = (args[i][0], 'in', [x[0] for x in res_ids]) + i += 1 + qu1, qu2 = [], [] + for x in args: + if x[1] != 'in': + if (x[2] is False) and (x[1] == '='): + qu1.append('(i.id IS NULL)') + elif (x[2] is False) and (x[1] == '<>' or x[1] == '!='): + qu1.append('(i.id IS NOT NULL)') + else: + qu1.append('(i.id %s %s)' % (x[1], '%d')) + qu2.append(x[2]) + elif x[1] == 'in': + if len(x[2]) > 0: + qu1.append('(i.id in (%s))' % (','.join(['%d'] * len(x[2])))) + qu2 += x[2] + else: + qu1.append(' (False)') + if len(qu1): + qu1 = ' AND' + ' AND'.join(qu1) + else: + qu1 = '' + cursor.execute('SELECT l.id ' \ + 'FROM account_move_line l, account_invoice i ' \ + 'WHERE l.move_id = i.move_id ' + qu1, qu2) + res = cursor.fetchall() + if not len(res): + return [('id', '=', '0')] + return [('id', 'in', [x[0] for x in res])] - _columns = { - 'name': fields.char('Name', size=64, required=True), - 'quantity': fields.float('Quantity', digits=(16,2), help="The optionnal quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very usefull for some reports."), - 'debit': fields.float('Debit', digits=(16,2)), - 'credit': fields.float('Credit', digits=(16,2)), - 'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade", domain=[('type','<>','view'), ('type', '<>', 'closed')], select=2), + _columns = { + 'name': fields.char('Name', size=64, required=True), + 'quantity': fields.float('Quantity', digits=(16,2), help="The optionnal quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very usefull for some reports."), + 'debit': fields.float('Debit', digits=(16,2)), + 'credit': fields.float('Credit', digits=(16,2)), + 'account_id': fields.many2one('account.account', 'Account', required=True, ondelete="cascade", domain=[('type','<>','view'), ('type', '<>', 'closed')], select=2), - 'move_id': fields.many2one('account.move', 'Move', ondelete="cascade", states={'valid':[('readonly',True)]}, help="The move of this entry line.", select=2), + 'move_id': fields.many2one('account.move', 'Move', ondelete="cascade", states={'valid':[('readonly',True)]}, help="The move of this entry line.", select=2), - 'ref': fields.char('Ref.', size=32), - 'statement_id': fields.many2one('account.bank.statement', 'Statement', help="The bank statement used for bank reconciliation", select=1), - 'reconcile_id': fields.many2one('account.move.reconcile', 'Reconcile', readonly=True, ondelete='set null', select=2), - 'reconcile_partial_id': fields.many2one('account.move.reconcile', 'Partial Reconcile', readonly=True, ondelete='set null', select=2), - 'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optionnal other currency if it is a multi-currency entry."), - 'currency_id': fields.many2one('res.currency', 'Currency', help="The optionnal other currency if it is a multi-currency entry."), + 'ref': fields.char('Ref.', size=32), + 'statement_id': fields.many2one('account.bank.statement', 'Statement', help="The bank statement used for bank reconciliation", select=1), + 'reconcile_id': fields.many2one('account.move.reconcile', 'Reconcile', readonly=True, ondelete='set null', select=2), + 'reconcile_partial_id': fields.many2one('account.move.reconcile', 'Partial Reconcile', readonly=True, ondelete='set null', select=2), + 'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optionnal other currency if it is a multi-currency entry."), + 'currency_id': fields.many2one('res.currency', 'Currency', help="The optionnal other currency if it is a multi-currency entry."), - 'period_id': fields.many2one('account.period', 'Period', required=True), - 'journal_id': fields.many2one('account.journal', 'Journal', required=True), - 'blocked': fields.boolean('Litigation', help="You can check this box to mark the entry line as a litigation with the associated partner"), + 'period_id': fields.many2one('account.period', 'Period', required=True), + 'journal_id': fields.many2one('account.journal', 'Journal', required=True), + 'blocked': fields.boolean('Litigation', help="You can check this box to mark the entry line as a litigation with the associated partner"), - 'partner_id': fields.many2one('res.partner', 'Partner Ref.'), - 'date_maturity': fields.date('Maturity date', help="This field is used for payable and receivable entries. You can put the limit date for the payment of this entry line."), - 'date': fields.date('Effective date', required=True), - 'date_created': fields.date('Creation date'), - 'analytic_lines': fields.one2many('account.analytic.line', 'move_id', 'Analytic lines'), - 'centralisation': fields.selection([('normal','Normal'),('credit','Credit Centralisation'),('debit','Debit Centralisation')], 'Centralisation', size=6), - 'balance': fields.function(_balance, method=True, string='Balance'), - 'active': fields.boolean('Active'), - 'state': fields.selection([('draft','Draft'), ('valid','Valid')], 'State', readonly=True), - 'tax_code_id': fields.many2one('account.tax.code', 'Tax Account'), - 'tax_amount': fields.float('Tax/Base Amount', digits=(16,2), select=True), - 'invoice': fields.function(_invoice, method=True, string='Invoice', - type='many2one', relation='account.invoice', fnct_search=_invoice_search), - } + 'partner_id': fields.many2one('res.partner', 'Partner Ref.'), + 'date_maturity': fields.date('Maturity date', help="This field is used for payable and receivable entries. You can put the limit date for the payment of this entry line."), + 'date': fields.date('Effective date', required=True), + 'date_created': fields.date('Creation date'), + 'analytic_lines': fields.one2many('account.analytic.line', 'move_id', 'Analytic lines'), + 'centralisation': fields.selection([('normal','Normal'),('credit','Credit Centralisation'),('debit','Debit Centralisation')], 'Centralisation', size=6), + 'balance': fields.function(_balance, method=True, string='Balance'), + 'active': fields.boolean('Active'), + 'state': fields.selection([('draft','Draft'), ('valid','Valid')], 'State', readonly=True), + 'tax_code_id': fields.many2one('account.tax.code', 'Tax Account'), + 'tax_amount': fields.float('Tax/Base Amount', digits=(16,2), select=True), + 'invoice': fields.function(_invoice, method=True, string='Invoice', + type='many2one', relation='account.invoice', fnct_search=_invoice_search), + } - def _get_date(self, cr, uid, context): - period_obj = self.pool.get('account.period') - dt = time.strftime('%Y-%m-%d') - if ('journal_id' in context) and ('period_id' in context): - cr.execute('select date from account_move_line ' \ - 'where journal_id=%d and period_id=%d ' \ - 'order by id desc limit 1', - (context['journal_id'], context['period_id'])) - res = cr.fetchone() - if res: - dt = res[0] - else: - period = period_obj.browse(cr, uid, context['period_id'], - context=context) - dt = period.date_start - return dt - _defaults = { - 'blocked': lambda *a: False, - 'active': lambda *a: True, - 'centralisation': lambda *a: 'normal', - 'date': _get_date, - 'date_created': lambda *a: time.strftime('%Y-%m-%d'), - 'state': lambda *a: 'draft', - 'journal_id': lambda self, cr, uid, c: c.get('journal_id', False), - 'period_id': lambda self, cr, uid, c: c.get('period_id', False), - } - _order = "date desc,id desc" - _sql_constraints = [ - ('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in accounting entry !'), - ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in accounting entry !'), - ] + def _get_date(self, cr, uid, context): + period_obj = self.pool.get('account.period') + dt = time.strftime('%Y-%m-%d') + if ('journal_id' in context) and ('period_id' in context): + cr.execute('select date from account_move_line ' \ + 'where journal_id=%d and period_id=%d ' \ + 'order by id desc limit 1', + (context['journal_id'], context['period_id'])) + res = cr.fetchone() + if res: + dt = res[0] + else: + period = period_obj.browse(cr, uid, context['period_id'], + context=context) + dt = period.date_start + return dt + _defaults = { + 'blocked': lambda *a: False, + 'active': lambda *a: True, + 'centralisation': lambda *a: 'normal', + 'date': _get_date, + 'date_created': lambda *a: time.strftime('%Y-%m-%d'), + 'state': lambda *a: 'draft', + 'journal_id': lambda self, cr, uid, c: c.get('journal_id', False), + 'period_id': lambda self, cr, uid, c: c.get('period_id', False), + } + _order = "date desc,id desc" + _sql_constraints = [ + ('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in accounting entry !'), + ('credit_debit2', 'CHECK (credit+debit>=0)', 'Wrong credit or debit value in accounting entry !'), + ] - def _auto_init(self, cr, context={}): - super(account_move_line, self)._auto_init(cr, context) - cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'account_move_line_journal_id_period_id_index\'') - if not cr.fetchone(): - cr.execute('CREATE INDEX account_move_line_journal_id_period_id_index ON account_move_line (journal_id, period_id)') - cr.commit() + def _auto_init(self, cr, context={}): + super(account_move_line, self)._auto_init(cr, context) + cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'account_move_line_journal_id_period_id_index\'') + if not cr.fetchone(): + cr.execute('CREATE INDEX account_move_line_journal_id_period_id_index ON account_move_line (journal_id, period_id)') + cr.commit() - def _check_no_view(self, cr, uid, ids): - lines = self.browse(cr, uid, ids) - for l in lines: - if l.account_id.type == 'view': - return False - return True + def _check_no_view(self, cr, uid, ids): + lines = self.browse(cr, uid, ids) + for l in lines: + if l.account_id.type == 'view': + return False + return True - def _check_no_closed(self, cr, uid, ids): - lines = self.browse(cr, uid, ids) - for l in lines: - if l.account_id.type == 'closed': - return False - return True + def _check_no_closed(self, cr, uid, ids): + lines = self.browse(cr, uid, ids) + for l in lines: + if l.account_id.type == 'closed': + return False + return True - _constraints = [ - (_check_no_view, 'You can not create move line on view account.', ['account_id']), - (_check_no_closed, 'You can not create move line on closed account.', ['account_id']), - ] + _constraints = [ + (_check_no_view, 'You can not create move line on view account.', ['account_id']), + (_check_no_closed, 'You can not create move line on closed account.', ['account_id']), + ] - def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, journal=False): - if (not partner_id) or account_id: - return {} - part = self.pool.get('res.partner').browse(cr, uid, partner_id) - id1 = part.property_account_payable.id - id2 = part.property_account_receivable.id - cr.execute('select sum(debit-credit) from account_move_line where (reconcile_id is null) and partner_id=%d and account_id=%d', (partner_id, id2)) - balance = cr.fetchone()[0] or 0.0 - val = {} - if (not debit) and (not credit): - if abs(balance)>0.01: - val['credit'] = ((balance>0) and balance) or 0 - val['debit'] = ((balance<0) and -balance) or 0 - val['account_id'] = id2 - else: - cr.execute('select sum(debit-credit) from account_move_line where (reconcile_id is null) and partner_id=%d and account_id=%d', (partner_id, id1)) - balance = cr.fetchone()[0] or 0.0 - val['credit'] = ((balance>0) and balance) or 0 - val['debit'] = ((balance<0) and -balance) or 0 - val['account_id'] = id1 - else: - val['account_id'] = (debit>0) and id2 or id1 - if journal: - jt = self.pool.get('account.journal').browse(cr, uid, journal).type - if jt=='sale': - val['account_id'] = id2 - elif jt=='purchase': - val['account_id'] = id1 - return {'value':val} + def onchange_partner_id(self, cr, uid, ids, move_id, partner_id, account_id=None, debit=0, credit=0, journal=False): + if (not partner_id) or account_id: + return {} + part = self.pool.get('res.partner').browse(cr, uid, partner_id) + id1 = part.property_account_payable.id + id2 = part.property_account_receivable.id + cr.execute('select sum(debit-credit) from account_move_line where (reconcile_id is null) and partner_id=%d and account_id=%d', (partner_id, id2)) + balance = cr.fetchone()[0] or 0.0 + val = {} + if (not debit) and (not credit): + if abs(balance)>0.01: + val['credit'] = ((balance>0) and balance) or 0 + val['debit'] = ((balance<0) and -balance) or 0 + val['account_id'] = id2 + else: + cr.execute('select sum(debit-credit) from account_move_line where (reconcile_id is null) and partner_id=%d and account_id=%d', (partner_id, id1)) + balance = cr.fetchone()[0] or 0.0 + val['credit'] = ((balance>0) and balance) or 0 + val['debit'] = ((balance<0) and -balance) or 0 + val['account_id'] = id1 + else: + val['account_id'] = (debit>0) and id2 or id1 + if journal: + jt = self.pool.get('account.journal').browse(cr, uid, journal).type + if jt=='sale': + val['account_id'] = id2 + elif jt=='purchase': + val['account_id'] = id1 + return {'value':val} - # - # type: the type if reconciliation (no logic behind this field, for info) - # - # writeoff; entry generated for the difference between the lines - # + # + # type: the type if reconciliation (no logic behind this field, for info) + # + # writeoff; entry generated for the difference between the lines + # - def reconcile_partial(self, cr, uid, ids, type='auto', context={}): - merges = [] - unmerge = [] - total = 0.0 - merges_rec = [] - for line in self.browse(cr, uid, ids, context): - if line.reconcile_id: - raise _('Already Reconciled') - if line.reconcile_partial_id: - for line2 in line.reconcile_partial_id.line_partial_ids: - if not line2.reconcile_id: - merges.append(line2.id) - total += (line2.debit or 0.0) - (line2.credit or 0.0) - merges_rec.append(line.reconcile_partial_id.id) - else: - unmerge.append(line.id) - total += (line.debit or 0.0) - (line.credit or 0.0) - if not total: - return self.reconcile(cr, uid, merges+unmerge, context=context) - r_id = self.pool.get('account.move.reconcile').create(cr, uid, { - 'type': type, - 'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge) - }) - self.pool.get('account.move.reconcile').reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context) - return True + def reconcile_partial(self, cr, uid, ids, type='auto', context={}): + merges = [] + unmerge = [] + total = 0.0 + merges_rec = [] + for line in self.browse(cr, uid, ids, context): + if line.reconcile_id: + raise _('Already Reconciled') + if line.reconcile_partial_id: + for line2 in line.reconcile_partial_id.line_partial_ids: + if not line2.reconcile_id: + merges.append(line2.id) + total += (line2.debit or 0.0) - (line2.credit or 0.0) + merges_rec.append(line.reconcile_partial_id.id) + else: + unmerge.append(line.id) + total += (line.debit or 0.0) - (line.credit or 0.0) + if not total: + return self.reconcile(cr, uid, merges+unmerge, context=context) + r_id = self.pool.get('account.move.reconcile').create(cr, uid, { + 'type': type, + 'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge) + }) + self.pool.get('account.move.reconcile').reconcile_partial_check(cr, uid, [r_id] + merges_rec, context=context) + return True - def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context={}): - id_set = ','.join(map(str, ids)) - lines = self.browse(cr, uid, ids, context=context) - unrec_lines = filter(lambda x: not x['reconcile_id'], lines) - credit = debit = 0.0 - currency = 0.0 - account_id = False - partner_id = False - for line in unrec_lines: - if line.state <> 'valid': - raise osv.except_osv(_('Error'), - _('Entry "%s" is not valid !') % line.name) - credit += line['credit'] - debit += line['debit'] - currency += line['amount_currency'] or 0.0 - account_id = line['account_id']['id'] - partner_id = (line['partner_id'] and line['partner_id']['id']) or False - writeoff = debit - credit - date = time.strftime('%Y-%m-%d') + def reconcile(self, cr, uid, ids, type='auto', writeoff_acc_id=False, writeoff_period_id=False, writeoff_journal_id=False, context={}): + id_set = ','.join(map(str, ids)) + lines = self.browse(cr, uid, ids, context=context) + unrec_lines = filter(lambda x: not x['reconcile_id'], lines) + credit = debit = 0.0 + currency = 0.0 + account_id = False + partner_id = False + for line in unrec_lines: + if line.state <> 'valid': + raise osv.except_osv(_('Error'), + _('Entry "%s" is not valid !') % line.name) + credit += line['credit'] + debit += line['debit'] + currency += line['amount_currency'] or 0.0 + account_id = line['account_id']['id'] + partner_id = (line['partner_id'] and line['partner_id']['id']) or False + writeoff = debit - credit + date = time.strftime('%Y-%m-%d') - cr.execute('SELECT account_id, reconcile_id \ - FROM account_move_line \ - WHERE id IN ('+id_set+') \ - GROUP BY account_id,reconcile_id') - r = cr.fetchall() + cr.execute('SELECT account_id, reconcile_id \ + FROM account_move_line \ + WHERE id IN ('+id_set+') \ + GROUP BY account_id,reconcile_id') + r = cr.fetchall() #TODO: move this check to a constraint in the account_move_reconcile object - if len(r) != 1: - raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! ')) - account = self.pool.get('account.account').browse(cr, uid, account_id, context=context) - if not account.reconcile: - raise osv.except_osv(_('Error'), _('The account is not defined to be reconcile !')) - if r[0][1] != None: - raise osv.except_osv(_('Error'), _('Some entries are already reconciled !')) + if len(r) != 1: + raise osv.except_osv(_('Error'), _('Entries are not of the same account or already reconciled ! ')) + account = self.pool.get('account.account').browse(cr, uid, account_id, context=context) + if not account.reconcile: + raise osv.except_osv(_('Error'), _('The account is not defined to be reconcile !')) + if r[0][1] != None: + raise osv.except_osv(_('Error'), _('Some entries are already reconciled !')) - if (not self.pool.get('res.currency').is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \ - (account.currency_id and (not self.pool.get('res.currency').is_zero(cr, uid, account.currency_id, currency))): - if not writeoff_acc_id: - raise osv.except_osv(_('Warning'), _('You have to provide an account for the write off entry !')) - if writeoff > 0: - debit = writeoff - credit = 0.0 - self_credit = writeoff - self_debit = 0.0 - else: - debit = 0.0 - credit = -writeoff - self_credit = 0.0 - self_debit = -writeoff + if (not self.pool.get('res.currency').is_zero(cr, uid, account.company_id.currency_id, writeoff)) or \ + (account.currency_id and (not self.pool.get('res.currency').is_zero(cr, uid, account.currency_id, currency))): + if not writeoff_acc_id: + raise osv.except_osv(_('Warning'), _('You have to provide an account for the write off entry !')) + if writeoff > 0: + debit = writeoff + credit = 0.0 + self_credit = writeoff + self_debit = 0.0 + else: + debit = 0.0 + credit = -writeoff + self_credit = 0.0 + self_debit = -writeoff - writeoff_lines = [ - (0, 0, { - 'name':'Write-Off', - 'debit':self_debit, - 'credit':self_credit, - 'account_id':account_id, - 'date':date, - 'partner_id':partner_id, - 'currency_id': account.currency_id.id or False, - 'amount_currency': account.currency_id.id and -currency or 0.0 - }), - (0, 0, { - 'name':'Write-Off', - 'debit':debit, - 'credit':credit, - 'account_id':writeoff_acc_id, - 'date':date, - 'partner_id':partner_id - }) - ] + writeoff_lines = [ + (0, 0, { + 'name':'Write-Off', + 'debit':self_debit, + 'credit':self_credit, + 'account_id':account_id, + 'date':date, + 'partner_id':partner_id, + 'currency_id': account.currency_id.id or False, + 'amount_currency': account.currency_id.id and -currency or 0.0 + }), + (0, 0, { + 'name':'Write-Off', + 'debit':debit, + 'credit':credit, + 'account_id':writeoff_acc_id, + 'date':date, + 'partner_id':partner_id + }) + ] - name = 'Write-Off' - if writeoff_journal_id: - journal = self.pool.get('account.journal').browse(cr, uid, writeoff_journal_id) - if journal.sequence_id: - name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) + name = 'Write-Off' + if writeoff_journal_id: + journal = self.pool.get('account.journal').browse(cr, uid, writeoff_journal_id) + if journal.sequence_id: + name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) - writeoff_move_id = self.pool.get('account.move').create(cr, uid, { - 'name': name, - 'period_id': writeoff_period_id, - 'journal_id': writeoff_journal_id, + writeoff_move_id = self.pool.get('account.move').create(cr, uid, { + 'name': name, + 'period_id': writeoff_period_id, + 'journal_id': writeoff_journal_id, - 'state': 'draft', - 'line_id': writeoff_lines - }) + 'state': 'draft', + 'line_id': writeoff_lines + }) - writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)]) - ids += writeoff_line_ids + writeoff_line_ids = self.search(cr, uid, [('move_id', '=', writeoff_move_id), ('account_id', '=', account_id)]) + ids += writeoff_line_ids - r_id = self.pool.get('account.move.reconcile').create(cr, uid, { - #'name': date, - 'type': type, - 'line_id': map(lambda x: (4,x,False), ids), - 'line_partial_ids': map(lambda x: (3,x,False), ids) - }) - # the id of the move.reconcile is written in the move.line (self) by the create method above - # because of the way the line_id are defined: (4, x, False) - wf_service = netsvc.LocalService("workflow") - for id in ids: - wf_service.trg_trigger(uid, 'account.move.line', id, cr) - return r_id + r_id = self.pool.get('account.move.reconcile').create(cr, uid, { + #'name': date, + 'type': type, + 'line_id': map(lambda x: (4,x,False), ids), + 'line_partial_ids': map(lambda x: (3,x,False), ids) + }) + # the id of the move.reconcile is written in the move.line (self) by the create method above + # because of the way the line_id are defined: (4, x, False) + wf_service = netsvc.LocalService("workflow") + for id in ids: + wf_service.trg_trigger(uid, 'account.move.line', id, cr) + return r_id - def view_header_get(self, cr, user, view_id, view_type, context): - if (not context.get('journal_id', False)) or (not context.get('period_id', False)): - return False - cr.execute('select code from account_journal where id=%d', (context['journal_id'],)) - j = cr.fetchone()[0] or '' - cr.execute('select code from account_period where id=%d', (context['period_id'],)) - p = cr.fetchone()[0] or '' - if j or p: - return j+':'+p - return 'Journal' + def view_header_get(self, cr, user, view_id, view_type, context): + if (not context.get('journal_id', False)) or (not context.get('period_id', False)): + return False + cr.execute('select code from account_journal where id=%d', (context['journal_id'],)) + j = cr.fetchone()[0] or '' + cr.execute('select code from account_period where id=%d', (context['period_id'],)) + p = cr.fetchone()[0] or '' + if j or p: + return j+':'+p + return 'Journal' - def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False): - result = super(osv.osv, self).fields_view_get(cr, uid, view_id,view_type,context) - if view_type=='tree' and 'journal_id' in context: - title = self.view_header_get(cr, uid, view_id, view_type, context) - journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id']) + def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False): + result = super(osv.osv, self).fields_view_get(cr, uid, view_id,view_type,context) + if view_type=='tree' and 'journal_id' in context: + title = self.view_header_get(cr, uid, view_id, view_type, context) + journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id']) - # if the journal view has a state field, color lines depending on - # its value - state = '' - for field in journal.view_id.columns_id: - if field.field=='state': - state = ' colors="red:state==\'draft\'"' + # if the journal view has a state field, color lines depending on + # its value + state = '' + for field in journal.view_id.columns_id: + if field.field=='state': + state = ' colors="red:state==\'draft\'"' - #xml = '''\n\n\t''' % (title, state) - xml = '''\n\n\t''' % (title, state) - fields = [] + #xml = '''\n\n\t''' % (title, state) + xml = '''\n\n\t''' % (title, state) + fields = [] - widths = { - 'ref': 50, - 'statement_id': 50, - 'state': 60, - 'tax_code_id': 50, - 'move_id': 40, - } - for field in journal.view_id.columns_id: - fields.append(field.field) - attrs = [] - if field.field=='debit': - attrs.append('sum="Total debit"') - elif field.field=='credit': - attrs.append('sum="Total credit"') - elif field.field=='account_id' and journal.id: - attrs.append('domain="[(\'journal_id\', \'=\', '+str(journal.id)+'),(\'type\',\'<>\',\'view\'), (\'type\',\'<>\',\'closed\')]"') - if field.readonly: - attrs.append('readonly="1"') - if field.required: - attrs.append('required="1"') - else: - attrs.append('required="0"') - if field.field == 'partner_id': - attrs.append('on_change="onchange_partner_id(move_id,partner_id,account_id,debit,credit,((\'journal_id\' in context) and context[\'journal_id\']) or {})"') - if field.field in widths: - attrs.append('width="'+str(widths[field.field])+'"') - xml += '''\n''' % (field.field,' '.join(attrs)) + widths = { + 'ref': 50, + 'statement_id': 50, + 'state': 60, + 'tax_code_id': 50, + 'move_id': 40, + } + for field in journal.view_id.columns_id: + fields.append(field.field) + attrs = [] + if field.field=='debit': + attrs.append('sum="Total debit"') + elif field.field=='credit': + attrs.append('sum="Total credit"') + elif field.field=='account_id' and journal.id: + attrs.append('domain="[(\'journal_id\', \'=\', '+str(journal.id)+'),(\'type\',\'<>\',\'view\'), (\'type\',\'<>\',\'closed\')]"') + if field.readonly: + attrs.append('readonly="1"') + if field.required: + attrs.append('required="1"') + else: + attrs.append('required="0"') + if field.field == 'partner_id': + attrs.append('on_change="onchange_partner_id(move_id,partner_id,account_id,debit,credit,((\'journal_id\' in context) and context[\'journal_id\']) or {})"') + if field.field in widths: + attrs.append('width="'+str(widths[field.field])+'"') + xml += '''\n''' % (field.field,' '.join(attrs)) - xml += '''''' - result['arch'] = xml - result['fields'] = self.fields_get(cr, uid, fields, context) - return result + xml += '''''' + result['arch'] = xml + result['fields'] = self.fields_get(cr, uid, fields, context) + return result - def unlink(self, cr, uid, ids, context={}, check=True): - self._update_check(cr, uid, ids, context) - result = False - for line in self.browse(cr, uid, ids, context): - context['journal_id']=line.journal_id.id - context['period_id']=line.period_id.id - result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context) - if check: - self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context=context) - return result + def unlink(self, cr, uid, ids, context={}, check=True): + self._update_check(cr, uid, ids, context) + result = False + for line in self.browse(cr, uid, ids, context): + context['journal_id']=line.journal_id.id + context['period_id']=line.period_id.id + result = super(account_move_line, self).unlink(cr, uid, [line.id], context=context) + if check: + self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context=context) + return result - def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True): - if not context: - context={} - account_obj = self.pool.get('account.account') + def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True): + if not context: + context={} + account_obj = self.pool.get('account.account') - if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']: - raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!')) - if update_check: - if ('account_id' in vals) or ('journal_id' in vals) or ('period_id' in vals) or ('move_id' in vals) or ('debit' in vals) or ('credit' in vals) or ('date' in vals): - self._update_check(cr, uid, ids, context) - result = super(osv.osv, self).write(cr, uid, ids, vals, context) - if check: - done = [] - for line in self.browse(cr, uid, ids): - if line.move_id.id not in done: - done.append(line.move_id.id) - self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context) - return result + if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']: + raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!')) + if update_check: + if ('account_id' in vals) or ('journal_id' in vals) or ('period_id' in vals) or ('move_id' in vals) or ('debit' in vals) or ('credit' in vals) or ('date' in vals): + self._update_check(cr, uid, ids, context) + result = super(osv.osv, self).write(cr, uid, ids, vals, context) + if check: + done = [] + for line in self.browse(cr, uid, ids): + if line.move_id.id not in done: + done.append(line.move_id.id) + self.pool.get('account.move').validate(cr, uid, [line.move_id.id], context) + return result - def _update_journal_check(self, cr, uid, journal_id, period_id, context={}): - cr.execute('select state from account_journal_period where journal_id=%d and period_id=%d', (journal_id, period_id)) - result = cr.fetchall() - for (state,) in result: - if state=='done': - raise osv.except_osv(_('Error !'), _('You can not add/modify entries in a closed journal.')) - if not result: - journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context) - period = self.pool.get('account.period').browse(cr, uid, period_id, context) - self.pool.get('account.journal.period').create(cr, uid, { - 'name': (journal.code or journal.name)+':'+(period.name or ''), - 'journal_id': journal.id, - 'period_id': period.id - }) - return True + def _update_journal_check(self, cr, uid, journal_id, period_id, context={}): + cr.execute('select state from account_journal_period where journal_id=%d and period_id=%d', (journal_id, period_id)) + result = cr.fetchall() + for (state,) in result: + if state=='done': + raise osv.except_osv(_('Error !'), _('You can not add/modify entries in a closed journal.')) + if not result: + journal = self.pool.get('account.journal').browse(cr, uid, journal_id, context) + period = self.pool.get('account.period').browse(cr, uid, period_id, context) + self.pool.get('account.journal.period').create(cr, uid, { + 'name': (journal.code or journal.name)+':'+(period.name or ''), + 'journal_id': journal.id, + 'period_id': period.id + }) + return True - def _update_check(self, cr, uid, ids, context={}): - done = {} - for line in self.browse(cr, uid, ids, context): - if line.move_id.state<>'draft': - raise osv.except_osv(_('Error !'), _('You can not do this modification on a confirmed entry ! Please note that you can just change some non important fields !')) - if line.reconcile_id: - raise osv.except_osv(_('Error !'), _('You can not do this modification on a reconciled entry ! Please note that you can just change some non important fields !')) - t = (line.journal_id.id, line.period_id.id) - if t not in done: - self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context) - done[t] = True - return True + def _update_check(self, cr, uid, ids, context={}): + done = {} + for line in self.browse(cr, uid, ids, context): + if line.move_id.state<>'draft': + raise osv.except_osv(_('Error !'), _('You can not do this modification on a confirmed entry ! Please note that you can just change some non important fields !')) + if line.reconcile_id: + raise osv.except_osv(_('Error !'), _('You can not do this modification on a reconciled entry ! Please note that you can just change some non important fields !')) + t = (line.journal_id.id, line.period_id.id) + if t not in done: + self._update_journal_check(cr, uid, line.journal_id.id, line.period_id.id, context) + done[t] = True + return True - def create(self, cr, uid, vals, context=None, check=True): - if not context: - context={} - account_obj = self.pool.get('account.account') + def create(self, cr, uid, vals, context=None, check=True): + if not context: + context={} + account_obj = self.pool.get('account.account') - if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']: - raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!')) - if 'journal_id' in vals and 'journal_id' not in context: - context['journal_id'] = vals['journal_id'] - if 'period_id' in vals and 'period_id' not in context: - context['period_id'] = vals['period_id'] - if 'journal_id' not in context and 'move_id' in vals: - m = self.pool.get('account.move').browse(cr, uid, vals['move_id']) - context['journal_id'] = m.journal_id.id - context['period_id'] = m.period_id.id - self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context) - move_id = vals.get('move_id', False) - journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id']) - if not move_id: - if journal.centralisation: - # use the first move ever created for this journal and period - cr.execute('select id, state, name from account_move where journal_id=%d and period_id=%d order by id limit 1', (context['journal_id'],context['period_id'])) - res = cr.fetchone() - if res: - if res[1] != 'draft': - raise osv.except_osv(_('UserError'), - _('The account move (%s) for centralisation ' \ - 'has been confirmed!') % res[2]) - vals['move_id'] = res[0] + if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']: + raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!')) + if 'journal_id' in vals and 'journal_id' not in context: + context['journal_id'] = vals['journal_id'] + if 'period_id' in vals and 'period_id' not in context: + context['period_id'] = vals['period_id'] + if 'journal_id' not in context and 'move_id' in vals: + m = self.pool.get('account.move').browse(cr, uid, vals['move_id']) + context['journal_id'] = m.journal_id.id + context['period_id'] = m.period_id.id + self._update_journal_check(cr, uid, context['journal_id'], context['period_id'], context) + move_id = vals.get('move_id', False) + journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id']) + if not move_id: + if journal.centralisation: + # use the first move ever created for this journal and period + cr.execute('select id, state, name from account_move where journal_id=%d and period_id=%d order by id limit 1', (context['journal_id'],context['period_id'])) + res = cr.fetchone() + if res: + if res[1] != 'draft': + raise osv.except_osv(_('UserError'), + _('The account move (%s) for centralisation ' \ + 'has been confirmed!') % res[2]) + vals['move_id'] = res[0] - if not vals.get('move_id', False): - if journal.sequence_id: - name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) - v = { - 'name': name, - 'period_id': context['period_id'], - 'journal_id': context['journal_id'] - } - move_id = self.pool.get('account.move').create(cr, uid, v, context) - vals['move_id'] = move_id - else: - raise osv.except_osv(_('No piece number !'), _('Can not create an automatic sequence for this piece !\n\nPut a sequence in the journal definition for automatic numbering or create a sequence manually for this piece.')) + if not vals.get('move_id', False): + if journal.sequence_id: + name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) + v = { + 'name': name, + 'period_id': context['period_id'], + 'journal_id': context['journal_id'] + } + move_id = self.pool.get('account.move').create(cr, uid, v, context) + vals['move_id'] = move_id + else: + raise osv.except_osv(_('No piece number !'), _('Can not create an automatic sequence for this piece !\n\nPut a sequence in the journal definition for automatic numbering or create a sequence manually for this piece.')) - ok = not (journal.type_control_ids or journal.account_control_ids) - if ('account_id' in vals): - account = account_obj.browse(cr, uid, vals['account_id']) - if journal.type_control_ids: - type = account.type - for t in journal.type_control_ids: - if type==t.code: - ok = True - break - if journal.account_control_ids and not ok: - for a in journal.account_control_ids: - if a.id==vals['account_id']: - ok = True - break - if (account.currency_id) and 'amount_currency' not in vals: - vals['currency_id'] = account.currency_id.id - cur_obj = self.pool.get('res.currency') - ctx = {} - if 'date' in vals: - ctx['date'] = vals['date'] - vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id, account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0), context=ctx) - if not ok: - raise osv.except_osv(_('Bad account !'), _('You can not use this general account in this journal !')) - result = super(osv.osv, self).create(cr, uid, vals, context) - if check: - self.pool.get('account.move').validate(cr, uid, [vals['move_id']], context) - return result + ok = not (journal.type_control_ids or journal.account_control_ids) + if ('account_id' in vals): + account = account_obj.browse(cr, uid, vals['account_id']) + if journal.type_control_ids: + type = account.type + for t in journal.type_control_ids: + if type==t.code: + ok = True + break + if journal.account_control_ids and not ok: + for a in journal.account_control_ids: + if a.id==vals['account_id']: + ok = True + break + if (account.currency_id) and 'amount_currency' not in vals: + vals['currency_id'] = account.currency_id.id + cur_obj = self.pool.get('res.currency') + ctx = {} + if 'date' in vals: + ctx['date'] = vals['date'] + vals['amount_currency'] = cur_obj.compute(cr, uid, account.company_id.currency_id.id, account.currency_id.id, vals.get('debit', 0.0)-vals.get('credit', 0.0), context=ctx) + if not ok: + raise osv.except_osv(_('Bad account !'), _('You can not use this general account in this journal !')) + result = super(osv.osv, self).create(cr, uid, vals, context) + if check: + self.pool.get('account.move').validate(cr, uid, [vals['move_id']], context) + return result account_move_line() class account_bank_statement_reconcile(osv.osv): - _inherit = "account.bank.statement.reconcile" - _columns = { - 'line_ids': fields.many2many('account.move.line', 'account_bank_statement_line_rel', 'statement_id', 'line_id', 'Entries'), - } + _inherit = "account.bank.statement.reconcile" + _columns = { + 'line_ids': fields.many2many('account.move.line', 'account_bank_statement_line_rel', 'statement_id', 'line_id', 'Entries'), + } account_bank_statement_reconcile() diff --git a/addons/account/invoice.py b/addons/account/invoice.py index 3ec87e737d3..fea8fcccdfd 100644 --- a/addons/account/invoice.py +++ b/addons/account/invoice.py @@ -40,959 +40,959 @@ from tools import config from tools.translate import _ class account_invoice(osv.osv): - def _amount_untaxed(self, cr, uid, ids, name, args, context={}): - id_set=",".join(map(str,ids)) - cr.execute("SELECT s.id,COALESCE(SUM(l.price_subtotal),0)::decimal(16,2) AS amount FROM account_invoice s LEFT OUTER JOIN account_invoice_line l ON (s.id=l.invoice_id) WHERE s.id IN ("+id_set+") GROUP BY s.id ") - res=dict(cr.fetchall()) - return res - - def _amount_tax(self, cr, uid, ids, name, args, context={}): - id_set=",".join(map(str,ids)) - cr.execute("SELECT s.id,COALESCE(SUM(l.amount),0)::decimal(16,2) AS amount FROM account_invoice s LEFT OUTER JOIN account_invoice_tax l ON (s.id=l.invoice_id) WHERE s.id IN ("+id_set+") GROUP BY s.id ") - res=dict(cr.fetchall()) - return res - - def _amount_total(self, cr, uid, ids, name, args, context={}): - untax = self._amount_untaxed(cr, uid, ids, name, args, context) - tax = self._amount_tax(cr, uid, ids, name, args, context) - res = {} - for id in ids: - res[id] = untax.get(id,0.0) + tax.get(id,0.0) - return res - - def _get_journal(self, cr, uid, context): - type_inv = context.get('type', 'out_invoice') - type2journal = {'out_invoice': 'sale', 'in_invoice': 'purchase', 'out_refund': 'sale', 'in_refund': 'purchase'} - journal_obj = self.pool.get('account.journal') - res = journal_obj.search(cr, uid, [('type', '=', type2journal.get(type_inv, 'sale'))], limit=1) - if res: - return res[0] - else: - return False - - def _get_currency(self, cr, uid, context): - user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, [uid])[0] - if user.company_id: - return user.company_id.currency_id.id - else: - return pooler.get_pool(cr.dbname).get('res.currency').search(cr, uid, [('rate','=',1.0)])[0] - - def _get_journal_analytic(self, cr, uid, type_inv, context={}): - type2journal = {'out_invoice': 'sale', 'in_invoice': 'purchase', 'out_refund': 'sale', 'in_refund': 'purchase'} - tt = type2journal.get(type_inv, 'sale') - cr.execute("select id from account_analytic_journal where type=%s limit 1", (tt,)) - result = cr.fetchone() - if not result: - raise osv.except_osv(_('No Analytic Journal !'),("You have to define an analytic journal of type '%s' !") % (tt,)) - return result[0] - - def _get_type(self, cr, uid, context={}): - type = context.get('type', 'out_invoice') - return type - - def _reconciled(self, cr, uid, ids, name, args, context): - res = {} - for id in ids: - res[id] = self.test_paid(cr, uid, [id]) - return res - - def _get_reference_type(self, cursor, user, context=None): - return [('none', 'Free Reference')] - - _name = "account.invoice" - _description = 'Invoice' - _order = "number" - _columns = { - 'name': fields.char('Description', size=64, select=True,readonly=True, states={'draft':[('readonly',False)]}), - 'origin': fields.char('Origin', size=64), - 'type': fields.selection([ - ('out_invoice','Customer Invoice'), - ('in_invoice','Supplier Invoice'), - ('out_refund','Customer Refund'), - ('in_refund','Supplier Refund'), - ],'Type', readonly=True, select=True), - - 'number': fields.char('Invoice Number', size=32, readonly=True), - 'reference': fields.char('Invoice Reference', size=64), - 'reference_type': fields.selection(_get_reference_type, 'Reference Type', - required=True), - 'comment': fields.text('Additionnal Information'), - - 'state': fields.selection([ - ('draft','Draft'), - ('proforma','Pro-forma'), - ('open','Open'), - ('paid','Paid'), - ('cancel','Canceled') - ],'State', select=True, readonly=True), - - 'date_invoice': fields.date('Date Invoiced', required=True, states={'open':[('readonly',True)],'close':[('readonly',True)]}), - 'date_due': fields.date('Due Date', states={'open':[('readonly',True)],'close':[('readonly',True)]}), - - 'partner_id': fields.many2one('res.partner', 'Partner', change_default=True, readonly=True, required=True, states={'draft':[('readonly',False)]}), - 'address_contact_id': fields.many2one('res.partner.address', 'Contact Address', readonly=True, states={'draft':[('readonly',False)]}), - 'address_invoice_id': fields.many2one('res.partner.address', 'Invoice Address', readonly=True, required=True, states={'draft':[('readonly',False)]}), - - 'payment_term': fields.many2one('account.payment.term', 'Payment Term',readonly=True, states={'draft':[('readonly',False)]} ), - - 'period_id': fields.many2one('account.period', 'Force Period', help="Keep empty to use the period of the validation date."), - - 'account_id': fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}), - 'invoice_line': fields.one2many('account.invoice.line', 'invoice_id', 'Invoice Lines', readonly=True, states={'draft':[('readonly',False)]}), - 'tax_line': fields.one2many('account.invoice.tax', 'invoice_id', 'Tax Lines', readonly=True, states={'draft':[('readonly',False)]}), - - 'move_id': fields.many2one('account.move', 'Invoice Movement', readonly=True), - 'amount_untaxed': fields.function(_amount_untaxed, method=True, digits=(16,2),string='Untaxed', store=True), - 'amount_tax': fields.function(_amount_tax, method=True, digits=(16,2), string='Tax', store=True), - 'amount_total': fields.function(_amount_total, method=True, digits=(16,2), string='Total', store=True), - 'currency_id': fields.many2one('res.currency', 'Currency', required=True, readonly=True, states={'draft':[('readonly',False)]}), - 'journal_id': fields.many2one('account.journal', 'Journal', required=True,readonly=True, states={'draft':[('readonly',False)]}), - 'company_id': fields.many2one('res.company', 'Company', required=True), - 'check_total': fields.float('Total', digits=(16,2), states={'open':[('readonly',True)],'close':[('readonly',True)]}), - 'reconciled': fields.function(_reconciled, method=True, string='Reconciled', type='boolean'), - 'partner_bank': fields.many2one('res.partner.bank', 'Bank Account', - help='The bank account to pay or to be paid'), - } - _defaults = { - 'type': _get_type, - 'date_invoice': lambda *a: time.strftime('%Y-%m-%d'), - 'state': lambda *a: 'draft', - 'journal_id': _get_journal, - 'currency_id': _get_currency, - 'company_id': lambda self, cr, uid, context: \ - self.pool.get('res.users').browse(cr, uid, uid, - context=context).company_id.id, - 'reference_type': lambda *a: 'none', - } - - def unlink(self, cr, uid, ids): - invoices = self.read(cr, uid, ids, ['state']) - unlink_ids = [] - for t in invoices: - if t['state'] in ('draft', 'cancel'): - unlink_ids.append(t['id']) - else: - raise osv.except_osv(_('Invalid action !'), _('Cannot delete invoice(s) which are already opened or paid !')) - osv.osv.unlink(self, cr, uid, unlink_ids) - return True - -# def get_invoice_address(self, cr, uid, ids): -# res = self.pool.get('res.partner').address_get(cr, uid, [part], ['invoice']) -# return [{}] - - def onchange_partner_id(self, cr, uid, ids, type, partner_id, - date_invoice=False, payment_term=False, partner_bank_id=False): - invoice_addr_id = False - contact_addr_id = False - partner_payment_term = False - acc_id = False - bank_id = False - - opt = [('uid', str(uid))] - if partner_id: - - opt.insert(0, ('id', partner_id)) - res = self.pool.get('res.partner').address_get(cr, uid, [partner_id], ['contact', 'invoice']) - contact_addr_id = res['contact'] - invoice_addr_id = res['invoice'] - p = self.pool.get('res.partner').browse(cr, uid, partner_id) - if type in ('out_invoice', 'out_refund'): - acc_id = p.property_account_receivable.id - else: - acc_id = p.property_account_payable.id - - partner_payment_term = p.property_payment_term and p.property_payment_term.id or False - if p.bank_ids: - bank_id = p.bank_ids[0].id - - result = {'value': { - 'address_contact_id': contact_addr_id, - 'address_invoice_id': invoice_addr_id, - 'account_id': acc_id, - 'payment_term': partner_payment_term, - } - } - - if type in ('in_invoice', 'in_refund'): - result['value']['partner_bank'] = bank_id - - if payment_term != partner_payment_term: - if partner_payment_term: - to_update = self.onchange_payment_term_date_invoice( - cr,uid,ids,partner_payment_term,date_invoice) - result['value'].update(to_update['value']) - else: - result['value']['date_due'] = False - - if partner_bank_id != bank_id: - to_update = self.onchange_partner_bank(cr, uid, ids, bank_id) - result['value'].update(to_update['value']) - return result - - def onchange_currency_id(self, cr, uid, ids, curr_id): - return {} - - def onchange_payment_term_date_invoice(self, cr, uid, ids, payment_term_id, date_invoice): - if not payment_term_id: - return {} - res={} - pt_obj= self.pool.get('account.payment.term') - - if not date_invoice : - date_invoice = self._defaults["date_invoice"](cr,uid,{}) - - pterm_list= pt_obj.compute(cr, uid, payment_term_id, value=1, date_ref=date_invoice) - - if pterm_list: - pterm_list = [line[0] for line in pterm_list] - pterm_list.sort() - res= {'value':{'date_due': pterm_list[-1]}} - - return res - - def onchange_invoice_line(self, cr, uid, ids, lines): - return {} - - def onchange_partner_bank(self, cursor, user, ids, partner_bank_id): - return {'value': {}} - - # go from canceled state to draft state - def action_cancel_draft(self, cr, uid, ids, *args): - self.write(cr, uid, ids, {'state':'draft'}) - wf_service = netsvc.LocalService("workflow") - for inv_id in ids: - wf_service.trg_create(uid, 'account.invoice', inv_id, cr) - return True - - # Workflow stuff - ################# - - # return the ids of the move lines which has the same account than the invoice - # whose id is in ids - def move_line_id_payment_get(self, cr, uid, ids, *args): - ml = self.pool.get('account.move.line') - res = [] - for inv in self.read(cr, uid, ids, ['move_id','account_id']): - if inv['move_id']: - move_line_ids = ml.search(cr, uid, [('move_id', '=', inv['move_id'][0])]) - for line in ml.read(cr, uid, move_line_ids, ['account_id']): - if line['account_id']==inv['account_id']: - res.append(line['id']) - return res - - def copy(self, cr, uid, id, default=None, context=None): - if default is None: - default = {} - default = default.copy() - default.update({'state':'draft', 'number':False, 'move_id':False,}) - if 'date_invoice' not in default: - default['date_invoice'] = time.strftime('%Y-%m-%d') - if 'date_due' not in default: - default['date_due'] = False - return super(account_invoice, self).copy(cr, uid, id, default, context) - - def test_paid(self, cr, uid, ids, *args): - res = self.move_line_id_payment_get(cr, uid, ids) - if not res: - return False - ok = True - for id in res: - cr.execute('select reconcile_id from account_move_line where id=%d', (id,)) - ok = ok and bool(cr.fetchone()[0]) - return ok - - def button_reset_taxes(self, cr, uid, ids, context={}): - ait_obj = self.pool.get('account.invoice.tax') - for id in ids: - cr.execute("DELETE FROM account_invoice_tax WHERE invoice_id=%d", (id,)) - for taxe in ait_obj.compute(cr, uid, id).values(): - ait_obj.create(cr, uid, taxe) - return True - - def button_compute(self, cr, uid, ids, context={}, set_total=False): - ait_obj = self.pool.get('account.invoice.tax') - cur_obj = self.pool.get('res.currency') - for inv in self.browse(cr, uid, ids): - company_currency = inv.company_id.currency_id.id - compute_taxes = ait_obj.compute(cr, uid, inv.id) - if not inv.tax_line: - for tax in compute_taxes.values(): - ait_obj.create(cr, uid, tax) - else: - tax_key = [] - for tax in inv.tax_line: - if tax.manual: - continue - key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id) - tax_key.append(key) - if not key in compute_taxes: - ait_obj.unlink(cr, uid, [tax.id]) - continue - compute_taxes[key]['base'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, compute_taxes[key]['base'], context={'date': inv.date_invoice}) - if abs(compute_taxes[key]['base'] - tax.base) > inv.company_id.currency_id.rounding: - ait_obj.write(cr, uid, [tax.id], compute_taxes[key]) - for key in compute_taxes: - if not key in tax_key: - ait_obj.create(cr, uid, compute_taxes[key]) - if set_total: - self.pool.get('account.invoice').write(cr, uid, [inv.id], {'check_total': inv.amount_total}) - return True - - def _convert_ref(self, cr, uid, ref): - return (ref or '').replace('/','') - - def _get_analityc_lines(self, cr, uid, id): - inv = self.browse(cr, uid, [id])[0] - cur_obj = self.pool.get('res.currency') - - company_currency = inv.company_id.currency_id.id - if inv.type in ('out_invoice', 'in_refund'): - sign = 1 - else: - sign = -1 - - iml = self.pool.get('account.invoice.line').move_line_get(cr, uid, inv.id) - for il in iml: - if il['account_analytic_id']: - if inv.type in ('in_invoice', 'in_refund'): - ref = inv.reference - else: - ref = self._convert_ref(cr, uid, inv.number) - il['analytic_lines'] = [(0,0, { - 'name': il['name'], - 'date': inv['date_invoice'], - 'account_id': il['account_analytic_id'], - 'unit_amount': il['quantity'], - 'amount': cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, il['price'], context={'date': inv.date_invoice}) * sign, - 'product_id': il['product_id'], - 'product_uom_id': il['uos_id'], - 'general_account_id': il['account_id'], - 'journal_id': self._get_journal_analytic(cr, uid, inv.type), - 'ref': ref, - })] - return iml - - def action_move_create(self, cr, uid, ids, *args): - ait_obj = self.pool.get('account.invoice.tax') - cur_obj = self.pool.get('res.currency') - for inv in self.browse(cr, uid, ids): - if inv.move_id: - continue - if inv.type in ('in_invoice', 'in_refund') and abs(inv.check_total - inv.amount_total) >= (inv.currency_id.rounding/2.0): - raise osv.except_osv(_('Bad total !'), _('Please verify the price of the invoice !\nThe real total does not match the computed total.')) - company_currency = inv.company_id.currency_id.id - # create the analytical lines - line_ids = self.read(cr, uid, [inv.id], ['invoice_line'])[0]['invoice_line'] - ils = self.pool.get('account.invoice.line').read(cr, uid, line_ids) - # one move line per invoice line - iml = self._get_analityc_lines(cr, uid, inv.id) - # check if taxes are all computed - compute_taxes = ait_obj.compute(cr, uid, inv.id) - if not inv.tax_line: - for tax in compute_taxes.values(): - ait_obj.create(cr, uid, tax) - else: - tax_key = [] - for tax in inv.tax_line: - if tax.manual: - continue - key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id) - tax_key.append(key) - if not key in compute_taxes: - raise osv.except_osv(_('Warning !'), _('Global taxes defined, but not in invoice lines !')) - base = compute_taxes[key]['base'] - if abs(base - tax.base) > inv.company_id.currency_id.rounding: - raise osv.except_osv(_('Warning !'), _('Tax base different !\nClick on compute to update tax base')) - for key in compute_taxes: - if not key in tax_key: - raise osv.except_osv(_('Warning !'), _('Taxes missing !')) - - # one move line per tax line - iml += ait_obj.move_line_get(cr, uid, inv.id) - - if inv.type in ('in_invoice', 'in_refund'): - ref = inv.reference - else: - ref = self._convert_ref(cr, uid, inv.number) - - diff_currency_p = inv.currency_id.id <> company_currency - # create one move line for the total and possibly adjust the other lines amount - total = 0 - total_currency = 0 - for i in iml: - if inv.currency_id.id != company_currency: - i['currency_id'] = inv.currency_id.id - i['amount_currency'] = i['price'] - i['price'] = cur_obj.compute(cr, uid, inv.currency_id.id, - company_currency, i['price'], - context={'date': inv.date_invoice}) - else: - i['amount_currency'] = False - i['currency_id'] = False - i['ref'] = ref - if inv.type in ('out_invoice','in_refund'): - total += i['price'] - total_currency += i['amount_currency'] or i['price'] - i['price'] = - i['price'] - else: - total -= i['price'] - total_currency -= i['amount_currency'] or i['price'] - acc_id = inv.account_id.id - - name = inv['name'] or '/' - totlines = False - if inv.payment_term: - totlines = self.pool.get('account.payment.term').compute(cr, - uid, inv.payment_term.id, total, inv.date_invoice or False) - if totlines: - res_amount_currency = total_currency - i = 0 - for t in totlines: - if inv.currency_id.id != company_currency: - amount_currency = cur_obj.compute(cr, uid, - company_currency, inv.currency_id.id, t[1]) - else: - amount_currency = False - - # last line add the diff - res_amount_currency -= amount_currency or 0 - i += 1 - if i == len(totlines): - amount_currency += res_amount_currency - - iml.append({ - 'type': 'dest', - 'name': name, - 'price': t[1], - 'account_id': acc_id, - 'date_maturity': t[0], - 'amount_currency': diff_currency_p \ - and amount_currency or False, - 'currency_id': diff_currency_p \ - and inv.currency_id.id or False, - 'ref': ref, - }) - else: - iml.append({ - 'type': 'dest', - 'name': name, - 'price': total, - 'account_id': acc_id, - 'date_maturity' : inv.date_due or False, - 'amount_currency': diff_currency_p \ - and total_currency or False, - 'currency_id': diff_currency_p \ - and inv.currency_id.id or False, - 'ref': ref - }) - - date = inv.date_invoice - part = inv.partner_id.id - line = map(lambda x:(0,0,self.line_get_convert(cr, uid, x, part, date, context={})) ,iml) - - journal_id = inv.journal_id.id #self._get_journal(cr, uid, {'type': inv['type']}) - journal = self.pool.get('account.journal').browse(cr, uid, journal_id) - if journal.sequence_id: - name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) - if journal.centralisation: - raise osv.except_osv(_('UserError'), - _('Can not create invoice move on centralized journal')) - - move = {'name': name, 'line_id': line, 'journal_id': journal_id} - if inv.period_id: - move['period_id'] = inv.period_id.id - for i in line: - i[2]['period_id'] = inv.period_id.id - - move_id = self.pool.get('account.move').create(cr, uid, move) - # make the invoice point to that move - self.write(cr, uid, [inv.id], {'move_id': move_id}) - self.pool.get('account.move').post(cr, uid, [move_id]) - self._log_event(cr, uid, ids) - return True - - def line_get_convert(self, cr, uid, x, part, date, context={}): - return { - 'date':date, - 'date_maturity': x.get('date_maturity', False), - 'partner_id':part, - 'name':x['name'][:64], - 'debit':x['price']>0 and x['price'], - 'credit':x['price']<0 and -x['price'], - 'account_id':x['account_id'], - 'analytic_lines':x.get('analytic_lines', []), - 'amount_currency':x['price']>0 and abs(x.get('amount_currency', False)) or -abs(x.get('amount_currency', False)), - 'currency_id':x.get('currency_id', False), - 'tax_code_id': x.get('tax_code_id', False), - 'tax_amount': x.get('tax_amount', False), - 'ref':x.get('ref',False) - } - - def action_number(self, cr, uid, ids, *args): - cr.execute('SELECT id, type, number, move_id, reference ' \ - 'FROM account_invoice ' \ - 'WHERE id IN ('+','.join(map(str,ids))+')') - for (id, invtype, number, move_id, reference) in cr.fetchall(): - if not number: - number = self.pool.get('ir.sequence').get(cr, uid, - 'account.invoice.' + invtype) - if invtype in ('in_invoice', 'in_refund'): - ref = reference - else: - ref = self._convert_ref(cr, uid, number) - cr.execute('UPDATE account_invoice SET number=%s ' \ - 'WHERE id=%d', (number, id)) - cr.execute('UPDATE account_move_line SET ref=%s ' \ - 'WHERE move_id=%d AND (ref is null OR ref = \'\')', - (ref, move_id)) - cr.execute('UPDATE account_analytic_line SET ref=%s ' \ - 'FROM account_move_line ' \ - 'WHERE account_move_line.move_id = %d ' \ - 'AND account_analytic_line.move_id = account_move_line.id', - (ref, move_id)) - return True - - def action_cancel(self, cr, uid, ids, *args): - account_move_obj = self.pool.get('account.move') - invoices = self.read(cr, uid, ids, ['move_id']) - for i in invoices: - if i['move_id']: - account_move_obj.button_cancel(cr, uid, [i['move_id'][0]]) - # delete the move this invoice was pointing to - # Note that the corresponding move_lines and move_reconciles - # will be automatically deleted too - account_move_obj.unlink(cr, uid, [i['move_id'][0]]) - self.write(cr, uid, ids, {'state':'cancel', 'move_id':False}) - self._log_event(cr, uid, ids,-1.0, 'Cancel Invoice') - return True - - ################### - - def list_distinct_taxes(self, cr, uid, ids): - invoices = self.browse(cr, uid, ids) - taxes = {} - for inv in invoices: - for tax in inv.tax_line: - if not tax['name'] in taxes: - taxes[tax['name']] = {'name': tax['name']} - return taxes.values() - - def _log_event(self, cr, uid, ids, factor=1.0, name='Open Invoice'): - invs = self.read(cr, uid, ids, ['type','partner_id','amount_untaxed']) - for inv in invs: - part=inv['partner_id'] and inv['partner_id'][0] - pc = pr = 0.0 - cr.execute('select sum(quantity*price_unit) from account_invoice_line where invoice_id=%d', (inv['id'],)) - total = inv['amount_untaxed'] - if inv['type'] in ('in_invoice','in_refund'): - partnertype='supplier' - eventtype = 'purchase' - pc = total*factor - else: - partnertype = 'customer' - eventtype = 'sale' - pr = total*factor - if self.pool.get('res.partner.event.type').check(cr, uid, 'invoice_open'): - self.pool.get('res.partner.event').create(cr, uid, {'name':'Invoice: '+name, 'som':False, 'description':name+' '+str(inv['id']), 'document':name, 'partner_id':part, 'date':time.strftime('%Y-%m-%d %H:%M:%S'), 'canal_id':False, 'user_id':uid, 'partner_type':partnertype, 'probability':1.0, 'planned_revenue':pr, 'planned_cost':pc, 'type':eventtype}) - return len(invs) - - def name_get(self, cr, uid, ids, context={}): - if not len(ids): - return [] - types = { - 'out_invoice': 'CI: ', - 'in_invoice': 'SI: ', - 'out_refund': 'OR: ', - 'in_refund': 'SR: ', - } - return [(r['id'], types[r['type']]+(r['number'] or '')+' '+(r['name'] or '')) for r in self.read(cr, uid, ids, ['type', 'number', 'name'], context, load='_classic_write')] - - def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): - if not args: - args=[] - if not context: - context={} - ids = [] - if name: - ids = self.search(cr, user, [('number','=',name)]+ args, limit=limit, context=context) - if not ids: - ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit, context=context) - return self.name_get(cr, user, ids, context) - - def _refund_cleanup_lines(self, lines): - for line in lines: - del line['id'] - del line['invoice_id'] - if 'account_id' in line: - line['account_id'] = line.get('account_id', False) and line['account_id'][0] - if 'product_id' in line: - line['product_id'] = line.get('product_id', False) and line['product_id'][0] - if 'uos_id' in line: - line['uos_id'] = line.get('uos_id', False) and line['uos_id'][0] - if 'invoice_line_tax_id' in line: - line['invoice_line_tax_id'] = [(6,0, line.get('invoice_line_tax_id', [])) ] - if 'account_analytic_id' in line: - line['account_analytic_id'] = line.get('account_analytic_id', False) and line['account_analytic_id'][0] - return map(lambda x: (0,0,x), lines) - - def refund(self, cr, uid, ids): - invoices = self.read(cr, uid, ids, ['name', 'type', 'number', 'reference', 'comment', 'date_due', 'partner_id', 'address_contact_id', 'address_invoice_id', 'partner_contact', 'partner_insite', 'partner_ref', 'payment_term', 'account_id', 'currency_id', 'invoice_line', 'tax_line', 'journal_id']) - - new_ids = [] - for invoice in invoices: - del invoice['id'] - - type_dict = { - 'out_invoice': 'out_refund', # Customer Invoice - 'in_invoice': 'in_refund', # Supplier Invoice - 'out_refund': 'out_invoice', # Customer Refund - 'in_refund': 'in_invoice', # Supplier Refund - } - - - invoice_lines = self.pool.get('account.invoice.line').read(cr, uid, invoice['invoice_line']) - invoice_lines = self._refund_cleanup_lines(invoice_lines) - - tax_lines = self.pool.get('account.invoice.tax').read(cr, uid, invoice['tax_line']) - tax_lines = filter(lambda l: l['manual'], tax_lines) - tax_lines = self._refund_cleanup_lines(tax_lines) - - invoice.update({ - 'type': type_dict[invoice['type']], - 'date_invoice': time.strftime('%Y-%m-%d'), - 'state': 'draft', - 'number': False, - 'invoice_line': invoice_lines, - 'tax_line': tax_lines - }) - - # take the id part of the tuple returned for many2one fields - for field in ('address_contact_id', 'address_invoice_id', 'partner_id', - 'account_id', 'currency_id', 'payment_term', 'journal_id'): - invoice[field] = invoice[field] and invoice[field][0] - - # create the new invoice - new_ids.append(self.create(cr, uid, invoice)) - return new_ids - - def pay_and_reconcile(self, cr, uid, ids, pay_amount, pay_account_id, period_id, pay_journal_id, writeoff_acc_id, writeoff_period_id, writeoff_journal_id, context={}, name=''): - #TODO check if we can use different period for payment and the writeoff line - assert len(ids)==1, "Can only pay one invoice at a time" - invoice = self.browse(cr, uid, ids[0]) - src_account_id = invoice.account_id.id - journal = self.pool.get('account.journal').browse(cr, uid, pay_journal_id) - if not name: - if journal.sequence_id: - name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) - else: - raise osv.except_osv(_('No piece number !'), _('Can not create an automatic sequence for this piece !\n\nPut a sequence in the journal definition for automatic numbering or create a sequence manually for this piece.')) - types = {'out_invoice': -1, 'in_invoice': 1, 'out_refund': 1, 'in_refund': -1} - direction = types[invoice.type] - l1 = { - 'name': name, - 'debit': direction * pay_amount>0 and direction * pay_amount, - 'credit': direction * pay_amount<0 and - direction * pay_amount, - 'account_id': src_account_id, - 'partner_id': invoice.partner_id.id, - 'date': time.strftime('%Y-%m-%d'), - } - l2 = { - 'name':name, - 'debit': direction * pay_amount<0 and - direction * pay_amount, - 'credit': direction * pay_amount>0 and direction * pay_amount, - 'account_id': pay_account_id, - 'partner_id': invoice.partner_id.id, - 'date': time.strftime('%Y-%m-%d'), - } - - lines = [(0, 0, l1), (0, 0, l2)] - move = {'name': name, 'line_id': lines, 'journal_id': pay_journal_id, 'period_id': period_id} - move_id = self.pool.get('account.move').create(cr, uid, move) - - line_ids = [] - total = 0.0 - line = self.pool.get('account.move.line') - cr.execute('select id from account_move_line where move_id in ('+str(move_id)+','+str(invoice.move_id.id)+')') - lines = line.browse(cr, uid, map(lambda x: x[0], cr.fetchall()) ) - for l in lines: - if l.account_id.id==src_account_id: - line_ids.append(l.id) - total += (l.debit or 0.0) - (l.credit or 0.0) - if (not total) or writeoff_acc_id: - self.pool.get('account.move.line').reconcile(cr, uid, line_ids, 'manual', writeoff_acc_id, writeoff_period_id, writeoff_journal_id, context) - else: - self.pool.get('account.move.line').reconcile_partial(cr, uid, line_ids, 'manual', context) - return True + def _amount_untaxed(self, cr, uid, ids, name, args, context={}): + id_set=",".join(map(str,ids)) + cr.execute("SELECT s.id,COALESCE(SUM(l.price_subtotal),0)::decimal(16,2) AS amount FROM account_invoice s LEFT OUTER JOIN account_invoice_line l ON (s.id=l.invoice_id) WHERE s.id IN ("+id_set+") GROUP BY s.id ") + res=dict(cr.fetchall()) + return res + + def _amount_tax(self, cr, uid, ids, name, args, context={}): + id_set=",".join(map(str,ids)) + cr.execute("SELECT s.id,COALESCE(SUM(l.amount),0)::decimal(16,2) AS amount FROM account_invoice s LEFT OUTER JOIN account_invoice_tax l ON (s.id=l.invoice_id) WHERE s.id IN ("+id_set+") GROUP BY s.id ") + res=dict(cr.fetchall()) + return res + + def _amount_total(self, cr, uid, ids, name, args, context={}): + untax = self._amount_untaxed(cr, uid, ids, name, args, context) + tax = self._amount_tax(cr, uid, ids, name, args, context) + res = {} + for id in ids: + res[id] = untax.get(id,0.0) + tax.get(id,0.0) + return res + + def _get_journal(self, cr, uid, context): + type_inv = context.get('type', 'out_invoice') + type2journal = {'out_invoice': 'sale', 'in_invoice': 'purchase', 'out_refund': 'sale', 'in_refund': 'purchase'} + journal_obj = self.pool.get('account.journal') + res = journal_obj.search(cr, uid, [('type', '=', type2journal.get(type_inv, 'sale'))], limit=1) + if res: + return res[0] + else: + return False + + def _get_currency(self, cr, uid, context): + user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, [uid])[0] + if user.company_id: + return user.company_id.currency_id.id + else: + return pooler.get_pool(cr.dbname).get('res.currency').search(cr, uid, [('rate','=',1.0)])[0] + + def _get_journal_analytic(self, cr, uid, type_inv, context={}): + type2journal = {'out_invoice': 'sale', 'in_invoice': 'purchase', 'out_refund': 'sale', 'in_refund': 'purchase'} + tt = type2journal.get(type_inv, 'sale') + cr.execute("select id from account_analytic_journal where type=%s limit 1", (tt,)) + result = cr.fetchone() + if not result: + raise osv.except_osv(_('No Analytic Journal !'),("You have to define an analytic journal of type '%s' !") % (tt,)) + return result[0] + + def _get_type(self, cr, uid, context={}): + type = context.get('type', 'out_invoice') + return type + + def _reconciled(self, cr, uid, ids, name, args, context): + res = {} + for id in ids: + res[id] = self.test_paid(cr, uid, [id]) + return res + + def _get_reference_type(self, cursor, user, context=None): + return [('none', 'Free Reference')] + + _name = "account.invoice" + _description = 'Invoice' + _order = "number" + _columns = { + 'name': fields.char('Description', size=64, select=True,readonly=True, states={'draft':[('readonly',False)]}), + 'origin': fields.char('Origin', size=64), + 'type': fields.selection([ + ('out_invoice','Customer Invoice'), + ('in_invoice','Supplier Invoice'), + ('out_refund','Customer Refund'), + ('in_refund','Supplier Refund'), + ],'Type', readonly=True, select=True), + + 'number': fields.char('Invoice Number', size=32, readonly=True), + 'reference': fields.char('Invoice Reference', size=64), + 'reference_type': fields.selection(_get_reference_type, 'Reference Type', + required=True), + 'comment': fields.text('Additionnal Information'), + + 'state': fields.selection([ + ('draft','Draft'), + ('proforma','Pro-forma'), + ('open','Open'), + ('paid','Paid'), + ('cancel','Canceled') + ],'State', select=True, readonly=True), + + 'date_invoice': fields.date('Date Invoiced', required=True, states={'open':[('readonly',True)],'close':[('readonly',True)]}), + 'date_due': fields.date('Due Date', states={'open':[('readonly',True)],'close':[('readonly',True)]}), + + 'partner_id': fields.many2one('res.partner', 'Partner', change_default=True, readonly=True, required=True, states={'draft':[('readonly',False)]}), + 'address_contact_id': fields.many2one('res.partner.address', 'Contact Address', readonly=True, states={'draft':[('readonly',False)]}), + 'address_invoice_id': fields.many2one('res.partner.address', 'Invoice Address', readonly=True, required=True, states={'draft':[('readonly',False)]}), + + 'payment_term': fields.many2one('account.payment.term', 'Payment Term',readonly=True, states={'draft':[('readonly',False)]} ), + + 'period_id': fields.many2one('account.period', 'Force Period', help="Keep empty to use the period of the validation date."), + + 'account_id': fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}), + 'invoice_line': fields.one2many('account.invoice.line', 'invoice_id', 'Invoice Lines', readonly=True, states={'draft':[('readonly',False)]}), + 'tax_line': fields.one2many('account.invoice.tax', 'invoice_id', 'Tax Lines', readonly=True, states={'draft':[('readonly',False)]}), + + 'move_id': fields.many2one('account.move', 'Invoice Movement', readonly=True), + 'amount_untaxed': fields.function(_amount_untaxed, method=True, digits=(16,2),string='Untaxed', store=True), + 'amount_tax': fields.function(_amount_tax, method=True, digits=(16,2), string='Tax', store=True), + 'amount_total': fields.function(_amount_total, method=True, digits=(16,2), string='Total', store=True), + 'currency_id': fields.many2one('res.currency', 'Currency', required=True, readonly=True, states={'draft':[('readonly',False)]}), + 'journal_id': fields.many2one('account.journal', 'Journal', required=True,readonly=True, states={'draft':[('readonly',False)]}), + 'company_id': fields.many2one('res.company', 'Company', required=True), + 'check_total': fields.float('Total', digits=(16,2), states={'open':[('readonly',True)],'close':[('readonly',True)]}), + 'reconciled': fields.function(_reconciled, method=True, string='Reconciled', type='boolean'), + 'partner_bank': fields.many2one('res.partner.bank', 'Bank Account', + help='The bank account to pay or to be paid'), + } + _defaults = { + 'type': _get_type, + 'date_invoice': lambda *a: time.strftime('%Y-%m-%d'), + 'state': lambda *a: 'draft', + 'journal_id': _get_journal, + 'currency_id': _get_currency, + 'company_id': lambda self, cr, uid, context: \ + self.pool.get('res.users').browse(cr, uid, uid, + context=context).company_id.id, + 'reference_type': lambda *a: 'none', + } + + def unlink(self, cr, uid, ids): + invoices = self.read(cr, uid, ids, ['state']) + unlink_ids = [] + for t in invoices: + if t['state'] in ('draft', 'cancel'): + unlink_ids.append(t['id']) + else: + raise osv.except_osv(_('Invalid action !'), _('Cannot delete invoice(s) which are already opened or paid !')) + osv.osv.unlink(self, cr, uid, unlink_ids) + return True + +# def get_invoice_address(self, cr, uid, ids): +# res = self.pool.get('res.partner').address_get(cr, uid, [part], ['invoice']) +# return [{}] + + def onchange_partner_id(self, cr, uid, ids, type, partner_id, + date_invoice=False, payment_term=False, partner_bank_id=False): + invoice_addr_id = False + contact_addr_id = False + partner_payment_term = False + acc_id = False + bank_id = False + + opt = [('uid', str(uid))] + if partner_id: + + opt.insert(0, ('id', partner_id)) + res = self.pool.get('res.partner').address_get(cr, uid, [partner_id], ['contact', 'invoice']) + contact_addr_id = res['contact'] + invoice_addr_id = res['invoice'] + p = self.pool.get('res.partner').browse(cr, uid, partner_id) + if type in ('out_invoice', 'out_refund'): + acc_id = p.property_account_receivable.id + else: + acc_id = p.property_account_payable.id + + partner_payment_term = p.property_payment_term and p.property_payment_term.id or False + if p.bank_ids: + bank_id = p.bank_ids[0].id + + result = {'value': { + 'address_contact_id': contact_addr_id, + 'address_invoice_id': invoice_addr_id, + 'account_id': acc_id, + 'payment_term': partner_payment_term, + } + } + + if type in ('in_invoice', 'in_refund'): + result['value']['partner_bank'] = bank_id + + if payment_term != partner_payment_term: + if partner_payment_term: + to_update = self.onchange_payment_term_date_invoice( + cr,uid,ids,partner_payment_term,date_invoice) + result['value'].update(to_update['value']) + else: + result['value']['date_due'] = False + + if partner_bank_id != bank_id: + to_update = self.onchange_partner_bank(cr, uid, ids, bank_id) + result['value'].update(to_update['value']) + return result + + def onchange_currency_id(self, cr, uid, ids, curr_id): + return {} + + def onchange_payment_term_date_invoice(self, cr, uid, ids, payment_term_id, date_invoice): + if not payment_term_id: + return {} + res={} + pt_obj= self.pool.get('account.payment.term') + + if not date_invoice : + date_invoice = self._defaults["date_invoice"](cr,uid,{}) + + pterm_list= pt_obj.compute(cr, uid, payment_term_id, value=1, date_ref=date_invoice) + + if pterm_list: + pterm_list = [line[0] for line in pterm_list] + pterm_list.sort() + res= {'value':{'date_due': pterm_list[-1]}} + + return res + + def onchange_invoice_line(self, cr, uid, ids, lines): + return {} + + def onchange_partner_bank(self, cursor, user, ids, partner_bank_id): + return {'value': {}} + + # go from canceled state to draft state + def action_cancel_draft(self, cr, uid, ids, *args): + self.write(cr, uid, ids, {'state':'draft'}) + wf_service = netsvc.LocalService("workflow") + for inv_id in ids: + wf_service.trg_create(uid, 'account.invoice', inv_id, cr) + return True + + # Workflow stuff + ################# + + # return the ids of the move lines which has the same account than the invoice + # whose id is in ids + def move_line_id_payment_get(self, cr, uid, ids, *args): + ml = self.pool.get('account.move.line') + res = [] + for inv in self.read(cr, uid, ids, ['move_id','account_id']): + if inv['move_id']: + move_line_ids = ml.search(cr, uid, [('move_id', '=', inv['move_id'][0])]) + for line in ml.read(cr, uid, move_line_ids, ['account_id']): + if line['account_id']==inv['account_id']: + res.append(line['id']) + return res + + def copy(self, cr, uid, id, default=None, context=None): + if default is None: + default = {} + default = default.copy() + default.update({'state':'draft', 'number':False, 'move_id':False,}) + if 'date_invoice' not in default: + default['date_invoice'] = time.strftime('%Y-%m-%d') + if 'date_due' not in default: + default['date_due'] = False + return super(account_invoice, self).copy(cr, uid, id, default, context) + + def test_paid(self, cr, uid, ids, *args): + res = self.move_line_id_payment_get(cr, uid, ids) + if not res: + return False + ok = True + for id in res: + cr.execute('select reconcile_id from account_move_line where id=%d', (id,)) + ok = ok and bool(cr.fetchone()[0]) + return ok + + def button_reset_taxes(self, cr, uid, ids, context={}): + ait_obj = self.pool.get('account.invoice.tax') + for id in ids: + cr.execute("DELETE FROM account_invoice_tax WHERE invoice_id=%d", (id,)) + for taxe in ait_obj.compute(cr, uid, id).values(): + ait_obj.create(cr, uid, taxe) + return True + + def button_compute(self, cr, uid, ids, context={}, set_total=False): + ait_obj = self.pool.get('account.invoice.tax') + cur_obj = self.pool.get('res.currency') + for inv in self.browse(cr, uid, ids): + company_currency = inv.company_id.currency_id.id + compute_taxes = ait_obj.compute(cr, uid, inv.id) + if not inv.tax_line: + for tax in compute_taxes.values(): + ait_obj.create(cr, uid, tax) + else: + tax_key = [] + for tax in inv.tax_line: + if tax.manual: + continue + key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id) + tax_key.append(key) + if not key in compute_taxes: + ait_obj.unlink(cr, uid, [tax.id]) + continue + compute_taxes[key]['base'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, compute_taxes[key]['base'], context={'date': inv.date_invoice}) + if abs(compute_taxes[key]['base'] - tax.base) > inv.company_id.currency_id.rounding: + ait_obj.write(cr, uid, [tax.id], compute_taxes[key]) + for key in compute_taxes: + if not key in tax_key: + ait_obj.create(cr, uid, compute_taxes[key]) + if set_total: + self.pool.get('account.invoice').write(cr, uid, [inv.id], {'check_total': inv.amount_total}) + return True + + def _convert_ref(self, cr, uid, ref): + return (ref or '').replace('/','') + + def _get_analityc_lines(self, cr, uid, id): + inv = self.browse(cr, uid, [id])[0] + cur_obj = self.pool.get('res.currency') + + company_currency = inv.company_id.currency_id.id + if inv.type in ('out_invoice', 'in_refund'): + sign = 1 + else: + sign = -1 + + iml = self.pool.get('account.invoice.line').move_line_get(cr, uid, inv.id) + for il in iml: + if il['account_analytic_id']: + if inv.type in ('in_invoice', 'in_refund'): + ref = inv.reference + else: + ref = self._convert_ref(cr, uid, inv.number) + il['analytic_lines'] = [(0,0, { + 'name': il['name'], + 'date': inv['date_invoice'], + 'account_id': il['account_analytic_id'], + 'unit_amount': il['quantity'], + 'amount': cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, il['price'], context={'date': inv.date_invoice}) * sign, + 'product_id': il['product_id'], + 'product_uom_id': il['uos_id'], + 'general_account_id': il['account_id'], + 'journal_id': self._get_journal_analytic(cr, uid, inv.type), + 'ref': ref, + })] + return iml + + def action_move_create(self, cr, uid, ids, *args): + ait_obj = self.pool.get('account.invoice.tax') + cur_obj = self.pool.get('res.currency') + for inv in self.browse(cr, uid, ids): + if inv.move_id: + continue + if inv.type in ('in_invoice', 'in_refund') and abs(inv.check_total - inv.amount_total) >= (inv.currency_id.rounding/2.0): + raise osv.except_osv(_('Bad total !'), _('Please verify the price of the invoice !\nThe real total does not match the computed total.')) + company_currency = inv.company_id.currency_id.id + # create the analytical lines + line_ids = self.read(cr, uid, [inv.id], ['invoice_line'])[0]['invoice_line'] + ils = self.pool.get('account.invoice.line').read(cr, uid, line_ids) + # one move line per invoice line + iml = self._get_analityc_lines(cr, uid, inv.id) + # check if taxes are all computed + compute_taxes = ait_obj.compute(cr, uid, inv.id) + if not inv.tax_line: + for tax in compute_taxes.values(): + ait_obj.create(cr, uid, tax) + else: + tax_key = [] + for tax in inv.tax_line: + if tax.manual: + continue + key = (tax.tax_code_id.id, tax.base_code_id.id, tax.account_id.id) + tax_key.append(key) + if not key in compute_taxes: + raise osv.except_osv(_('Warning !'), _('Global taxes defined, but not in invoice lines !')) + base = compute_taxes[key]['base'] + if abs(base - tax.base) > inv.company_id.currency_id.rounding: + raise osv.except_osv(_('Warning !'), _('Tax base different !\nClick on compute to update tax base')) + for key in compute_taxes: + if not key in tax_key: + raise osv.except_osv(_('Warning !'), _('Taxes missing !')) + + # one move line per tax line + iml += ait_obj.move_line_get(cr, uid, inv.id) + + if inv.type in ('in_invoice', 'in_refund'): + ref = inv.reference + else: + ref = self._convert_ref(cr, uid, inv.number) + + diff_currency_p = inv.currency_id.id <> company_currency + # create one move line for the total and possibly adjust the other lines amount + total = 0 + total_currency = 0 + for i in iml: + if inv.currency_id.id != company_currency: + i['currency_id'] = inv.currency_id.id + i['amount_currency'] = i['price'] + i['price'] = cur_obj.compute(cr, uid, inv.currency_id.id, + company_currency, i['price'], + context={'date': inv.date_invoice}) + else: + i['amount_currency'] = False + i['currency_id'] = False + i['ref'] = ref + if inv.type in ('out_invoice','in_refund'): + total += i['price'] + total_currency += i['amount_currency'] or i['price'] + i['price'] = - i['price'] + else: + total -= i['price'] + total_currency -= i['amount_currency'] or i['price'] + acc_id = inv.account_id.id + + name = inv['name'] or '/' + totlines = False + if inv.payment_term: + totlines = self.pool.get('account.payment.term').compute(cr, + uid, inv.payment_term.id, total, inv.date_invoice or False) + if totlines: + res_amount_currency = total_currency + i = 0 + for t in totlines: + if inv.currency_id.id != company_currency: + amount_currency = cur_obj.compute(cr, uid, + company_currency, inv.currency_id.id, t[1]) + else: + amount_currency = False + + # last line add the diff + res_amount_currency -= amount_currency or 0 + i += 1 + if i == len(totlines): + amount_currency += res_amount_currency + + iml.append({ + 'type': 'dest', + 'name': name, + 'price': t[1], + 'account_id': acc_id, + 'date_maturity': t[0], + 'amount_currency': diff_currency_p \ + and amount_currency or False, + 'currency_id': diff_currency_p \ + and inv.currency_id.id or False, + 'ref': ref, + }) + else: + iml.append({ + 'type': 'dest', + 'name': name, + 'price': total, + 'account_id': acc_id, + 'date_maturity' : inv.date_due or False, + 'amount_currency': diff_currency_p \ + and total_currency or False, + 'currency_id': diff_currency_p \ + and inv.currency_id.id or False, + 'ref': ref + }) + + date = inv.date_invoice + part = inv.partner_id.id + line = map(lambda x:(0,0,self.line_get_convert(cr, uid, x, part, date, context={})) ,iml) + + journal_id = inv.journal_id.id #self._get_journal(cr, uid, {'type': inv['type']}) + journal = self.pool.get('account.journal').browse(cr, uid, journal_id) + if journal.sequence_id: + name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) + if journal.centralisation: + raise osv.except_osv(_('UserError'), + _('Can not create invoice move on centralized journal')) + + move = {'name': name, 'line_id': line, 'journal_id': journal_id} + if inv.period_id: + move['period_id'] = inv.period_id.id + for i in line: + i[2]['period_id'] = inv.period_id.id + + move_id = self.pool.get('account.move').create(cr, uid, move) + # make the invoice point to that move + self.write(cr, uid, [inv.id], {'move_id': move_id}) + self.pool.get('account.move').post(cr, uid, [move_id]) + self._log_event(cr, uid, ids) + return True + + def line_get_convert(self, cr, uid, x, part, date, context={}): + return { + 'date':date, + 'date_maturity': x.get('date_maturity', False), + 'partner_id':part, + 'name':x['name'][:64], + 'debit':x['price']>0 and x['price'], + 'credit':x['price']<0 and -x['price'], + 'account_id':x['account_id'], + 'analytic_lines':x.get('analytic_lines', []), + 'amount_currency':x['price']>0 and abs(x.get('amount_currency', False)) or -abs(x.get('amount_currency', False)), + 'currency_id':x.get('currency_id', False), + 'tax_code_id': x.get('tax_code_id', False), + 'tax_amount': x.get('tax_amount', False), + 'ref':x.get('ref',False) + } + + def action_number(self, cr, uid, ids, *args): + cr.execute('SELECT id, type, number, move_id, reference ' \ + 'FROM account_invoice ' \ + 'WHERE id IN ('+','.join(map(str,ids))+')') + for (id, invtype, number, move_id, reference) in cr.fetchall(): + if not number: + number = self.pool.get('ir.sequence').get(cr, uid, + 'account.invoice.' + invtype) + if invtype in ('in_invoice', 'in_refund'): + ref = reference + else: + ref = self._convert_ref(cr, uid, number) + cr.execute('UPDATE account_invoice SET number=%s ' \ + 'WHERE id=%d', (number, id)) + cr.execute('UPDATE account_move_line SET ref=%s ' \ + 'WHERE move_id=%d AND (ref is null OR ref = \'\')', + (ref, move_id)) + cr.execute('UPDATE account_analytic_line SET ref=%s ' \ + 'FROM account_move_line ' \ + 'WHERE account_move_line.move_id = %d ' \ + 'AND account_analytic_line.move_id = account_move_line.id', + (ref, move_id)) + return True + + def action_cancel(self, cr, uid, ids, *args): + account_move_obj = self.pool.get('account.move') + invoices = self.read(cr, uid, ids, ['move_id']) + for i in invoices: + if i['move_id']: + account_move_obj.button_cancel(cr, uid, [i['move_id'][0]]) + # delete the move this invoice was pointing to + # Note that the corresponding move_lines and move_reconciles + # will be automatically deleted too + account_move_obj.unlink(cr, uid, [i['move_id'][0]]) + self.write(cr, uid, ids, {'state':'cancel', 'move_id':False}) + self._log_event(cr, uid, ids,-1.0, 'Cancel Invoice') + return True + + ################### + + def list_distinct_taxes(self, cr, uid, ids): + invoices = self.browse(cr, uid, ids) + taxes = {} + for inv in invoices: + for tax in inv.tax_line: + if not tax['name'] in taxes: + taxes[tax['name']] = {'name': tax['name']} + return taxes.values() + + def _log_event(self, cr, uid, ids, factor=1.0, name='Open Invoice'): + invs = self.read(cr, uid, ids, ['type','partner_id','amount_untaxed']) + for inv in invs: + part=inv['partner_id'] and inv['partner_id'][0] + pc = pr = 0.0 + cr.execute('select sum(quantity*price_unit) from account_invoice_line where invoice_id=%d', (inv['id'],)) + total = inv['amount_untaxed'] + if inv['type'] in ('in_invoice','in_refund'): + partnertype='supplier' + eventtype = 'purchase' + pc = total*factor + else: + partnertype = 'customer' + eventtype = 'sale' + pr = total*factor + if self.pool.get('res.partner.event.type').check(cr, uid, 'invoice_open'): + self.pool.get('res.partner.event').create(cr, uid, {'name':'Invoice: '+name, 'som':False, 'description':name+' '+str(inv['id']), 'document':name, 'partner_id':part, 'date':time.strftime('%Y-%m-%d %H:%M:%S'), 'canal_id':False, 'user_id':uid, 'partner_type':partnertype, 'probability':1.0, 'planned_revenue':pr, 'planned_cost':pc, 'type':eventtype}) + return len(invs) + + def name_get(self, cr, uid, ids, context={}): + if not len(ids): + return [] + types = { + 'out_invoice': 'CI: ', + 'in_invoice': 'SI: ', + 'out_refund': 'OR: ', + 'in_refund': 'SR: ', + } + return [(r['id'], types[r['type']]+(r['number'] or '')+' '+(r['name'] or '')) for r in self.read(cr, uid, ids, ['type', 'number', 'name'], context, load='_classic_write')] + + def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80): + if not args: + args=[] + if not context: + context={} + ids = [] + if name: + ids = self.search(cr, user, [('number','=',name)]+ args, limit=limit, context=context) + if not ids: + ids = self.search(cr, user, [('name',operator,name)]+ args, limit=limit, context=context) + return self.name_get(cr, user, ids, context) + + def _refund_cleanup_lines(self, lines): + for line in lines: + del line['id'] + del line['invoice_id'] + if 'account_id' in line: + line['account_id'] = line.get('account_id', False) and line['account_id'][0] + if 'product_id' in line: + line['product_id'] = line.get('product_id', False) and line['product_id'][0] + if 'uos_id' in line: + line['uos_id'] = line.get('uos_id', False) and line['uos_id'][0] + if 'invoice_line_tax_id' in line: + line['invoice_line_tax_id'] = [(6,0, line.get('invoice_line_tax_id', [])) ] + if 'account_analytic_id' in line: + line['account_analytic_id'] = line.get('account_analytic_id', False) and line['account_analytic_id'][0] + return map(lambda x: (0,0,x), lines) + + def refund(self, cr, uid, ids): + invoices = self.read(cr, uid, ids, ['name', 'type', 'number', 'reference', 'comment', 'date_due', 'partner_id', 'address_contact_id', 'address_invoice_id', 'partner_contact', 'partner_insite', 'partner_ref', 'payment_term', 'account_id', 'currency_id', 'invoice_line', 'tax_line', 'journal_id']) + + new_ids = [] + for invoice in invoices: + del invoice['id'] + + type_dict = { + 'out_invoice': 'out_refund', # Customer Invoice + 'in_invoice': 'in_refund', # Supplier Invoice + 'out_refund': 'out_invoice', # Customer Refund + 'in_refund': 'in_invoice', # Supplier Refund + } + + + invoice_lines = self.pool.get('account.invoice.line').read(cr, uid, invoice['invoice_line']) + invoice_lines = self._refund_cleanup_lines(invoice_lines) + + tax_lines = self.pool.get('account.invoice.tax').read(cr, uid, invoice['tax_line']) + tax_lines = filter(lambda l: l['manual'], tax_lines) + tax_lines = self._refund_cleanup_lines(tax_lines) + + invoice.update({ + 'type': type_dict[invoice['type']], + 'date_invoice': time.strftime('%Y-%m-%d'), + 'state': 'draft', + 'number': False, + 'invoice_line': invoice_lines, + 'tax_line': tax_lines + }) + + # take the id part of the tuple returned for many2one fields + for field in ('address_contact_id', 'address_invoice_id', 'partner_id', + 'account_id', 'currency_id', 'payment_term', 'journal_id'): + invoice[field] = invoice[field] and invoice[field][0] + + # create the new invoice + new_ids.append(self.create(cr, uid, invoice)) + return new_ids + + def pay_and_reconcile(self, cr, uid, ids, pay_amount, pay_account_id, period_id, pay_journal_id, writeoff_acc_id, writeoff_period_id, writeoff_journal_id, context={}, name=''): + #TODO check if we can use different period for payment and the writeoff line + assert len(ids)==1, "Can only pay one invoice at a time" + invoice = self.browse(cr, uid, ids[0]) + src_account_id = invoice.account_id.id + journal = self.pool.get('account.journal').browse(cr, uid, pay_journal_id) + if not name: + if journal.sequence_id: + name = self.pool.get('ir.sequence').get_id(cr, uid, journal.sequence_id.id) + else: + raise osv.except_osv(_('No piece number !'), _('Can not create an automatic sequence for this piece !\n\nPut a sequence in the journal definition for automatic numbering or create a sequence manually for this piece.')) + types = {'out_invoice': -1, 'in_invoice': 1, 'out_refund': 1, 'in_refund': -1} + direction = types[invoice.type] + l1 = { + 'name': name, + 'debit': direction * pay_amount>0 and direction * pay_amount, + 'credit': direction * pay_amount<0 and - direction * pay_amount, + 'account_id': src_account_id, + 'partner_id': invoice.partner_id.id, + 'date': time.strftime('%Y-%m-%d'), + } + l2 = { + 'name':name, + 'debit': direction * pay_amount<0 and - direction * pay_amount, + 'credit': direction * pay_amount>0 and direction * pay_amount, + 'account_id': pay_account_id, + 'partner_id': invoice.partner_id.id, + 'date': time.strftime('%Y-%m-%d'), + } + + lines = [(0, 0, l1), (0, 0, l2)] + move = {'name': name, 'line_id': lines, 'journal_id': pay_journal_id, 'period_id': period_id} + move_id = self.pool.get('account.move').create(cr, uid, move) + + line_ids = [] + total = 0.0 + line = self.pool.get('account.move.line') + cr.execute('select id from account_move_line where move_id in ('+str(move_id)+','+str(invoice.move_id.id)+')') + lines = line.browse(cr, uid, map(lambda x: x[0], cr.fetchall()) ) + for l in lines: + if l.account_id.id==src_account_id: + line_ids.append(l.id) + total += (l.debit or 0.0) - (l.credit or 0.0) + if (not total) or writeoff_acc_id: + self.pool.get('account.move.line').reconcile(cr, uid, line_ids, 'manual', writeoff_acc_id, writeoff_period_id, writeoff_journal_id, context) + else: + self.pool.get('account.move.line').reconcile_partial(cr, uid, line_ids, 'manual', context) + return True account_invoice() class account_invoice_line(osv.osv): - def _amount_line(self, cr, uid, ids, prop, unknow_none,unknow_dict): - res = {} - for line in self.browse(cr, uid, ids): - res[line.id] = round(line.price_unit * line.quantity * (1-(line.discount or 0.0)/100.0),2) - return res + def _amount_line(self, cr, uid, ids, prop, unknow_none,unknow_dict): + res = {} + for line in self.browse(cr, uid, ids): + res[line.id] = round(line.price_unit * line.quantity * (1-(line.discount or 0.0)/100.0),2) + return res - def _price_unit_default(self, cr, uid, context={}): - if 'check_total' in context: - t = context['check_total'] - for l in context.get('invoice_line', {}): - if len(l) >= 3 and l[2]: - tax_obj = self.pool.get('account.tax') - p = l[2].get('price_unit', 0) * (1-l[2].get('discount', 0)/100.0) - t = t - (p * l[2].get('quantity')) - taxes = l[2].get('invoice_line_tax_id') - if len(taxes[0]) >= 3 and taxes[0][2]: - taxes=tax_obj.browse(cr, uid, taxes[0][2]) - for tax in tax_obj.compute(cr, uid, taxes, p,l[2].get('quantity'), context.get('address_invoice_id', False), l[2].get('product_id', False), context.get('partner_id', False)): - t = t - tax['amount'] - return t - return 0 + def _price_unit_default(self, cr, uid, context={}): + if 'check_total' in context: + t = context['check_total'] + for l in context.get('invoice_line', {}): + if len(l) >= 3 and l[2]: + tax_obj = self.pool.get('account.tax') + p = l[2].get('price_unit', 0) * (1-l[2].get('discount', 0)/100.0) + t = t - (p * l[2].get('quantity')) + taxes = l[2].get('invoice_line_tax_id') + if len(taxes[0]) >= 3 and taxes[0][2]: + taxes=tax_obj.browse(cr, uid, taxes[0][2]) + for tax in tax_obj.compute(cr, uid, taxes, p,l[2].get('quantity'), context.get('address_invoice_id', False), l[2].get('product_id', False), context.get('partner_id', False)): + t = t - tax['amount'] + return t + return 0 - _name = "account.invoice.line" - _description = "Invoice line" - _columns = { - 'name': fields.char('Description', size=256, required=True), - 'invoice_id': fields.many2one('account.invoice', 'Invoice Ref', ondelete='cascade', select=True), - 'uos_id': fields.many2one('product.uom', 'Unit', ondelete='set null'), - 'product_id': fields.many2one('product.product', 'Product', ondelete='set null'), - 'account_id': fields.many2one('account.account', 'Account', required=True, domain=[('type','<>','view'), ('type', '<>', 'closed')]), - 'price_unit': fields.float('Unit Price', required=True, digits=(16, int(config['price_accuracy']))), - 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal',store=True), - 'quantity': fields.float('Quantity', required=True), - 'discount': fields.float('Discount (%)', digits=(16,2)), - 'invoice_line_tax_id': fields.many2many('account.tax', 'account_invoice_line_tax', 'invoice_line_id', 'tax_id', 'Taxes', domain=[('parent_id','=',False)]), - 'note': fields.text('Notes'), - 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'), - } - _defaults = { - 'quantity': lambda *a: 1, - 'discount': lambda *a: 0.0, - 'price_unit': _price_unit_default, - } + _name = "account.invoice.line" + _description = "Invoice line" + _columns = { + 'name': fields.char('Description', size=256, required=True), + 'invoice_id': fields.many2one('account.invoice', 'Invoice Ref', ondelete='cascade', select=True), + 'uos_id': fields.many2one('product.uom', 'Unit', ondelete='set null'), + 'product_id': fields.many2one('product.product', 'Product', ondelete='set null'), + 'account_id': fields.many2one('account.account', 'Account', required=True, domain=[('type','<>','view'), ('type', '<>', 'closed')]), + 'price_unit': fields.float('Unit Price', required=True, digits=(16, int(config['price_accuracy']))), + 'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal',store=True), + 'quantity': fields.float('Quantity', required=True), + 'discount': fields.float('Discount (%)', digits=(16,2)), + 'invoice_line_tax_id': fields.many2many('account.tax', 'account_invoice_line_tax', 'invoice_line_id', 'tax_id', 'Taxes', domain=[('parent_id','=',False)]), + 'note': fields.text('Notes'), + 'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'), + } + _defaults = { + 'quantity': lambda *a: 1, + 'discount': lambda *a: 0.0, + 'price_unit': _price_unit_default, + } - def product_id_change_unit_price_inv(self, cr, uid, tax_id, price_unit, qty, address_invoice_id, product, partner_id, context={}): - tax_obj = self.pool.get('account.tax') - if price_unit: - taxes = tax_obj.browse(cr, uid, tax_id) - for tax in tax_obj.compute_inv(cr, uid, taxes, price_unit, qty, address_invoice_id, product, partner_id): - price_unit = price_unit - tax['amount'] - return {'price_unit': price_unit,'invoice_line_tax_id': tax_id} + def product_id_change_unit_price_inv(self, cr, uid, tax_id, price_unit, qty, address_invoice_id, product, partner_id, context={}): + tax_obj = self.pool.get('account.tax') + if price_unit: + taxes = tax_obj.browse(cr, uid, tax_id) + for tax in tax_obj.compute_inv(cr, uid, taxes, price_unit, qty, address_invoice_id, product, partner_id): + price_unit = price_unit - tax['amount'] + return {'price_unit': price_unit,'invoice_line_tax_id': tax_id} - def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, price_unit=False, address_invoice_id=False, context={}): - if not product: - if type in ('in_invoice', 'in_refund'): - return {'domain':{'product_uom':[]}} - else: - return {'value': {'price_unit': 0.0}, 'domain':{'product_uom':[]}} - lang=False - context.update({'lang': lang}) - res = self.pool.get('product.product').browse(cr, uid, product, context=context) - taxep=None - if partner_id: - lang=self.pool.get('res.partner').read(cr, uid, [partner_id])[0]['lang'] - taxep = self.pool.get('res.partner').browse(cr, uid, partner_id).property_account_tax - tax_obj = self.pool.get('account.tax') - if type in ('out_invoice', 'out_refund'): - if not taxep or not taxep.id: - tax_id = map(lambda x: x.id, res.taxes_id) - else: - tax_id = [taxep.id] - for t in res.taxes_id: - if not t.tax_group==taxep.tax_group: - tax_id.append(t.id) - else: - if not taxep or not taxep.id: - tax_id = map(lambda x: x.id, res.supplier_taxes_id) - else: - tax_id = [taxep.id] - for t in res.supplier_taxes_id: - if not t.tax_group==taxep.tax_group: - tax_id.append(t.id) - if type in ('in_invoice', 'in_refund'): - result = self.product_id_change_unit_price_inv(cr, uid, tax_id, price_unit, qty, address_invoice_id, product, partner_id, context=context) - else: - result = {'price_unit': res.list_price, 'invoice_line_tax_id': tax_id} + def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, price_unit=False, address_invoice_id=False, context={}): + if not product: + if type in ('in_invoice', 'in_refund'): + return {'domain':{'product_uom':[]}} + else: + return {'value': {'price_unit': 0.0}, 'domain':{'product_uom':[]}} + lang=False + context.update({'lang': lang}) + res = self.pool.get('product.product').browse(cr, uid, product, context=context) + taxep=None + if partner_id: + lang=self.pool.get('res.partner').read(cr, uid, [partner_id])[0]['lang'] + taxep = self.pool.get('res.partner').browse(cr, uid, partner_id).property_account_tax + tax_obj = self.pool.get('account.tax') + if type in ('out_invoice', 'out_refund'): + if not taxep or not taxep.id: + tax_id = map(lambda x: x.id, res.taxes_id) + else: + tax_id = [taxep.id] + for t in res.taxes_id: + if not t.tax_group==taxep.tax_group: + tax_id.append(t.id) + else: + if not taxep or not taxep.id: + tax_id = map(lambda x: x.id, res.supplier_taxes_id) + else: + tax_id = [taxep.id] + for t in res.supplier_taxes_id: + if not t.tax_group==taxep.tax_group: + tax_id.append(t.id) + if type in ('in_invoice', 'in_refund'): + result = self.product_id_change_unit_price_inv(cr, uid, tax_id, price_unit, qty, address_invoice_id, product, partner_id, context=context) + else: + result = {'price_unit': res.list_price, 'invoice_line_tax_id': tax_id} - if not name: - result['name'] = res.name + if not name: + result['name'] = res.name - if type in ('out_invoice','out_refund'): - a = res.product_tmpl_id.property_account_income.id - if not a: - a = res.categ_id.property_account_income_categ.id - else: - a = res.product_tmpl_id.property_account_expense.id - if not a: - a = res.categ_id.property_account_expense_categ.id - if a: - result['account_id'] = a + if type in ('out_invoice','out_refund'): + a = res.product_tmpl_id.property_account_income.id + if not a: + a = res.categ_id.property_account_income_categ.id + else: + a = res.product_tmpl_id.property_account_expense.id + if not a: + a = res.categ_id.property_account_expense_categ.id + if a: + result['account_id'] = a - domain = {} - result['uos_id'] = uom or res.uom_id.id or False - if result['uos_id']: - res2 = res.uom_id.category_id.id - if res2 : - domain = {'uos_id':[('category_id','=',res2 )]} - return {'value':result, 'domain':domain} + domain = {} + result['uos_id'] = uom or res.uom_id.id or False + if result['uos_id']: + res2 = res.uom_id.category_id.id + if res2 : + domain = {'uos_id':[('category_id','=',res2 )]} + return {'value':result, 'domain':domain} - def move_line_get(self, cr, uid, invoice_id, context={}): - res = [] - tax_grouped = {} - tax_obj = self.pool.get('account.tax') - cur_obj = self.pool.get('res.currency') - ait_obj = self.pool.get('account.invoice.tax') - inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id) - company_currency = inv.company_id.currency_id.id - cur = inv.currency_id + def move_line_get(self, cr, uid, invoice_id, context={}): + res = [] + tax_grouped = {} + tax_obj = self.pool.get('account.tax') + cur_obj = self.pool.get('res.currency') + ait_obj = self.pool.get('account.invoice.tax') + inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id) + company_currency = inv.company_id.currency_id.id + cur = inv.currency_id - for line in inv.invoice_line: - mres = self.move_line_get_item(cr, uid, line, context) - if not mres: - continue - res.append(mres) - tax_code_found= False - for tax in tax_obj.compute(cr, uid, line.invoice_line_tax_id, - (line.price_unit * (1.0 - (line['discount'] or 0.0) / 100.0)), - line.quantity, inv.address_invoice_id.id, line.product_id, - inv.partner_id): + for line in inv.invoice_line: + mres = self.move_line_get_item(cr, uid, line, context) + if not mres: + continue + res.append(mres) + tax_code_found= False + for tax in tax_obj.compute(cr, uid, line.invoice_line_tax_id, + (line.price_unit * (1.0 - (line['discount'] or 0.0) / 100.0)), + line.quantity, inv.address_invoice_id.id, line.product_id, + inv.partner_id): - if inv.type in ('out_invoice', 'in_invoice'): - tax_code_id = tax['base_code_id'] - tax_amount = line.price_subtotal * tax['base_sign'] - else: - tax_code_id = tax['ref_base_code_id'] - tax_amount = line.price_subtotal * tax['ref_base_sign'] + if inv.type in ('out_invoice', 'in_invoice'): + tax_code_id = tax['base_code_id'] + tax_amount = line.price_subtotal * tax['base_sign'] + else: + tax_code_id = tax['ref_base_code_id'] + tax_amount = line.price_subtotal * tax['ref_base_sign'] - if tax_code_found: - if not tax_code_id: - continue - res.append(self.move_line_get_item(cr, uid, line, context)) - res[-1]['price'] = 0.0 - res[-1]['account_analytic_id'] = False - elif not tax_code_id: - continue - tax_code_found = True + if tax_code_found: + if not tax_code_id: + continue + res.append(self.move_line_get_item(cr, uid, line, context)) + res[-1]['price'] = 0.0 + res[-1]['account_analytic_id'] = False + elif not tax_code_id: + continue + tax_code_found = True - res[-1]['tax_code_id'] = tax_code_id - res[-1]['tax_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, tax_amount, context={'date': inv.date_invoice}) - return res + res[-1]['tax_code_id'] = tax_code_id + res[-1]['tax_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, tax_amount, context={'date': inv.date_invoice}) + return res - def move_line_get_item(self, cr, uid, line, context={}): - return { - 'type':'src', - 'name': line.name[:64], - 'price_unit':line.price_unit, - 'quantity':line.quantity, - 'price':line.price_subtotal, - 'account_id':line.account_id.id, - 'product_id':line.product_id.id, - 'uos_id':line.uos_id.id, - 'account_analytic_id':line.account_analytic_id.id, - } - # - # Set the tax field according to the account and the partner - # - def onchange_account_id(self, cr, uid, ids, partner_id,account_id): - if not (partner_id and account_id): - return {} - taxes = self.pool.get('account.account').browse(cr, uid, account_id).tax_ids - taxep = self.pool.get('res.partner').browse(cr, uid, partner_id).property_account_tax - if not taxep.id: - return {'value': {'invoice_line_tax_id': map(lambda x: x.id, taxes or []) }} - res = [taxep.id] - for t in taxes: - if not t.tax_group==taxep.tax_group: - res.append(t.id) - r = {'value':{'invoice_line_tax_id': res}} - return r + def move_line_get_item(self, cr, uid, line, context={}): + return { + 'type':'src', + 'name': line.name[:64], + 'price_unit':line.price_unit, + 'quantity':line.quantity, + 'price':line.price_subtotal, + 'account_id':line.account_id.id, + 'product_id':line.product_id.id, + 'uos_id':line.uos_id.id, + 'account_analytic_id':line.account_analytic_id.id, + } + # + # Set the tax field according to the account and the partner + # + def onchange_account_id(self, cr, uid, ids, partner_id,account_id): + if not (partner_id and account_id): + return {} + taxes = self.pool.get('account.account').browse(cr, uid, account_id).tax_ids + taxep = self.pool.get('res.partner').browse(cr, uid, partner_id).property_account_tax + if not taxep.id: + return {'value': {'invoice_line_tax_id': map(lambda x: x.id, taxes or []) }} + res = [taxep.id] + for t in taxes: + if not t.tax_group==taxep.tax_group: + res.append(t.id) + r = {'value':{'invoice_line_tax_id': res}} + return r account_invoice_line() class account_invoice_tax(osv.osv): - _name = "account.invoice.tax" - _description = "Invoice Tax" - _columns = { - 'invoice_id': fields.many2one('account.invoice', 'Invoice Line', ondelete='cascade', select=True), - 'name': fields.char('Tax Description', size=64, required=True), - 'account_id': fields.many2one('account.account', 'Tax Account', required=True, domain=[('type','<>','view'),('type','<>','income'), ('type', '<>', 'closed')]), - 'base': fields.float('Base', digits=(16,2)), - 'amount': fields.float('Amount', digits=(16,2)), - 'manual': fields.boolean('Manual'), - 'sequence': fields.integer('Sequence'), + _name = "account.invoice.tax" + _description = "Invoice Tax" + _columns = { + 'invoice_id': fields.many2one('account.invoice', 'Invoice Line', ondelete='cascade', select=True), + 'name': fields.char('Tax Description', size=64, required=True), + 'account_id': fields.many2one('account.account', 'Tax Account', required=True, domain=[('type','<>','view'),('type','<>','income'), ('type', '<>', 'closed')]), + 'base': fields.float('Base', digits=(16,2)), + 'amount': fields.float('Amount', digits=(16,2)), + 'manual': fields.boolean('Manual'), + 'sequence': fields.integer('Sequence'), - 'base_code_id': fields.many2one('account.tax.code', 'Base Code'), - 'base_amount': fields.float('Base Code Amount', digits=(16,2)), - 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code'), - 'tax_amount': fields.float('Tax Code Amount', digits=(16,2)), - } - def base_change(self, cr, uid, ids, base): - return {'value': {'base_amount':base}} - def amount_change(self, cr, uid, ids, amount): - return {'value': {'tax_amount':amount}} - _order = 'sequence' - _defaults = { - 'manual': lambda *a: 1, - 'base_amount': lambda *a: 0.0, - 'tax_amount': lambda *a: 0.0, - } - def compute(self, cr, uid, invoice_id): - tax_grouped = {} - tax_obj = self.pool.get('account.tax') - cur_obj = self.pool.get('res.currency') - inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id) - cur = inv.currency_id - company_currency = inv.company_id.currency_id.id + 'base_code_id': fields.many2one('account.tax.code', 'Base Code'), + 'base_amount': fields.float('Base Code Amount', digits=(16,2)), + 'tax_code_id': fields.many2one('account.tax.code', 'Tax Code'), + 'tax_amount': fields.float('Tax Code Amount', digits=(16,2)), + } + def base_change(self, cr, uid, ids, base): + return {'value': {'base_amount':base}} + def amount_change(self, cr, uid, ids, amount): + return {'value': {'tax_amount':amount}} + _order = 'sequence' + _defaults = { + 'manual': lambda *a: 1, + 'base_amount': lambda *a: 0.0, + 'tax_amount': lambda *a: 0.0, + } + def compute(self, cr, uid, invoice_id): + tax_grouped = {} + tax_obj = self.pool.get('account.tax') + cur_obj = self.pool.get('res.currency') + inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id) + cur = inv.currency_id + company_currency = inv.company_id.currency_id.id - for line in inv.invoice_line: - for tax in tax_obj.compute(cr, uid, line.invoice_line_tax_id, (line.price_unit* (1-(line.discount or 0.0)/100.0)), line.quantity, inv.address_invoice_id.id, line.product_id, inv.partner_id): - val={} - val['invoice_id'] = inv.id - val['name'] = tax['name'] - val['amount'] = cur_obj.round(cr, uid, cur, tax['amount']) - val['manual'] = False - val['sequence'] = tax['sequence'] - val['base'] = tax['price_unit'] * line['quantity'] + for line in inv.invoice_line: + for tax in tax_obj.compute(cr, uid, line.invoice_line_tax_id, (line.price_unit* (1-(line.discount or 0.0)/100.0)), line.quantity, inv.address_invoice_id.id, line.product_id, inv.partner_id): + val={} + val['invoice_id'] = inv.id + val['name'] = tax['name'] + val['amount'] = cur_obj.round(cr, uid, cur, tax['amount']) + val['manual'] = False + val['sequence'] = tax['sequence'] + val['base'] = tax['price_unit'] * line['quantity'] - if inv.type in ('out_invoice','in_invoice'): - val['base_code_id'] = tax['base_code_id'] - val['tax_code_id'] = tax['tax_code_id'] - val['base_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['base'] * tax['base_sign'], context={'date': inv.date_invoice}) - val['tax_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['amount'] * tax['tax_sign'], context={'date': inv.date_invoice}) - val['account_id'] = tax['account_collected_id'] or line.account_id.id - else: - val['base_code_id'] = tax['ref_base_code_id'] - val['tax_code_id'] = tax['ref_tax_code_id'] - val['base_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['base'] * tax['ref_base_sign'], context={'date': inv.date_invoice}) - val['tax_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['amount'] * tax['ref_tax_sign'], context={'date': inv.date_invoice}) - val['account_id'] = tax['account_paid_id'] or line.account_id.id + if inv.type in ('out_invoice','in_invoice'): + val['base_code_id'] = tax['base_code_id'] + val['tax_code_id'] = tax['tax_code_id'] + val['base_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['base'] * tax['base_sign'], context={'date': inv.date_invoice}) + val['tax_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['amount'] * tax['tax_sign'], context={'date': inv.date_invoice}) + val['account_id'] = tax['account_collected_id'] or line.account_id.id + else: + val['base_code_id'] = tax['ref_base_code_id'] + val['tax_code_id'] = tax['ref_tax_code_id'] + val['base_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['base'] * tax['ref_base_sign'], context={'date': inv.date_invoice}) + val['tax_amount'] = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, val['amount'] * tax['ref_tax_sign'], context={'date': inv.date_invoice}) + val['account_id'] = tax['account_paid_id'] or line.account_id.id - key = (val['tax_code_id'], val['base_code_id'], val['account_id']) - if not key in tax_grouped: - tax_grouped[key] = val - else: - tax_grouped[key]['amount'] += val['amount'] - tax_grouped[key]['base'] += val['base'] - tax_grouped[key]['base_amount'] += val['base_amount'] - tax_grouped[key]['tax_amount'] += val['tax_amount'] + key = (val['tax_code_id'], val['base_code_id'], val['account_id']) + if not key in tax_grouped: + tax_grouped[key] = val + else: + tax_grouped[key]['amount'] += val['amount'] + tax_grouped[key]['base'] += val['base'] + tax_grouped[key]['base_amount'] += val['base_amount'] + tax_grouped[key]['tax_amount'] += val['tax_amount'] - return tax_grouped + return tax_grouped - def move_line_get(self, cr, uid, invoice_id): - res = [] - cr.execute('SELECT * FROM account_invoice_tax WHERE invoice_id=%d', (invoice_id,)) - for t in cr.dictfetchall(): - if not t['amount'] \ - and not t['tax_code_id'] \ - and not t['tax_amount']: - continue - res.append({ - 'type':'tax', - 'name':t['name'], - 'price_unit': t['amount'], - 'quantity': 1, - 'price': t['amount'] or 0.0, - 'account_id': t['account_id'], - 'tax_code_id': t['tax_code_id'], - 'tax_amount': t['tax_amount'] - }) - return res + def move_line_get(self, cr, uid, invoice_id): + res = [] + cr.execute('SELECT * FROM account_invoice_tax WHERE invoice_id=%d', (invoice_id,)) + for t in cr.dictfetchall(): + if not t['amount'] \ + and not t['tax_code_id'] \ + and not t['tax_amount']: + continue + res.append({ + 'type':'tax', + 'name':t['name'], + 'price_unit': t['amount'], + 'quantity': 1, + 'price': t['amount'] or 0.0, + 'account_id': t['account_id'], + 'tax_code_id': t['tax_code_id'], + 'tax_amount': t['tax_amount'] + }) + return res account_invoice_tax() diff --git a/addons/account/partner.py b/addons/account/partner.py index 539a8ef2d2f..97d0cf9544d 100644 --- a/addons/account/partner.py +++ b/addons/account/partner.py @@ -32,94 +32,94 @@ from osv import fields, osv import ir class res_partner(osv.osv): - _name = 'res.partner' - _inherit = 'res.partner' - _description = 'Partner' - def _credit_get(self, cr, uid, ids, name, arg, context): - res={} - query = self.pool.get('account.move.line')._query_get(cr, uid, context=context) - for id in ids: - cr.execute("select sum(debit-credit) from account_move_line as l where account_id in (select id from account_account where type = %s and active) and partner_id=%d and reconcile_id is null and "+query, ('receivable', id)) - res[id]=cr.fetchone()[0] or 0.0 - return res + _name = 'res.partner' + _inherit = 'res.partner' + _description = 'Partner' + def _credit_get(self, cr, uid, ids, name, arg, context): + res={} + query = self.pool.get('account.move.line')._query_get(cr, uid, context=context) + for id in ids: + cr.execute("select sum(debit-credit) from account_move_line as l where account_id in (select id from account_account where type = %s and active) and partner_id=%d and reconcile_id is null and "+query, ('receivable', id)) + res[id]=cr.fetchone()[0] or 0.0 + return res - def _debit_get(self, cr, uid, ids, name, arg, context): - res={} - query = self.pool.get('account.move.line')._query_get(cr, uid, context=context) - for id in ids: - cr.execute("select sum(debit-credit) from account_move_line as l where account_id in (select id from account_account where type = %s and active) and partner_id=%d and reconcile_id is null and "+query, ('payable', id)) - res[id]=cr.fetchone()[0] or 0.0 - return res + def _debit_get(self, cr, uid, ids, name, arg, context): + res={} + query = self.pool.get('account.move.line')._query_get(cr, uid, context=context) + for id in ids: + cr.execute("select sum(debit-credit) from account_move_line as l where account_id in (select id from account_account where type = %s and active) and partner_id=%d and reconcile_id is null and "+query, ('payable', id)) + res[id]=cr.fetchone()[0] or 0.0 + return res - def _credit_search(self, cr, uid, obj, name, args): - if not len(args): - return [] - where = ' and '.join(map(lambda x: '(sum(debit-credit)'+x[1]+str(x[2])+')',args)) - query = self.pool.get('account.move.line')._query_get(cr, uid, context={}) - cr.execute(('select partner_id from account_move_line l where account_id in (select id from account_account where type=%s and active) and reconcile_id is null and '+query+' and partner_id is not null group by partner_id having '+where), ('receivable',) ) - res = cr.fetchall() - if not len(res): - return [('id','=','0')] - return [('id','in',map(lambda x:x[0], res))] + def _credit_search(self, cr, uid, obj, name, args): + if not len(args): + return [] + where = ' and '.join(map(lambda x: '(sum(debit-credit)'+x[1]+str(x[2])+')',args)) + query = self.pool.get('account.move.line')._query_get(cr, uid, context={}) + cr.execute(('select partner_id from account_move_line l where account_id in (select id from account_account where type=%s and active) and reconcile_id is null and '+query+' and partner_id is not null group by partner_id having '+where), ('receivable',) ) + res = cr.fetchall() + if not len(res): + return [('id','=','0')] + return [('id','in',map(lambda x:x[0], res))] - def _debit_search(self, cr, uid, obj, name, args): - if not len(args): - return [] - query = self.pool.get('account.move.line')._query_get(cr, uid, context={}) - where = ' and '.join(map(lambda x: '(sum(debit-credit)'+x[1]+str(x[2])+')',args)) - cr.execute(('select partner_id from account_move_line l where account_id in (select id from account_account where type=%s and active) and reconcile_id is null and '+query+' and partner_id is not null group by partner_id having '+where), ('payable',) ) - res = cr.fetchall() - if not len(res): - return [('id','=','0')] - return [('id','in',map(lambda x:x[0], res))] + def _debit_search(self, cr, uid, obj, name, args): + if not len(args): + return [] + query = self.pool.get('account.move.line')._query_get(cr, uid, context={}) + where = ' and '.join(map(lambda x: '(sum(debit-credit)'+x[1]+str(x[2])+')',args)) + cr.execute(('select partner_id from account_move_line l where account_id in (select id from account_account where type=%s and active) and reconcile_id is null and '+query+' and partner_id is not null group by partner_id having '+where), ('payable',) ) + res = cr.fetchall() + if not len(res): + return [('id','=','0')] + return [('id','in',map(lambda x:x[0], res))] - _columns = { - 'credit': fields.function(_credit_get, fnct_search=_credit_search, method=True, string='Total Receivable'), - 'debit': fields.function(_debit_get, fnct_search=_debit_search, method=True, string='Total Payable'), - 'debit_limit': fields.float('Payable Limit'), - 'property_account_payable': fields.property( - 'account.account', - type='many2one', - relation='account.account', - string="Account Payable", - method=True, - view_load=True, - group_name="Accounting Properties", - domain="[('type', '=', 'payable')]", - help="This account will be used, instead of the default one, as the payable account for the current partner", - required=True), - 'property_account_receivable': fields.property( - 'account.account', - type='many2one', - relation='account.account', - string="Account Receivable", - method=True, - view_load=True, - group_name="Accounting Properties", - domain="[('type', '=', 'receivable')]", - help="This account will be used, instead of the default one, as the receivable account for the current partner", - required=True), - 'property_account_tax': fields.property( - 'account.tax', - type='many2one', - relation='account.tax', - string="Default Tax", - method=True, - view_load=True, - group_name="Accounting Properties", - help="This tax will be used, instead of the default one."), - 'property_payment_term': fields.property( - 'account.payment.term', - type='many2one', - relation='account.payment.term', - string ='Payment Term', - method=True, - view_load=True, - group_name="Accounting Properties", - help="This payment term will be used, instead of the default one, for the current partner"), - 'ref_companies': fields.one2many('res.company', 'partner_id', - 'Companies that refers to partner'), - } + _columns = { + 'credit': fields.function(_credit_get, fnct_search=_credit_search, method=True, string='Total Receivable'), + 'debit': fields.function(_debit_get, fnct_search=_debit_search, method=True, string='Total Payable'), + 'debit_limit': fields.float('Payable Limit'), + 'property_account_payable': fields.property( + 'account.account', + type='many2one', + relation='account.account', + string="Account Payable", + method=True, + view_load=True, + group_name="Accounting Properties", + domain="[('type', '=', 'payable')]", + help="This account will be used, instead of the default one, as the payable account for the current partner", + required=True), + 'property_account_receivable': fields.property( + 'account.account', + type='many2one', + relation='account.account', + string="Account Receivable", + method=True, + view_load=True, + group_name="Accounting Properties", + domain="[('type', '=', 'receivable')]", + help="This account will be used, instead of the default one, as the receivable account for the current partner", + required=True), + 'property_account_tax': fields.property( + 'account.tax', + type='many2one', + relation='account.tax', + string="Default Tax", + method=True, + view_load=True, + group_name="Accounting Properties", + help="This tax will be used, instead of the default one."), + 'property_payment_term': fields.property( + 'account.payment.term', + type='many2one', + relation='account.payment.term', + string ='Payment Term', + method=True, + view_load=True, + group_name="Accounting Properties", + help="This payment term will be used, instead of the default one, for the current partner"), + 'ref_companies': fields.one2many('res.company', 'partner_id', + 'Companies that refers to partner'), + } res_partner() diff --git a/addons/account/product.py b/addons/account/product.py index 5c4d2ffa26f..151d6218c69 100644 --- a/addons/account/product.py +++ b/addons/account/product.py @@ -33,58 +33,58 @@ import netsvc from osv import fields, osv class product_category(osv.osv): - _inherit = "product.category" - _columns = { - 'property_account_income_categ': fields.property( - 'account.account', - type='many2one', - relation='account.account', - string="Income Account", - method=True, - view_load=True, - group_name="Accounting Properties", - help="This account will be used, instead of the default one, to value incoming stock for the current product category"), - 'property_account_expense_categ': fields.property( - 'account.account', - type='many2one', - relation='account.account', - string="Expense Account", - method=True, - view_load=True, - group_name="Accounting Properties", - help="This account will be used, instead of the default one, to value outgoing stock for the current product category"), - } + _inherit = "product.category" + _columns = { + 'property_account_income_categ': fields.property( + 'account.account', + type='many2one', + relation='account.account', + string="Income Account", + method=True, + view_load=True, + group_name="Accounting Properties", + help="This account will be used, instead of the default one, to value incoming stock for the current product category"), + 'property_account_expense_categ': fields.property( + 'account.account', + type='many2one', + relation='account.account', + string="Expense Account", + method=True, + view_load=True, + group_name="Accounting Properties", + help="This account will be used, instead of the default one, to value outgoing stock for the current product category"), + } product_category() #---------------------------------------------------------- # Products #---------------------------------------------------------- class product_template(osv.osv): - _inherit = "product.template" - _columns = { - 'taxes_id': fields.many2many('account.tax', 'product_taxes_rel', - 'prod_id', 'tax_id', 'Customer Taxes', - domain=[('parent_id','=',False)]), - 'supplier_taxes_id': fields.many2many('account.tax', - 'product_supplier_taxes_rel', 'prod_id', 'tax_id', - 'Supplier Taxes', domain=[('parent_id', '=', False)]), - 'property_account_income': fields.property( - 'account.account', - type='many2one', - relation='account.account', - string="Income Account", - method=True, - view_load=True, - group_name="Accounting Properties", - help="This account will be used, instead of the default one, to value incoming stock for the current product"), - 'property_account_expense': fields.property( - 'account.account', - type='many2one', - relation='account.account', - string="Expense Account", - method=True, - view_load=True, - group_name="Accounting Properties", - help="This account will be used, instead of the default one, to value outgoing stock for the current product"), - } + _inherit = "product.template" + _columns = { + 'taxes_id': fields.many2many('account.tax', 'product_taxes_rel', + 'prod_id', 'tax_id', 'Customer Taxes', + domain=[('parent_id','=',False)]), + 'supplier_taxes_id': fields.many2many('account.tax', + 'product_supplier_taxes_rel', 'prod_id', 'tax_id', + 'Supplier Taxes', domain=[('parent_id', '=', False)]), + 'property_account_income': fields.property( + 'account.account', + type='many2one', + relation='account.account', + string="Income Account", + method=True, + view_load=True, + group_name="Accounting Properties", + help="This account will be used, instead of the default one, to value incoming stock for the current product"), + 'property_account_expense': fields.property( + 'account.account', + type='many2one', + relation='account.account', + string="Expense Account", + method=True, + view_load=True, + group_name="Accounting Properties", + help="This account will be used, instead of the default one, to value outgoing stock for the current product"), + } product_template() diff --git a/addons/account/project/project.py b/addons/account/project/project.py index 1bf9bf0a4c4..c2ca84fb738 100644 --- a/addons/account/project/project.py +++ b/addons/account/project/project.py @@ -38,202 +38,202 @@ from osv import osv # class account_analytic_account(osv.osv): - _name = 'account.analytic.account' - _description = 'Analytic Accounts' + _name = 'account.analytic.account' + _description = 'Analytic Accounts' - def _credit_calc(self, cr, uid, ids, name, arg, context={}): - acc_set = ",".join(map(str, ids)) - cr.execute("SELECT a.id, COALESCE(SUM(l.amount),0) FROM account_analytic_account a LEFT JOIN account_analytic_line l ON (a.id=l.account_id) WHERE l.amount<0 and a.id IN (%s) GROUP BY a.id" % acc_set) - r= dict(cr.fetchall()) - for i in ids: - r.setdefault(i,0.0) - return r + def _credit_calc(self, cr, uid, ids, name, arg, context={}): + acc_set = ",".join(map(str, ids)) + cr.execute("SELECT a.id, COALESCE(SUM(l.amount),0) FROM account_analytic_account a LEFT JOIN account_analytic_line l ON (a.id=l.account_id) WHERE l.amount<0 and a.id IN (%s) GROUP BY a.id" % acc_set) + r= dict(cr.fetchall()) + for i in ids: + r.setdefault(i,0.0) + return r - def _debit_calc(self, cr, uid, ids, name, arg, context={}): + def _debit_calc(self, cr, uid, ids, name, arg, context={}): - acc_set = ",".join(map(str, ids)) - cr.execute("SELECT a.id, COALESCE(SUM(l.amount),0) FROM account_analytic_account a LEFT JOIN account_analytic_line l ON (a.id=l.account_id) WHERE l.amount>0 and a.id IN (%s) GROUP BY a.id" % acc_set) - r= dict(cr.fetchall()) - for i in ids: - r.setdefault(i,0.0) - return r + acc_set = ",".join(map(str, ids)) + cr.execute("SELECT a.id, COALESCE(SUM(l.amount),0) FROM account_analytic_account a LEFT JOIN account_analytic_line l ON (a.id=l.account_id) WHERE l.amount>0 and a.id IN (%s) GROUP BY a.id" % acc_set) + r= dict(cr.fetchall()) + for i in ids: + r.setdefault(i,0.0) + return r - def _balance_calc(self, cr, uid, ids, name, arg, context={}): - ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)]) - acc_set = ",".join(map(str, ids2)) - cr.execute("SELECT a.id, COALESCE(SUM(l.amount),0) FROM account_analytic_account a LEFT JOIN account_analytic_line l ON (a.id=l.account_id) WHERE a.id IN (%s) GROUP BY a.id" % acc_set) - res = {} - for account_id, sum in cr.fetchall(): - res[account_id] = sum + def _balance_calc(self, cr, uid, ids, name, arg, context={}): + ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)]) + acc_set = ",".join(map(str, ids2)) + cr.execute("SELECT a.id, COALESCE(SUM(l.amount),0) FROM account_analytic_account a LEFT JOIN account_analytic_line l ON (a.id=l.account_id) WHERE a.id IN (%s) GROUP BY a.id" % acc_set) + res = {} + for account_id, sum in cr.fetchall(): + res[account_id] = sum - cr.execute("SELECT a.id, r.currency_id FROM account_analytic_account a INNER JOIN res_company r ON (a.company_id = r.id) where a.id in (%s)" % acc_set) + cr.execute("SELECT a.id, r.currency_id FROM account_analytic_account a INNER JOIN res_company r ON (a.company_id = r.id) where a.id in (%s)" % acc_set) - currency= dict(cr.fetchall()) + currency= dict(cr.fetchall()) - res_currency= self.pool.get('res.currency') - for id in ids: - for child in self.search(cr, uid, [('parent_id', 'child_of', [id])]): - if child <> id: - res.setdefault(id, 0.0) - if currency[child]<>currency[id] : - res[id] += res_currency.compute(cr, uid, currency[child], currency[id], res.get(child, 0.0), context=context) - else: - res[id] += res.get(child, 0.0) + res_currency= self.pool.get('res.currency') + for id in ids: + for child in self.search(cr, uid, [('parent_id', 'child_of', [id])]): + if child <> id: + res.setdefault(id, 0.0) + if currency[child]<>currency[id] : + res[id] += res_currency.compute(cr, uid, currency[child], currency[id], res.get(child, 0.0), context=context) + else: + res[id] += res.get(child, 0.0) - cur_obj = res_currency.browse(cr,uid,currency.values(),context) - cur_obj = dict([(o.id, o) for o in cur_obj]) - for id in ids: - res[id] = res_currency.round(cr,uid,cur_obj[currency[id]],res.get(id,0.0)) + cur_obj = res_currency.browse(cr,uid,currency.values(),context) + cur_obj = dict([(o.id, o) for o in cur_obj]) + for id in ids: + res[id] = res_currency.round(cr,uid,cur_obj[currency[id]],res.get(id,0.0)) - return dict([(i, res[i]) for i in ids ]) + return dict([(i, res[i]) for i in ids ]) - def _quantity_calc(self, cr, uid, ids, name, arg, context={}): - #XXX must convert into one uom - ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)]) - acc_set = ",".join(map(str, ids2)) - cr.execute('SELECT a.id, COALESCE(SUM(l.unit_amount), 0) \ - FROM account_analytic_account a \ - LEFT JOIN account_analytic_line l ON (a.id = l.account_id) \ - WHERE a.id IN ('+acc_set+') GROUP BY a.id') - res = {} - for account_id, sum in cr.fetchall(): - res[account_id] = sum + def _quantity_calc(self, cr, uid, ids, name, arg, context={}): + #XXX must convert into one uom + ids2 = self.search(cr, uid, [('parent_id', 'child_of', ids)]) + acc_set = ",".join(map(str, ids2)) + cr.execute('SELECT a.id, COALESCE(SUM(l.unit_amount), 0) \ + FROM account_analytic_account a \ + LEFT JOIN account_analytic_line l ON (a.id = l.account_id) \ + WHERE a.id IN ('+acc_set+') GROUP BY a.id') + res = {} + for account_id, sum in cr.fetchall(): + res[account_id] = sum - for id in ids: - for child in self.search(cr, uid, [('parent_id', 'child_of', [id])]): - if child <> id: - res.setdefault(id, 0.0) - res[id] += res.get(child, 0.0) - return dict([(i, res[i]) for i in ids]) + for id in ids: + for child in self.search(cr, uid, [('parent_id', 'child_of', [id])]): + if child <> id: + res.setdefault(id, 0.0) + res[id] += res.get(child, 0.0) + return dict([(i, res[i]) for i in ids]) - def name_get(self, cr, uid, ids, context={}): - if not len(ids): - return [] - reads = self.read(cr, uid, ids, ['name','parent_id'], context) - res = [] - for record in reads: - name = record['name'] - if record['parent_id']: - name = record['parent_id'][1]+' / '+name - res.append((record['id'], name)) - return res + def name_get(self, cr, uid, ids, context={}): + if not len(ids): + return [] + reads = self.read(cr, uid, ids, ['name','parent_id'], context) + res = [] + for record in reads: + name = record['name'] + if record['parent_id']: + name = record['parent_id'][1]+' / '+name + res.append((record['id'], name)) + return res - def _complete_name_calc(self, cr, uid, ids, prop, unknow_none, unknow_dict): - res = self.name_get(cr, uid, ids) - return dict(res) + def _complete_name_calc(self, cr, uid, ids, prop, unknow_none, unknow_dict): + res = self.name_get(cr, uid, ids) + return dict(res) - def _get_company_currency(self, cr, uid, ids, field_name, arg, context={}): - result = {} - for rec in self.browse(cr, uid, ids, context): - result[rec.id] = (rec.company_id.currency_id.id,rec.company_id.currency_id.code) or False - return result + def _get_company_currency(self, cr, uid, ids, field_name, arg, context={}): + result = {} + for rec in self.browse(cr, uid, ids, context): + result[rec.id] = (rec.company_id.currency_id.id,rec.company_id.currency_id.code) or False + return result - _columns = { - 'name' : fields.char('Account name', size=64, required=True), - 'complete_name': fields.function(_complete_name_calc, method=True, type='char', string='Account Name'), - 'code' : fields.char('Account code', size=24), - 'active' : fields.boolean('Active'), - 'type': fields.selection([('view','View'), ('normal','Normal')], 'Account type'), - 'description' : fields.text('Description'), - 'parent_id': fields.many2one('account.analytic.account', 'Parent analytic account', select=2), - 'child_ids': fields.one2many('account.analytic.account', 'parent_id', 'Childs Accounts'), - 'line_ids': fields.one2many('account.analytic.line', 'account_id', 'Analytic entries'), - 'balance' : fields.function(_balance_calc, method=True, type='float', string='Balance'), - 'debit' : fields.function(_debit_calc, method=True, type='float', string='Debit'), - 'credit' : fields.function(_credit_calc, method=True, type='float', string='Credit'), - 'quantity': fields.function(_quantity_calc, method=True, type='float', string='Quantity'), - 'quantity_max': fields.float('Maximal quantity'), - 'partner_id' : fields.many2one('res.partner', 'Associated partner'), - 'contact_id' : fields.many2one('res.partner.address', 'Contact'), - 'user_id' : fields.many2one('res.users', 'Account Manager'), - 'date_start': fields.date('Date Start'), - 'date': fields.date('Date End'), - 'company_id': fields.many2one('res.company', 'Company', required=True), - 'company_currency_id': fields.function(_get_company_currency, method=True, type='many2one', relation='res.currency', string='Currency'), - 'state': fields.selection([('draft','Draft'), ('open','Open'), ('pending','Pending'), ('close','Close'),], 'State', required=True), - } + _columns = { + 'name' : fields.char('Account name', size=64, required=True), + 'complete_name': fields.function(_complete_name_calc, method=True, type='char', string='Account Name'), + 'code' : fields.char('Account code', size=24), + 'active' : fields.boolean('Active'), + 'type': fields.selection([('view','View'), ('normal','Normal')], 'Account type'), + 'description' : fields.text('Description'), + 'parent_id': fields.many2one('account.analytic.account', 'Parent analytic account', select=2), + 'child_ids': fields.one2many('account.analytic.account', 'parent_id', 'Childs Accounts'), + 'line_ids': fields.one2many('account.analytic.line', 'account_id', 'Analytic entries'), + 'balance' : fields.function(_balance_calc, method=True, type='float', string='Balance'), + 'debit' : fields.function(_debit_calc, method=True, type='float', string='Debit'), + 'credit' : fields.function(_credit_calc, method=True, type='float', string='Credit'), + 'quantity': fields.function(_quantity_calc, method=True, type='float', string='Quantity'), + 'quantity_max': fields.float('Maximal quantity'), + 'partner_id' : fields.many2one('res.partner', 'Associated partner'), + 'contact_id' : fields.many2one('res.partner.address', 'Contact'), + 'user_id' : fields.many2one('res.users', 'Account Manager'), + 'date_start': fields.date('Date Start'), + 'date': fields.date('Date End'), + 'company_id': fields.many2one('res.company', 'Company', required=True), + 'company_currency_id': fields.function(_get_company_currency, method=True, type='many2one', relation='res.currency', string='Currency'), + 'state': fields.selection([('draft','Draft'), ('open','Open'), ('pending','Pending'), ('close','Close'),], 'State', required=True), + } - def _default_company(self, cr, uid, context={}): - user = self.pool.get('res.users').browse(cr, uid, uid, context=context) - if user.company_id: - return user.company_id.id - return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] - _defaults = { - 'active' : lambda *a : True, - 'type' : lambda *a : 'normal', - 'company_id': _default_company, - 'state' : lambda *a : 'draft', - 'user_id' : lambda self,cr,uid,ctx : uid - } + def _default_company(self, cr, uid, context={}): + user = self.pool.get('res.users').browse(cr, uid, uid, context=context) + if user.company_id: + return user.company_id.id + return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] + _defaults = { + 'active' : lambda *a : True, + 'type' : lambda *a : 'normal', + 'company_id': _default_company, + 'state' : lambda *a : 'draft', + 'user_id' : lambda self,cr,uid,ctx : uid + } - def check_recursion(self, cr, uid, ids, parent=None): - return super(account_analytic_account, self).check_recursion(cr, uid, ids, parent=parent) + def check_recursion(self, cr, uid, ids, parent=None): + return super(account_analytic_account, self).check_recursion(cr, uid, ids, parent=parent) - _order = 'parent_id desc,code' - _constraints = [ - (check_recursion, 'Error! You can not create recursive account.', ['parent_id']) - ] + _order = 'parent_id desc,code' + _constraints = [ + (check_recursion, 'Error! You can not create recursive account.', ['parent_id']) + ] - def create(self, cr, uid, vals, context=None): - parent_id = vals.get('parent_id', 0) - if ('code' not in vals or not vals['code']) and not parent_id: - vals['code'] = self.pool.get('ir.sequence').get(cr, uid, 'account.analytic.account') - return super(account_analytic_account, self).create(cr, uid, vals, context=context) + def create(self, cr, uid, vals, context=None): + parent_id = vals.get('parent_id', 0) + if ('code' not in vals or not vals['code']) and not parent_id: + vals['code'] = self.pool.get('ir.sequence').get(cr, uid, 'account.analytic.account') + return super(account_analytic_account, self).create(cr, uid, vals, context=context) - def copy(self, cr, uid, id, default=None, context={}): - if not default: - default = {} - default['code'] = False - return super(account_analytic_account, self).copy(cr, uid, id, default, context=context) + def copy(self, cr, uid, id, default=None, context={}): + if not default: + default = {} + default['code'] = False + return super(account_analytic_account, self).copy(cr, uid, id, default, context=context) - def on_change_parent(self, cr, uid, id, parent_id): - if not parent_id: - return {} - parent = self.read(cr, uid, [parent_id], ['partner_id','code'])[0] - childs = self.search(cr, uid, [('parent_id', '=', parent_id), ('active', 'in', [True, False])]) - numchild = len(childs) - if parent['partner_id']: - partner = parent['partner_id'][0] - else: - partner = False - res = {'value' : {'code' : '%s - %03d' % (parent['code'] or '', numchild + 1),}} - if partner: - res['value']['partner_id'] = partner - return res + def on_change_parent(self, cr, uid, id, parent_id): + if not parent_id: + return {} + parent = self.read(cr, uid, [parent_id], ['partner_id','code'])[0] + childs = self.search(cr, uid, [('parent_id', '=', parent_id), ('active', 'in', [True, False])]) + numchild = len(childs) + if parent['partner_id']: + partner = parent['partner_id'][0] + else: + partner = False + res = {'value' : {'code' : '%s - %03d' % (parent['code'] or '', numchild + 1),}} + if partner: + res['value']['partner_id'] = partner + return res - def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=80): - if not args: - args=[] - if not context: - context={} - account = self.search(cr, uid, [('code', '=', name)]+args, limit=limit, context=context) - if not account: - account = self.search(cr, uid, [('name', 'ilike', '%%%s%%' % name)]+args, limit=limit, context=context) - newacc = account - while newacc: - newacc = self.search(cr, uid, [('parent_id', 'in', newacc)]+args, limit=limit, context=context) - account+=newacc - return self.name_get(cr, uid, account, context=context) + def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=80): + if not args: + args=[] + if not context: + context={} + account = self.search(cr, uid, [('code', '=', name)]+args, limit=limit, context=context) + if not account: + account = self.search(cr, uid, [('name', 'ilike', '%%%s%%' % name)]+args, limit=limit, context=context) + newacc = account + while newacc: + newacc = self.search(cr, uid, [('parent_id', 'in', newacc)]+args, limit=limit, context=context) + account+=newacc + return self.name_get(cr, uid, account, context=context) account_analytic_account() class account_analytic_journal(osv.osv): - _name = 'account.analytic.journal' - _columns = { - 'name' : fields.char('Journal name', size=64, required=True), - 'code' : fields.char('Journal code', size=8), - 'active' : fields.boolean('Active'), - 'type': fields.selection([('sale','Sale'), ('purchase','Purchase'), ('cash','Cash'), ('general','General'), ('situation','Situation')], 'Type', size=32, required=True, help="Gives the type of the analytic journal. When a document (eg: an invoice) needs to create analytic entries, Tiny ERP will look for a matching journal of the same type."), - 'line_ids' : fields.one2many('account.analytic.line', 'journal_id', 'Lines'), - } - _defaults = { - 'active': lambda *a: True, - 'type': lambda *a: 'general', - } + _name = 'account.analytic.journal' + _columns = { + 'name' : fields.char('Journal name', size=64, required=True), + 'code' : fields.char('Journal code', size=8), + 'active' : fields.boolean('Active'), + 'type': fields.selection([('sale','Sale'), ('purchase','Purchase'), ('cash','Cash'), ('general','General'), ('situation','Situation')], 'Type', size=32, required=True, help="Gives the type of the analytic journal. When a document (eg: an invoice) needs to create analytic entries, Tiny ERP will look for a matching journal of the same type."), + 'line_ids' : fields.one2many('account.analytic.line', 'journal_id', 'Lines'), + } + _defaults = { + 'active': lambda *a: True, + 'type': lambda *a: 'general', + } account_analytic_journal() @@ -242,42 +242,42 @@ account_analytic_journal() # --------------------------------------------------------- #class account_analytic_budget_post(osv.osv): -# _name = 'account.analytic.budget.post' -# _description = 'Budget item' -# _columns = { -# 'code': fields.char('Code', size=64, required=True), -# 'name': fields.char('Name', size=256, required=True), -# 'sens': fields.selection( [('charge','Charge'), ('produit','Product')], 'Direction', required=True), -# 'dotation_ids': fields.one2many('account.analytic.budget.post.dotation', 'post_id', 'Expenses'), -# 'account_ids': fields.many2many('account.analytic.account', 'account_analytic_budget_rel', 'budget_id', 'account_id', 'Accounts'), -# } -# _defaults = { -# 'sens': lambda *a: 'produit', -# } +# _name = 'account.analytic.budget.post' +# _description = 'Budget item' +# _columns = { +# 'code': fields.char('Code', size=64, required=True), +# 'name': fields.char('Name', size=256, required=True), +# 'sens': fields.selection( [('charge','Charge'), ('produit','Product')], 'Direction', required=True), +# 'dotation_ids': fields.one2many('account.analytic.budget.post.dotation', 'post_id', 'Expenses'), +# 'account_ids': fields.many2many('account.analytic.account', 'account_analytic_budget_rel', 'budget_id', 'account_id', 'Accounts'), +# } +# _defaults = { +# 'sens': lambda *a: 'produit', +# } # -# def spread(self, cr, uid, ids, fiscalyear_id=False, quantity=0.0, amount=0.0): +# def spread(self, cr, uid, ids, fiscalyear_id=False, quantity=0.0, amount=0.0): # -# dobj = self.pool.get('account.analytic.budget.post.dotation') -# for o in self.browse(cr, uid, ids): -# # delete dotations for this post -# dobj.unlink(cr, uid, dobj.search(cr, uid, [('post_id','=',o.id)])) +# dobj = self.pool.get('account.analytic.budget.post.dotation') +# for o in self.browse(cr, uid, ids): +# # delete dotations for this post +# dobj.unlink(cr, uid, dobj.search(cr, uid, [('post_id','=',o.id)])) # -# # create one dotation per period in the fiscal year, and spread the total amount/quantity over those dotations -# fy = self.pool.get('account.fiscalyear').browse(cr, uid, [fiscalyear_id])[0] -# num = len(fy.period_ids) -# for p in fy.period_ids: -# dobj.create(cr, uid, {'post_id': o.id, 'period_id': p.id, 'quantity': quantity/num, 'amount': amount/num}) -# return True +# # create one dotation per period in the fiscal year, and spread the total amount/quantity over those dotations +# fy = self.pool.get('account.fiscalyear').browse(cr, uid, [fiscalyear_id])[0] +# num = len(fy.period_ids) +# for p in fy.period_ids: +# dobj.create(cr, uid, {'post_id': o.id, 'period_id': p.id, 'quantity': quantity/num, 'amount': amount/num}) +# return True #account_analytic_budget_post() # #class account_analytic_budget_post_dotation(osv.osv): -# _name = 'account.analytic.budget.post.dotation' -# _description = "Budget item endowment" -# _columns = { -# 'name': fields.char('Name', size=64), -# 'post_id': fields.many2one('account.analytic.budget.post', 'Item', select=True), -# 'period_id': fields.many2one('account.period', 'Period'), -# 'quantity': fields.float('Quantity', digits=(16,2)), -# 'amount': fields.float('Amount', digits=(16,2)), -# } +# _name = 'account.analytic.budget.post.dotation' +# _description = "Budget item endowment" +# _columns = { +# 'name': fields.char('Name', size=64), +# 'post_id': fields.many2one('account.analytic.budget.post', 'Item', select=True), +# 'period_id': fields.many2one('account.period', 'Period'), +# 'quantity': fields.float('Quantity', digits=(16,2)), +# 'amount': fields.float('Amount', digits=(16,2)), +# } #account_analytic_budget_post_dotation() diff --git a/addons/account/project/report/account_journal.py b/addons/account/project/report/account_journal.py index 1ed0bb9f2a7..92d7d983f56 100644 --- a/addons/account/project/report/account_journal.py +++ b/addons/account/project/report/account_journal.py @@ -35,20 +35,20 @@ from report import report_sxw # Use period and Journal for selection or resources # class journal_print(report_sxw.rml_parse): - def lines(self, journal_id, *args): - self.cr.execute('select id from account_analytic_line where journal_id=%d order by date,id', (journal_id,)) - ids = map(lambda x: x[0], self.cr.fetchall()) - res = self.pool.get('account.analytic.line').browse(self.cr, self.uid, ids) - return res - def _sum_lines(self, journal_id): - self.cr.execute('select sum(amount) from account_analytic_line where journal_id=%d', (journal_id,)) - return self.cr.fetchone()[0] or 0.0 - def __init__(self, cr, uid, name, context): - super(journal_print, self).__init__(cr, uid, name, context) - self.localcontext = { - 'time': time, - 'lines': self.lines, - 'sum_lines': self._sum_lines, - } + def lines(self, journal_id, *args): + self.cr.execute('select id from account_analytic_line where journal_id=%d order by date,id', (journal_id,)) + ids = map(lambda x: x[0], self.cr.fetchall()) + res = self.pool.get('account.analytic.line').browse(self.cr, self.uid, ids) + return res + def _sum_lines(self, journal_id): + self.cr.execute('select sum(amount) from account_analytic_line where journal_id=%d', (journal_id,)) + return self.cr.fetchone()[0] or 0.0 + def __init__(self, cr, uid, name, context): + super(journal_print, self).__init__(cr, uid, name, context) + self.localcontext = { + 'time': time, + 'lines': self.lines, + 'sum_lines': self._sum_lines, + } report_sxw.report_sxw('report.account.analytic.journal.print', 'account.analytic.journal', 'addons/account/project/report/analytic_journal.rml',parser=journal_print) diff --git a/addons/account/project/report/analytic_balance.py b/addons/account/project/report/analytic_balance.py index c8038bdb667..4884db9c86c 100644 --- a/addons/account/project/report/analytic_balance.py +++ b/addons/account/project/report/analytic_balance.py @@ -32,137 +32,137 @@ import time from report import report_sxw class account_analytic_balance(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(account_analytic_balance, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time': time, - 'lines_g': self._lines_g, - 'move_sum_debit': self._move_sum_debit, - 'move_sum_credit': self._move_sum_credit, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit, - 'sum_balance': self._sum_balance, - 'sum_quantity': self._sum_quantity, - 'move_sum_balance': self._move_sum_balance, - 'move_sum_quantity': self._move_sum_quantity, - }) - - def _lines_g(self, account_id, date1, date2): - account_analytic_obj = self.pool.get('account.analytic.account') - ids = account_analytic_obj.search(self.cr, self.uid, - [('parent_id', 'child_of', [account_id])]) - self.cr.execute("SELECT aa.name AS name, aa.code AS code, \ - sum(aal.amount) AS balance, sum(aal.unit_amount) AS quantity \ - FROM account_analytic_line AS aal, account_account AS aa \ - WHERE (aal.general_account_id=aa.id) \ - AND (aal.account_id in (" + ','.join(map(str, ids)) + "))\ - AND (date>=%s) AND (date<=%s) AND aa.active \ - GROUP BY aal.general_account_id, aa.name, aa.code, aal.code \ - ORDER BY aal.code", (date1, date2)) - res = self.cr.dictfetchall() - - for r in res: - if r['balance'] > 0: - r['debit'] = r['balance'] - r['credit'] = 0.0 - elif r['balance'] < 0: - r['debit'] = 0.0 - r['credit'] = -r['balance'] - else: - r['balance'] == 0 - r['debit'] = 0.0 - r['credit'] = 0.0 - return res - + def __init__(self, cr, uid, name, context): + super(account_analytic_balance, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time': time, + 'lines_g': self._lines_g, + 'move_sum_debit': self._move_sum_debit, + 'move_sum_credit': self._move_sum_credit, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit, + 'sum_balance': self._sum_balance, + 'sum_quantity': self._sum_quantity, + 'move_sum_balance': self._move_sum_balance, + 'move_sum_quantity': self._move_sum_quantity, + }) + + def _lines_g(self, account_id, date1, date2): + account_analytic_obj = self.pool.get('account.analytic.account') + ids = account_analytic_obj.search(self.cr, self.uid, + [('parent_id', 'child_of', [account_id])]) + self.cr.execute("SELECT aa.name AS name, aa.code AS code, \ + sum(aal.amount) AS balance, sum(aal.unit_amount) AS quantity \ + FROM account_analytic_line AS aal, account_account AS aa \ + WHERE (aal.general_account_id=aa.id) \ + AND (aal.account_id in (" + ','.join(map(str, ids)) + "))\ + AND (date>=%s) AND (date<=%s) AND aa.active \ + GROUP BY aal.general_account_id, aa.name, aa.code, aal.code \ + ORDER BY aal.code", (date1, date2)) + res = self.cr.dictfetchall() + + for r in res: + if r['balance'] > 0: + r['debit'] = r['balance'] + r['credit'] = 0.0 + elif r['balance'] < 0: + r['debit'] = 0.0 + r['credit'] = -r['balance'] + else: + r['balance'] == 0 + r['debit'] = 0.0 + r['credit'] = 0.0 + return res + - def _move_sum_debit(self, account_id, date1, date2): - account_analytic_obj = self.pool.get('account.analytic.account') - ids = account_analytic_obj.search(self.cr, self.uid, - [('parent_id', 'child_of', [account_id])]) - self.cr.execute("SELECT sum(amount) \ - FROM account_analytic_line \ - WHERE account_id in ("+ ','.join(map(str, ids)) +") \ - AND date>=%s AND date<=%s AND amount>0", - (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _move_sum_debit(self, account_id, date1, date2): + account_analytic_obj = self.pool.get('account.analytic.account') + ids = account_analytic_obj.search(self.cr, self.uid, + [('parent_id', 'child_of', [account_id])]) + self.cr.execute("SELECT sum(amount) \ + FROM account_analytic_line \ + WHERE account_id in ("+ ','.join(map(str, ids)) +") \ + AND date>=%s AND date<=%s AND amount>0", + (date1, date2)) + return self.cr.fetchone()[0] or 0.0 - def _move_sum_credit(self, account_id, date1, date2): - account_analytic_obj = self.pool.get('account.analytic.account') - ids = account_analytic_obj.search(self.cr, self.uid, - [('parent_id', 'child_of', [account_id])]) - self.cr.execute("SELECT -sum(amount) \ - FROM account_analytic_line \ - WHERE account_id in ("+ ','.join(map(str, ids)) +") \ - AND date>=%s AND date<=%s AND amount<0", - (date1, date2)) - return self.cr.fetchone()[0] or 0.0 - - def _move_sum_balance(self, account_id, date1, date2): - debit = self._move_sum_debit(account_id, date1, date2) - credit = self._move_sum_credit(account_id, date1, date2) - return (debit-credit) - - def _move_sum_quantity(self, account_id, date1, date2): - account_analytic_obj = self.pool.get('account.analytic.account') - ids = account_analytic_obj.search(self.cr, self.uid, - [('parent_id', 'child_of', [account_id])]) - self.cr.execute("SELECT sum(unit_amount) \ - FROM account_analytic_line \ - WHERE account_id in ("+ ','.join(map(str, ids)) +") \ - AND date>=%s AND date<=%s", - (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _move_sum_credit(self, account_id, date1, date2): + account_analytic_obj = self.pool.get('account.analytic.account') + ids = account_analytic_obj.search(self.cr, self.uid, + [('parent_id', 'child_of', [account_id])]) + self.cr.execute("SELECT -sum(amount) \ + FROM account_analytic_line \ + WHERE account_id in ("+ ','.join(map(str, ids)) +") \ + AND date>=%s AND date<=%s AND amount<0", + (date1, date2)) + return self.cr.fetchone()[0] or 0.0 + + def _move_sum_balance(self, account_id, date1, date2): + debit = self._move_sum_debit(account_id, date1, date2) + credit = self._move_sum_credit(account_id, date1, date2) + return (debit-credit) + + def _move_sum_quantity(self, account_id, date1, date2): + account_analytic_obj = self.pool.get('account.analytic.account') + ids = account_analytic_obj.search(self.cr, self.uid, + [('parent_id', 'child_of', [account_id])]) + self.cr.execute("SELECT sum(unit_amount) \ + FROM account_analytic_line \ + WHERE account_id in ("+ ','.join(map(str, ids)) +") \ + AND date>=%s AND date<=%s", + (date1, date2)) + return self.cr.fetchone()[0] or 0.0 - - def _sum_debit(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - if not len(ids): - return 0.0 - account_analytic_obj = self.pool.get('account.analytic.account') - ids2 = account_analytic_obj.search(self.cr, self.uid, - [('parent_id', 'child_of', ids)]) - self.cr.execute("SELECT sum(amount) \ - FROM account_analytic_line \ - WHERE account_id IN ("+','.join(map(str, ids2))+") \ - AND date>=%s AND date<=%s AND amount>0", - (date1, date2)) - return self.cr.fetchone()[0] or 0.0 - - def _sum_credit(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - if not len(ids): - return 0.0 - ids = map(lambda x: x.id, accounts) - account_analytic_obj = self.pool.get('account.analytic.account') - ids2 = account_analytic_obj.search(self.cr, self.uid, - [('parent_id', 'child_of', ids)]) - self.cr.execute("SELECT -sum(amount) \ - FROM account_analytic_line \ - WHERE account_id IN ("+','.join(map(str, ids2))+") \ - AND date>=%s AND date<=%s AND amount<0", - (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + + def _sum_debit(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + if not len(ids): + return 0.0 + account_analytic_obj = self.pool.get('account.analytic.account') + ids2 = account_analytic_obj.search(self.cr, self.uid, + [('parent_id', 'child_of', ids)]) + self.cr.execute("SELECT sum(amount) \ + FROM account_analytic_line \ + WHERE account_id IN ("+','.join(map(str, ids2))+") \ + AND date>=%s AND date<=%s AND amount>0", + (date1, date2)) + return self.cr.fetchone()[0] or 0.0 + + def _sum_credit(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + if not len(ids): + return 0.0 + ids = map(lambda x: x.id, accounts) + account_analytic_obj = self.pool.get('account.analytic.account') + ids2 = account_analytic_obj.search(self.cr, self.uid, + [('parent_id', 'child_of', ids)]) + self.cr.execute("SELECT -sum(amount) \ + FROM account_analytic_line \ + WHERE account_id IN ("+','.join(map(str, ids2))+") \ + AND date>=%s AND date<=%s AND amount<0", + (date1, date2)) + return self.cr.fetchone()[0] or 0.0 - def _sum_balance(self, accounts, date1, date2): - debit = self._sum_debit(accounts, date1, date2) or 0.0 - credit = self._sum_credit(accounts, date1, date2) or 0.0 - return (debit-credit) + def _sum_balance(self, accounts, date1, date2): + debit = self._sum_debit(accounts, date1, date2) or 0.0 + credit = self._sum_credit(accounts, date1, date2) or 0.0 + return (debit-credit) - def _sum_quantity(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - if not len(ids): - return 0.0 - account_analytic_obj = self.pool.get('account.analytic.account') - ids2 = account_analytic_obj.search(self.cr, self.uid, - [('parent_id', 'child_of', ids)]) - self.cr.execute("SELECT sum(unit_amount) \ - FROM account_analytic_line \ - WHERE account_id IN ("+','.join(map(str, ids2))+") \ - AND date>=%s AND date<=%s", - (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _sum_quantity(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + if not len(ids): + return 0.0 + account_analytic_obj = self.pool.get('account.analytic.account') + ids2 = account_analytic_obj.search(self.cr, self.uid, + [('parent_id', 'child_of', ids)]) + self.cr.execute("SELECT sum(unit_amount) \ + FROM account_analytic_line \ + WHERE account_id IN ("+','.join(map(str, ids2))+") \ + AND date>=%s AND date<=%s", + (date1, date2)) + return self.cr.fetchone()[0] or 0.0 report_sxw.report_sxw('report.account.analytic.account.balance', - 'account.analytic.account', 'addons/account/project/report/analytic_balance.rml', - parser=account_analytic_balance, header=False) + 'account.analytic.account', 'addons/account/project/report/analytic_balance.rml', + parser=account_analytic_balance, header=False) diff --git a/addons/account/project/report/analytic_check.py b/addons/account/project/report/analytic_check.py index 5d849beb82f..6c062a6467f 100644 --- a/addons/account/project/report/analytic_check.py +++ b/addons/account/project/report/analytic_check.py @@ -32,75 +32,75 @@ import time from report import report_sxw class account_analytic_analytic_check(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(account_analytic_analytic_check, self).__init__(cr, uid, name, context) - self.sum_gen_deb = 0.0 - self.sum_gen_cred = 0.0 - self.sum_ana_deb = 0.0 - self.sum_ana_cred = 0.0 - self.localcontext.update( { - 'time': time, - 'lines_p': self._lines_p, - 'general_debit': self._gen_deb, - 'general_credit': self._gen_cred, - 'analytic_debit': self._ana_deb, - 'analytic_credit': self._ana_cred, - 'delta_debit': self._delta_deb, - 'delta_credit': self._delta_cred, - }) + def __init__(self, cr, uid, name, context): + super(account_analytic_analytic_check, self).__init__(cr, uid, name, context) + self.sum_gen_deb = 0.0 + self.sum_gen_cred = 0.0 + self.sum_ana_deb = 0.0 + self.sum_ana_cred = 0.0 + self.localcontext.update( { + 'time': time, + 'lines_p': self._lines_p, + 'general_debit': self._gen_deb, + 'general_credit': self._gen_cred, + 'analytic_debit': self._ana_deb, + 'analytic_credit': self._ana_cred, + 'delta_debit': self._delta_deb, + 'delta_credit': self._delta_cred, + }) - def _lines_p(self, date1, date2): - res = [] - acc_obj = self.pool.get('account.account') - for a in acc_obj.read(self.cr, self.uid, self.ids, ['name', 'code', 'sign']): - self.cr.execute("SELECT sum(debit), sum(credit) \ - FROM account_move_line \ - WHERE date>=%s AND date<=%s AND state<>'draft' AND account_id = %d", (date1, date2, a['id'])) - (gd, gc) = self.cr.fetchone() - gd = gd or 0.0 - gc = gc or 0.0 + def _lines_p(self, date1, date2): + res = [] + acc_obj = self.pool.get('account.account') + for a in acc_obj.read(self.cr, self.uid, self.ids, ['name', 'code', 'sign']): + self.cr.execute("SELECT sum(debit), sum(credit) \ + FROM account_move_line \ + WHERE date>=%s AND date<=%s AND state<>'draft' AND account_id = %d", (date1, date2, a['id'])) + (gd, gc) = self.cr.fetchone() + gd = gd or 0.0 + gc = gc or 0.0 - self.cr.execute("SELECT abs(sum(amount)) AS balance \ - FROM account_analytic_line \ - WHERE date>=%s AND date<=%s AND amount*%d>0 AND general_account_id = %d", (date1, date2, a['sign'], a['id'])) - (ad,) = self.cr.fetchone() - ad = ad or 0.0 - self.cr.execute("SELECT abs(sum(amount)) AS balance \ - FROM account_analytic_line \ - WHERE date>=%s AND date<=%s AND amount*%d<0 AND general_account_id = %d", (date1, date2, a['sign'], a['id'])) - (ac,) = self.cr.fetchone() - ac = ac or 0.0 + self.cr.execute("SELECT abs(sum(amount)) AS balance \ + FROM account_analytic_line \ + WHERE date>=%s AND date<=%s AND amount*%d>0 AND general_account_id = %d", (date1, date2, a['sign'], a['id'])) + (ad,) = self.cr.fetchone() + ad = ad or 0.0 + self.cr.execute("SELECT abs(sum(amount)) AS balance \ + FROM account_analytic_line \ + WHERE date>=%s AND date<=%s AND amount*%d<0 AND general_account_id = %d", (date1, date2, a['sign'], a['id'])) + (ac,) = self.cr.fetchone() + ac = ac or 0.0 - res.append({'code': a['code'], 'name': a['name'], - 'gen_debit': gd, - 'gen_credit': gc, - 'ana_debit': ad, - 'ana_credit': ac, - 'delta_debit': gd - ad, - 'delta_credit': gc - ac,}) - self.sum_gen_deb += gd - self.sum_gen_cred += gc - self.sum_ana_deb += ad - self.sum_ana_cred += ac - return res + res.append({'code': a['code'], 'name': a['name'], + 'gen_debit': gd, + 'gen_credit': gc, + 'ana_debit': ad, + 'ana_credit': ac, + 'delta_debit': gd - ad, + 'delta_credit': gc - ac,}) + self.sum_gen_deb += gd + self.sum_gen_cred += gc + self.sum_ana_deb += ad + self.sum_ana_cred += ac + return res - def _gen_deb(self, date1, date2): - return self.sum_gen_deb + def _gen_deb(self, date1, date2): + return self.sum_gen_deb - def _gen_cred(self, date1, date2): - return self.sum_gen_cred + def _gen_cred(self, date1, date2): + return self.sum_gen_cred - def _ana_deb(self, date1, date2): - return self.sum_ana_deb + def _ana_deb(self, date1, date2): + return self.sum_ana_deb - def _ana_cred(self, date1, date2): - return self.sum_ana_cred + def _ana_cred(self, date1, date2): + return self.sum_ana_cred - def _delta_deb(self, date1, date2): - return (self._gen_deb(date1,date2)-self._ana_deb(date1,date2)) - - def _delta_cred(self, date1, date2): - return (self._gen_cred(date1,date2)-self._ana_cred(date1,date2)) + def _delta_deb(self, date1, date2): + return (self._gen_deb(date1,date2)-self._ana_deb(date1,date2)) + + def _delta_cred(self, date1, date2): + return (self._gen_cred(date1,date2)-self._ana_cred(date1,date2)) report_sxw.report_sxw('report.account.analytic.account.analytic.check', 'account.analytic.account', 'addons/account/project/report/analytic_check.rml',parser=account_analytic_analytic_check, header=False) diff --git a/addons/account/project/report/analytic_journal.py b/addons/account/project/report/analytic_journal.py index e11be742fad..2cab00c8fd2 100644 --- a/addons/account/project/report/analytic_journal.py +++ b/addons/account/project/report/analytic_journal.py @@ -34,35 +34,35 @@ from report import report_sxw # Use period and Journal for selection or resources # class account_analytic_journal(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(account_analytic_journal, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time': time, - 'lines': self._lines, - 'lines_a': self._lines_a, - 'sum_general': self._sum_general, - 'sum_analytic': self._sum_analytic, - }) + def __init__(self, cr, uid, name, context): + super(account_analytic_journal, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time': time, + 'lines': self._lines, + 'lines_a': self._lines_a, + 'sum_general': self._sum_general, + 'sum_analytic': self._sum_analytic, + }) - def _lines(self, journal_id, date1, date2): - self.cr.execute('SELECT DISTINCT move_id FROM account_analytic_line WHERE (date>=%s) AND (date<=%s) AND (journal_id=%d) AND (move_id is not null)', (date1, date2, journal_id,)) - ids = map(lambda x: x[0], self.cr.fetchall()) - return self.pool.get('account.move.line').browse(self.cr, self.uid, ids) + def _lines(self, journal_id, date1, date2): + self.cr.execute('SELECT DISTINCT move_id FROM account_analytic_line WHERE (date>=%s) AND (date<=%s) AND (journal_id=%d) AND (move_id is not null)', (date1, date2, journal_id,)) + ids = map(lambda x: x[0], self.cr.fetchall()) + return self.pool.get('account.move.line').browse(self.cr, self.uid, ids) - def _lines_a(self, move_id, journal_id, date1, date2): - ids = self.pool.get('account.analytic.line').search(self.cr, self.uid, [('move_id','=',move_id), ('journal_id','=',journal_id), ('date','>=',date1), ('date','<=',date2)]) - if not ids: - return [] - return self.pool.get('account.analytic.line').browse(self.cr, self.uid, ids) - - def _sum_general(self, journal_id, date1, date2): - self.cr.execute('SELECT SUM(debit-credit) FROM account_move_line WHERE id IN (SELECT move_id FROM account_analytic_line WHERE (date>=%s) AND (date<=%s) AND (journal_id=%d) AND (move_id is not null))', (date1, date2, journal_id,)) - return self.cr.fetchall()[0][0] or 0 + def _lines_a(self, move_id, journal_id, date1, date2): + ids = self.pool.get('account.analytic.line').search(self.cr, self.uid, [('move_id','=',move_id), ('journal_id','=',journal_id), ('date','>=',date1), ('date','<=',date2)]) + if not ids: + return [] + return self.pool.get('account.analytic.line').browse(self.cr, self.uid, ids) + + def _sum_general(self, journal_id, date1, date2): + self.cr.execute('SELECT SUM(debit-credit) FROM account_move_line WHERE id IN (SELECT move_id FROM account_analytic_line WHERE (date>=%s) AND (date<=%s) AND (journal_id=%d) AND (move_id is not null))', (date1, date2, journal_id,)) + return self.cr.fetchall()[0][0] or 0 - def _sum_analytic(self, journal_id, date1, date2): - self.cr.execute("SELECT SUM(amount) FROM account_analytic_line WHERE date>=%s AND date<=%s AND journal_id=%d", (date1, date2, journal_id)) - res = self.cr.dictfetchone() - return res['sum'] or 0 + def _sum_analytic(self, journal_id, date1, date2): + self.cr.execute("SELECT SUM(amount) FROM account_analytic_line WHERE date>=%s AND date<=%s AND journal_id=%d", (date1, date2, journal_id)) + res = self.cr.dictfetchone() + return res['sum'] or 0 report_sxw.report_sxw('report.account.analytic.journal', 'account.analytic.journal', 'addons/account/project/report/analytic_journal.rml',parser=account_analytic_journal) diff --git a/addons/account/project/report/cost_ledger.py b/addons/account/project/report/cost_ledger.py index fd5208fef01..fca21404b76 100644 --- a/addons/account/project/report/cost_ledger.py +++ b/addons/account/project/report/cost_ledger.py @@ -32,90 +32,90 @@ import time from report import report_sxw class account_analytic_cost_ledger(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(account_analytic_cost_ledger, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time': time, - 'lines_g': self._lines_g, - 'lines_a': self._lines_a, - 'account_sum_debit': self._account_sum_debit, - 'account_sum_credit': self._account_sum_credit, - 'account_sum_balance': self._account_sum_balance, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit, - 'sum_balance': self._sum_balance, - }) + def __init__(self, cr, uid, name, context): + super(account_analytic_cost_ledger, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time': time, + 'lines_g': self._lines_g, + 'lines_a': self._lines_a, + 'account_sum_debit': self._account_sum_debit, + 'account_sum_credit': self._account_sum_credit, + 'account_sum_balance': self._account_sum_balance, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit, + 'sum_balance': self._sum_balance, + }) - def _lines_g(self, account_id, date1, date2): - self.cr.execute("SELECT sum(aal.amount) AS balance, aa.code AS code, aa.name AS name, aa.id AS id \ - FROM account_account AS aa, account_analytic_line AS aal \ - WHERE (aal.account_id=%d) AND (aal.date>=%s) AND (aal.date<=%s) AND (aal.general_account_id=aa.id) AND aa.active \ - GROUP BY aa.code, aa.name, aa.id ORDER BY aa.code", (account_id, date1, date2)) - res = self.cr.dictfetchall() + def _lines_g(self, account_id, date1, date2): + self.cr.execute("SELECT sum(aal.amount) AS balance, aa.code AS code, aa.name AS name, aa.id AS id \ + FROM account_account AS aa, account_analytic_line AS aal \ + WHERE (aal.account_id=%d) AND (aal.date>=%s) AND (aal.date<=%s) AND (aal.general_account_id=aa.id) AND aa.active \ + GROUP BY aa.code, aa.name, aa.id ORDER BY aa.code", (account_id, date1, date2)) + res = self.cr.dictfetchall() - for r in res: - if r['balance'] > 0: - r['debit'] = r['balance'] - r['credit'] = 0.0 - elif r['balance'] < 0: - r['debit'] = 0.0 - r['credit'] = -r['balance'] - else: - r['debit'] = 0.0 - r['credit'] = 0.0 - return res + for r in res: + if r['balance'] > 0: + r['debit'] = r['balance'] + r['credit'] = 0.0 + elif r['balance'] < 0: + r['debit'] = 0.0 + r['credit'] = -r['balance'] + else: + r['debit'] = 0.0 + r['credit'] = 0.0 + return res - def _lines_a(self, general_account_id, account_id, date1, date2): - self.cr.execute("SELECT aal.name AS name, aal.code AS code, aal.amount AS balance, aal.date AS date, aaj.code AS cj FROM account_analytic_line AS aal, account_analytic_journal AS aaj \ - WHERE (aal.general_account_id=%d) AND (aal.account_id=%d) AND (aal.date>=%s) AND (aal.date<=%s) \ - AND (aal.journal_id=aaj.id) \ - ORDER BY aal.date, aaj.code, aal.code", (general_account_id, account_id, date1, date2)) - res = self.cr.dictfetchall() + def _lines_a(self, general_account_id, account_id, date1, date2): + self.cr.execute("SELECT aal.name AS name, aal.code AS code, aal.amount AS balance, aal.date AS date, aaj.code AS cj FROM account_analytic_line AS aal, account_analytic_journal AS aaj \ + WHERE (aal.general_account_id=%d) AND (aal.account_id=%d) AND (aal.date>=%s) AND (aal.date<=%s) \ + AND (aal.journal_id=aaj.id) \ + ORDER BY aal.date, aaj.code, aal.code", (general_account_id, account_id, date1, date2)) + res = self.cr.dictfetchall() - for r in res: - if r['balance'] > 0: - r['debit'] = r['balance'] - r['credit'] = 0.0 - elif r['balance'] < 0: - r['debit'] = 0.0 - r['credit'] = -r['balance'] - else: - r['debit'] = 0.0 - r['credit'] = 0.0 - return res + for r in res: + if r['balance'] > 0: + r['debit'] = r['balance'] + r['credit'] = 0.0 + elif r['balance'] < 0: + r['debit'] = 0.0 + r['credit'] = -r['balance'] + else: + r['debit'] = 0.0 + r['credit'] = 0.0 + return res - def _account_sum_debit(self, account_id, date1, date2): - self.cr.execute("SELECT sum(amount) FROM account_analytic_line WHERE account_id=%d AND date>=%s AND date<=%s AND amount>0", (account_id, date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _account_sum_debit(self, account_id, date1, date2): + self.cr.execute("SELECT sum(amount) FROM account_analytic_line WHERE account_id=%d AND date>=%s AND date<=%s AND amount>0", (account_id, date1, date2)) + return self.cr.fetchone()[0] or 0.0 - def _account_sum_credit(self, account_id, date1, date2): - self.cr.execute("SELECT -sum(amount) FROM account_analytic_line WHERE account_id=%d AND date>=%s AND date<=%s AND amount<0", (account_id, date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _account_sum_credit(self, account_id, date1, date2): + self.cr.execute("SELECT -sum(amount) FROM account_analytic_line WHERE account_id=%d AND date>=%s AND date<=%s AND amount<0", (account_id, date1, date2)) + return self.cr.fetchone()[0] or 0.0 - def _account_sum_balance(self, account_id, date1, date2): - debit = self._account_sum_debit(account_id, date1, date2) - credit = self._account_sum_credit(account_id, date1, date2) - return (debit-credit) + def _account_sum_balance(self, account_id, date1, date2): + debit = self._account_sum_debit(account_id, date1, date2) + credit = self._account_sum_credit(account_id, date1, date2) + return (debit-credit) - def _sum_debit(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - if not len(ids): - return 0.0 - self.cr.execute("SELECT sum(amount) FROM account_analytic_line WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s AND amount>0", (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _sum_debit(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + if not len(ids): + return 0.0 + self.cr.execute("SELECT sum(amount) FROM account_analytic_line WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s AND amount>0", (date1, date2)) + return self.cr.fetchone()[0] or 0.0 - def _sum_credit(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - if not len(ids): - return 0.0 - ids = map(lambda x: x.id, accounts) - self.cr.execute("SELECT -sum(amount) FROM account_analytic_line WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s AND amount<0", (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _sum_credit(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + if not len(ids): + return 0.0 + ids = map(lambda x: x.id, accounts) + self.cr.execute("SELECT -sum(amount) FROM account_analytic_line WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s AND amount<0", (date1, date2)) + return self.cr.fetchone()[0] or 0.0 - def _sum_balance(self, accounts, date1, date2): - debit = self._sum_debit(accounts, date1, date2) or 0.0 - credit = self._sum_credit(accounts, date1, date2) or 0.0 - return (debit-credit) + def _sum_balance(self, accounts, date1, date2): + debit = self._sum_debit(accounts, date1, date2) or 0.0 + credit = self._sum_credit(accounts, date1, date2) or 0.0 + return (debit-credit) report_sxw.report_sxw('report.account.analytic.account.cost_ledger', 'account.analytic.account', 'addons/account/project/report/cost_ledger.rml',parser=account_analytic_cost_ledger, header=False) diff --git a/addons/account/project/report/inverted_analytic_balance.py b/addons/account/project/report/inverted_analytic_balance.py index 32613fac807..90b38294ee6 100644 --- a/addons/account/project/report/inverted_analytic_balance.py +++ b/addons/account/project/report/inverted_analytic_balance.py @@ -32,89 +32,89 @@ import time from report import report_sxw class account_inverted_analytic_balance(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(account_inverted_analytic_balance, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time': time, - 'lines_g': self._lines_g, - 'lines_a': self._lines_a, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit, - 'sum_balance': self._sum_balance, - 'sum_quantity': self._sum_quantity, - }) + def __init__(self, cr, uid, name, context): + super(account_inverted_analytic_balance, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time': time, + 'lines_g': self._lines_g, + 'lines_a': self._lines_a, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit, + 'sum_balance': self._sum_balance, + 'sum_quantity': self._sum_quantity, + }) - def _lines_g(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - self.cr.execute("SELECT aa.name AS name, aa.code AS code, sum(aal.amount) AS balance, sum(aal.unit_amount) AS quantity, aa.id AS id \ - FROM account_analytic_line AS aal, account_account AS aa \ - WHERE (aal.general_account_id=aa.id) AND (aal.account_id IN ("+','.join(map(str, ids))+")) AND (date>=%s) AND (date<=%s) AND aa.active \ - GROUP BY aal.general_account_id, aa.name, aa.code, aal.code, aa.id ORDER BY aal.code", (date1, date2)) - res = self.cr.dictfetchall() + def _lines_g(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + self.cr.execute("SELECT aa.name AS name, aa.code AS code, sum(aal.amount) AS balance, sum(aal.unit_amount) AS quantity, aa.id AS id \ + FROM account_analytic_line AS aal, account_account AS aa \ + WHERE (aal.general_account_id=aa.id) AND (aal.account_id IN ("+','.join(map(str, ids))+")) AND (date>=%s) AND (date<=%s) AND aa.active \ + GROUP BY aal.general_account_id, aa.name, aa.code, aal.code, aa.id ORDER BY aal.code", (date1, date2)) + res = self.cr.dictfetchall() - for r in res: - if r['balance'] > 0: - r['debit'] = r['balance'] - r['credit'] = 0.0 - elif r['balance'] < 0: - r['debit'] = 0.0 - r['credit'] = -r['balance'] - else: - r['debit'] = 0.0 - r['credit'] = 0.0 - return res + for r in res: + if r['balance'] > 0: + r['debit'] = r['balance'] + r['credit'] = 0.0 + elif r['balance'] < 0: + r['debit'] = 0.0 + r['credit'] = -r['balance'] + else: + r['debit'] = 0.0 + r['credit'] = 0.0 + return res - def _lines_a(self, accounts, general_account_id, date1, date2): - ids = map(lambda x: x.id, accounts) - self.cr.execute("SELECT sum(aal.amount) AS balance, sum(aal.unit_amount) AS quantity, aaa.code AS code, aaa.name AS name, account_id \ - FROM account_analytic_line AS aal, account_analytic_account AS aaa \ - WHERE aal.account_id=aaa.id AND aal.account_id IN ("+','.join(map(str, ids))+") AND aal.general_account_id=%d AND aal.date>=%s AND aal.date<=%s \ - GROUP BY aal.account_id, general_account_id, aaa.code, aaa.name ORDER BY aal.account_id", (general_account_id, date1, date2)) - res = self.cr.dictfetchall() + def _lines_a(self, accounts, general_account_id, date1, date2): + ids = map(lambda x: x.id, accounts) + self.cr.execute("SELECT sum(aal.amount) AS balance, sum(aal.unit_amount) AS quantity, aaa.code AS code, aaa.name AS name, account_id \ + FROM account_analytic_line AS aal, account_analytic_account AS aaa \ + WHERE aal.account_id=aaa.id AND aal.account_id IN ("+','.join(map(str, ids))+") AND aal.general_account_id=%d AND aal.date>=%s AND aal.date<=%s \ + GROUP BY aal.account_id, general_account_id, aaa.code, aaa.name ORDER BY aal.account_id", (general_account_id, date1, date2)) + res = self.cr.dictfetchall() - aaa_obj = self.pool.get('account.analytic.account') - res2 = aaa_obj.read(self.cr, self.uid, ids, ['complete_name']) - complete_name = {} - for r in res2: - complete_name[r['id']] = r['complete_name'] - for r in res: - r['complete_name'] = complete_name[r['account_id']] - if r['balance'] > 0: - r['debit'] = r['balance'] - r['credit'] = 0.0 - elif r['balance'] < 0: - r['debit'] = 0.0 - r['credit'] = -r['balance'] - else: - r['debit'] = 0.0 - r['credit'] = 0.0 - return res + aaa_obj = self.pool.get('account.analytic.account') + res2 = aaa_obj.read(self.cr, self.uid, ids, ['complete_name']) + complete_name = {} + for r in res2: + complete_name[r['id']] = r['complete_name'] + for r in res: + r['complete_name'] = complete_name[r['account_id']] + if r['balance'] > 0: + r['debit'] = r['balance'] + r['credit'] = 0.0 + elif r['balance'] < 0: + r['debit'] = 0.0 + r['credit'] = -r['balance'] + else: + r['debit'] = 0.0 + r['credit'] = 0.0 + return res - def _sum_debit(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - self.cr.execute("SELECT sum(amount) \ - FROM account_analytic_line \ - WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s AND amount>0", (date1, date2)) - return self.cr.fetchone()[0] or 0.0 - - def _sum_credit(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - self.cr.execute("SELECT -sum(amount) \ - FROM account_analytic_line \ - WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s AND amount<0", (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _sum_debit(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + self.cr.execute("SELECT sum(amount) \ + FROM account_analytic_line \ + WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s AND amount>0", (date1, date2)) + return self.cr.fetchone()[0] or 0.0 + + def _sum_credit(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + self.cr.execute("SELECT -sum(amount) \ + FROM account_analytic_line \ + WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s AND amount<0", (date1, date2)) + return self.cr.fetchone()[0] or 0.0 - def _sum_balance(self, accounts, date1, date2): - debit = self._sum_debit(accounts, date1, date2) - credit = self._sum_credit(accounts, date1, date2) - return (debit-credit) + def _sum_balance(self, accounts, date1, date2): + debit = self._sum_debit(accounts, date1, date2) + credit = self._sum_credit(accounts, date1, date2) + return (debit-credit) - def _sum_quantity(self, accounts, date1, date2): - ids = map(lambda x: x.id, accounts) - self.cr.execute("SELECT sum(unit_amount) \ - FROM account_analytic_line \ - WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s", (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _sum_quantity(self, accounts, date1, date2): + ids = map(lambda x: x.id, accounts) + self.cr.execute("SELECT sum(unit_amount) \ + FROM account_analytic_line \ + WHERE account_id IN ("+','.join(map(str, ids))+") AND date>=%s AND date<=%s", (date1, date2)) + return self.cr.fetchone()[0] or 0.0 report_sxw.report_sxw('report.account.analytic.account.inverted.balance', 'account.analytic.account', 'addons/account/project/report/inverted_analytic_balance.rml',parser=account_inverted_analytic_balance, header=False) diff --git a/addons/account/project/report/quantity_cost_ledger.py b/addons/account/project/report/quantity_cost_ledger.py index 9b5cfaf61fa..bb870a40c82 100644 --- a/addons/account/project/report/quantity_cost_ledger.py +++ b/addons/account/project/report/quantity_cost_ledger.py @@ -32,109 +32,109 @@ import time from report import report_sxw class account_analytic_quantity_cost_ledger(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(account_analytic_quantity_cost_ledger, self).__init__(cr, uid, - name, context) - self.localcontext.update( { - 'time': time, - 'lines_g': self._lines_g, - 'lines_a': self._lines_a, - 'sum_quantity': self._sum_quantity, - 'account_sum_quantity': self._account_sum_quantity, - }) + def __init__(self, cr, uid, name, context): + super(account_analytic_quantity_cost_ledger, self).__init__(cr, uid, + name, context) + self.localcontext.update( { + 'time': time, + 'lines_g': self._lines_g, + 'lines_a': self._lines_a, + 'sum_quantity': self._sum_quantity, + 'account_sum_quantity': self._account_sum_quantity, + }) - def _lines_g(self, account_id, date1, date2, journals): - if not journals or not journals[0][2]: - self.cr.execute("SELECT sum(aal.unit_amount) AS quantity, \ - aa.code AS code, aa.name AS name, aa.id AS id \ - FROM account_account AS aa, account_analytic_line AS aal \ - WHERE (aal.account_id=%d) AND (aal.date>=%s) \ - AND (aal.date<=%s) AND (aal.general_account_id=aa.id) \ - AND aa.active \ - GROUP BY aa.code, aa.name, aa.id ORDER BY aa.code", - (account_id, date1, date2)) - else: - journal_ids = journals[0][2] - self.cr.execute("SELECT sum(aal.unit_amount) AS quantity, \ - aa.code AS code, aa.name AS name, aa.id AS id \ - FROM account_account AS aa, account_analytic_line AS aal \ - WHERE (aal.account_id=%d) AND (aal.date>=%s) \ - AND (aal.date<=%s) AND (aal.general_account_id=aa.id) \ - AND aa.active \ - AND (aal.journal_id IN (" + - ','.join(map(str, journal_ids)) + ")) \ - GROUP BY aa.code, aa.name, aa.id ORDER BY aa.code", - (account_id, date1, date2)) - res = self.cr.dictfetchall() - return res + def _lines_g(self, account_id, date1, date2, journals): + if not journals or not journals[0][2]: + self.cr.execute("SELECT sum(aal.unit_amount) AS quantity, \ + aa.code AS code, aa.name AS name, aa.id AS id \ + FROM account_account AS aa, account_analytic_line AS aal \ + WHERE (aal.account_id=%d) AND (aal.date>=%s) \ + AND (aal.date<=%s) AND (aal.general_account_id=aa.id) \ + AND aa.active \ + GROUP BY aa.code, aa.name, aa.id ORDER BY aa.code", + (account_id, date1, date2)) + else: + journal_ids = journals[0][2] + self.cr.execute("SELECT sum(aal.unit_amount) AS quantity, \ + aa.code AS code, aa.name AS name, aa.id AS id \ + FROM account_account AS aa, account_analytic_line AS aal \ + WHERE (aal.account_id=%d) AND (aal.date>=%s) \ + AND (aal.date<=%s) AND (aal.general_account_id=aa.id) \ + AND aa.active \ + AND (aal.journal_id IN (" + + ','.join(map(str, journal_ids)) + ")) \ + GROUP BY aa.code, aa.name, aa.id ORDER BY aa.code", + (account_id, date1, date2)) + res = self.cr.dictfetchall() + return res - def _lines_a(self, general_account_id, account_id, date1, date2, journals): - if not journals or not journals[0][2]: - self.cr.execute("SELECT aal.name AS name, aal.code AS code, \ - aal.unit_amount AS quantity, aal.date AS date, \ - aaj.code AS cj \ - FROM account_analytic_line AS aal, \ - account_analytic_journal AS aaj \ - WHERE (aal.general_account_id=%d) AND (aal.account_id=%d) \ - AND (aal.date>=%s) AND (aal.date<=%s) \ - AND (aal.journal_id=aaj.id) \ - ORDER BY aal.date, aaj.code, aal.code", - (general_account_id, account_id, date1, date2)) - else: - journal_ids = journals[0][2] - self.cr.execute("SELECT aal.name AS name, aal.code AS code, \ - aal.unit_amount AS quantity, aal.date AS date, \ - aaj.code AS cj \ - FROM account_analytic_line AS aal, \ - account_analytic_journal AS aaj \ - WHERE (aal.general_account_id=%d) AND (aal.account_id=%d) \ - AND (aal.date>=%s) AND (aal.date<=%s) \ - AND (aal.journal_id=aaj.id) AND (aaj.id IN (" + - ','.join(map(str, journal_ids)) + ")) \ - ORDER BY aal.date, aaj.code, aal.code", - (general_account_id, account_id, date1, date2)) - res = self.cr.dictfetchall() - return res + def _lines_a(self, general_account_id, account_id, date1, date2, journals): + if not journals or not journals[0][2]: + self.cr.execute("SELECT aal.name AS name, aal.code AS code, \ + aal.unit_amount AS quantity, aal.date AS date, \ + aaj.code AS cj \ + FROM account_analytic_line AS aal, \ + account_analytic_journal AS aaj \ + WHERE (aal.general_account_id=%d) AND (aal.account_id=%d) \ + AND (aal.date>=%s) AND (aal.date<=%s) \ + AND (aal.journal_id=aaj.id) \ + ORDER BY aal.date, aaj.code, aal.code", + (general_account_id, account_id, date1, date2)) + else: + journal_ids = journals[0][2] + self.cr.execute("SELECT aal.name AS name, aal.code AS code, \ + aal.unit_amount AS quantity, aal.date AS date, \ + aaj.code AS cj \ + FROM account_analytic_line AS aal, \ + account_analytic_journal AS aaj \ + WHERE (aal.general_account_id=%d) AND (aal.account_id=%d) \ + AND (aal.date>=%s) AND (aal.date<=%s) \ + AND (aal.journal_id=aaj.id) AND (aaj.id IN (" + + ','.join(map(str, journal_ids)) + ")) \ + ORDER BY aal.date, aaj.code, aal.code", + (general_account_id, account_id, date1, date2)) + res = self.cr.dictfetchall() + return res - def _account_sum_quantity(self, account_id, date1, date2, journals): - if not journals or not journals[0][2]: - self.cr.execute("SELECT sum(unit_amount) \ - FROM account_analytic_line \ - WHERE account_id=%d AND date>=%s AND date<=%s", - (account_id, date1, date2)) - else: - journal_ids = journals[0][2] - self.cr.execute("SELECT sum(unit_amount) \ - FROM account_analytic_line \ - WHERE account_id = %d AND date >= %s AND date <= %s \ - AND journal_id IN (" + - ','.join(map(str, journal_ids)) + ")", - (account_id, date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _account_sum_quantity(self, account_id, date1, date2, journals): + if not journals or not journals[0][2]: + self.cr.execute("SELECT sum(unit_amount) \ + FROM account_analytic_line \ + WHERE account_id=%d AND date>=%s AND date<=%s", + (account_id, date1, date2)) + else: + journal_ids = journals[0][2] + self.cr.execute("SELECT sum(unit_amount) \ + FROM account_analytic_line \ + WHERE account_id = %d AND date >= %s AND date <= %s \ + AND journal_id IN (" + + ','.join(map(str, journal_ids)) + ")", + (account_id, date1, date2)) + return self.cr.fetchone()[0] or 0.0 - def _sum_quantity(self, accounts, date1, date2, journals): - ids = map(lambda x: x.id, accounts) - if not len(ids): - return 0.0 - if not journals or not journals[0][2]: - self.cr.execute("SELECT sum(unit_amount) \ - FROM account_analytic_line \ - WHERE account_id IN (" + - ','.join(map(str, ids)) + ") AND date>=%s AND date<=%s", - (date1, date2)) - else: - journal_ids = journals[0][2] - self.cr.execute("SELECT sum(unit_amount) \ - FROM account_analytic_line \ - WHERE account_id IN (" + - ','.join(map(str, ids)) + ") AND date >= %s AND date <= %s \ - AND journal_id IN (" + - ','.join(map(str, journal_ids)) + ")", - (date1, date2)) - return self.cr.fetchone()[0] or 0.0 + def _sum_quantity(self, accounts, date1, date2, journals): + ids = map(lambda x: x.id, accounts) + if not len(ids): + return 0.0 + if not journals or not journals[0][2]: + self.cr.execute("SELECT sum(unit_amount) \ + FROM account_analytic_line \ + WHERE account_id IN (" + + ','.join(map(str, ids)) + ") AND date>=%s AND date<=%s", + (date1, date2)) + else: + journal_ids = journals[0][2] + self.cr.execute("SELECT sum(unit_amount) \ + FROM account_analytic_line \ + WHERE account_id IN (" + + ','.join(map(str, ids)) + ") AND date >= %s AND date <= %s \ + AND journal_id IN (" + + ','.join(map(str, journal_ids)) + ")", + (date1, date2)) + return self.cr.fetchone()[0] or 0.0 report_sxw.report_sxw('report.account.analytic.account.quantity_cost_ledger', - 'account.analytic.account', - 'addons/account/project/report/quantity_cost_ledger.rml', - parser=account_analytic_quantity_cost_ledger, header=False) + 'account.analytic.account', + 'addons/account/project/report/quantity_cost_ledger.rml', + parser=account_analytic_quantity_cost_ledger, header=False) diff --git a/addons/account/project/wizard/wizard_account_analytic_analytic_check.py b/addons/account/project/wizard/wizard_account_analytic_analytic_check.py index a2537c8dd0d..43cfa6ad332 100644 --- a/addons/account/project/wizard/wizard_account_analytic_analytic_check.py +++ b/addons/account/project/wizard/wizard_account_analytic_analytic_check.py @@ -32,26 +32,26 @@ import wizard dates_form = '''
- - + + ''' dates_fields = { - 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, - 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, + 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, + 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, } class wizard_report(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.analytic.account.analytic.check', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.analytic.account.analytic.check', 'state':'end'} + } + } wizard_report('account.analytic.account.analytic.check.report') diff --git a/addons/account/project/wizard/wizard_account_analytic_balance_report.py b/addons/account/project/wizard/wizard_account_analytic_balance_report.py index 9c1439e63f9..dab606b3f4f 100644 --- a/addons/account/project/wizard/wizard_account_analytic_balance_report.py +++ b/addons/account/project/wizard/wizard_account_analytic_balance_report.py @@ -32,27 +32,27 @@ import wizard dates_form = '''
- - + + ''' dates_fields = { - 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, - 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, + 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, + 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, } class wizard_report(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.analytic.account.balance', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.analytic.account.balance', 'state':'end'} + } + } wizard_report('account.analytic.account.balance.report') diff --git a/addons/account/project/wizard/wizard_account_analytic_cost_ledger_for_journal_report.py b/addons/account/project/wizard/wizard_account_analytic_cost_ledger_for_journal_report.py index df4de9bc29e..7958209553c 100644 --- a/addons/account/project/wizard/wizard_account_analytic_cost_ledger_for_journal_report.py +++ b/addons/account/project/wizard/wizard_account_analytic_cost_ledger_for_journal_report.py @@ -32,42 +32,42 @@ import wizard _form = '''
- - - - - + + + + + ''' _fields = { - 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, - 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, - 'journal': {'string':'Journals','type':'many2many', 'relation':'account.analytic.journal'}, + 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, + 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, + 'journal': {'string':'Journals','type':'many2many', 'relation':'account.analytic.journal'}, } class wizard_report(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': { - 'type': 'form', - 'arch': _form, - 'fields': _fields, - 'state': [ - ('end','Cancel'), - ('report','Print') - ] - } - }, - 'report': { - 'actions': [], - 'result': { - 'type': 'print', - 'report': 'account.analytic.account.quantity_cost_ledger', - 'state': 'end' - } - }, - } + states = { + 'init': { + 'actions': [], + 'result': { + 'type': 'form', + 'arch': _form, + 'fields': _fields, + 'state': [ + ('end','Cancel'), + ('report','Print') + ] + } + }, + 'report': { + 'actions': [], + 'result': { + 'type': 'print', + 'report': 'account.analytic.account.quantity_cost_ledger', + 'state': 'end' + } + }, + } wizard_report('account.analytic.account.quantity_cost_ledger.report') diff --git a/addons/account/project/wizard/wizard_account_analytic_cost_ledger_report.py b/addons/account/project/wizard/wizard_account_analytic_cost_ledger_report.py index d72a088e88c..b07e11d5a8a 100644 --- a/addons/account/project/wizard/wizard_account_analytic_cost_ledger_report.py +++ b/addons/account/project/wizard/wizard_account_analytic_cost_ledger_report.py @@ -32,26 +32,26 @@ import wizard dates_form = '''
- - + + ''' dates_fields = { - 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, - 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, + 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, + 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, } class wizard_report(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.analytic.account.cost_ledger', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.analytic.account.cost_ledger', 'state':'end'} + } + } wizard_report('account.analytic.account.cost_ledger.report') diff --git a/addons/account/project/wizard/wizard_account_analytic_inverted_balance_report.py b/addons/account/project/wizard/wizard_account_analytic_inverted_balance_report.py index e5f00cb12f7..5213c91bc91 100644 --- a/addons/account/project/wizard/wizard_account_analytic_inverted_balance_report.py +++ b/addons/account/project/wizard/wizard_account_analytic_inverted_balance_report.py @@ -32,26 +32,26 @@ import wizard dates_form = '''
- - + + ''' dates_fields = { - 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, - 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, + 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, + 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, } class wizard_report(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.analytic.account.inverted.balance', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.analytic.account.inverted.balance', 'state':'end'} + } + } wizard_report('account.analytic.account.inverted.balance.report') diff --git a/addons/account/project/wizard/wizard_account_analytic_journal_report.py b/addons/account/project/wizard/wizard_account_analytic_journal_report.py index f70ebeef978..a57d9d0c95c 100644 --- a/addons/account/project/wizard/wizard_account_analytic_journal_report.py +++ b/addons/account/project/wizard/wizard_account_analytic_journal_report.py @@ -32,25 +32,25 @@ import wizard dates_form = '''
- - + + ''' dates_fields = { - 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, - 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, + 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, + 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, } class wizard_report(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.analytic.journal', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.analytic.journal', 'state':'end'} + } + } wizard_report('account.analytic.account.journal.report') diff --git a/addons/account/report/account_balance.py b/addons/account/report/account_balance.py index 5debaf7b751..4167cb09c69 100644 --- a/addons/account/report/account_balance.py +++ b/addons/account/report/account_balance.py @@ -31,93 +31,93 @@ import time from report import report_sxw class account_balance(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(account_balance, self).__init__(cr, uid, name, context) - self.sum_debit = 0.0 - self.sum_credit = 0.0 - self.localcontext.update({ - 'time': time, - 'lines': self.lines, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit, - 'get_fiscalyear':self.get_fiscalyear, - 'get_periods':self.get_periods, - }) - self.context = context - - def get_fiscalyear(self, form): - fisc_id = form['fiscalyear'] - if not(fisc_id): - return '' - self.cr.execute("select name from account_fiscalyear where id = %d" %(int(fisc_id))) - res=self.cr.fetchone() - return res and res[0] or '' + def __init__(self, cr, uid, name, context): + super(account_balance, self).__init__(cr, uid, name, context) + self.sum_debit = 0.0 + self.sum_credit = 0.0 + self.localcontext.update({ + 'time': time, + 'lines': self.lines, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit, + 'get_fiscalyear':self.get_fiscalyear, + 'get_periods':self.get_periods, + }) + self.context = context + + def get_fiscalyear(self, form): + fisc_id = form['fiscalyear'] + if not(fisc_id): + return '' + self.cr.execute("select name from account_fiscalyear where id = %d" %(int(fisc_id))) + res=self.cr.fetchone() + return res and res[0] or '' - def get_periods(self, form): - period_ids = ",".join([str(x) for x in form['periods'][0][2] if x]) - self.cr.execute("select name from account_period where id in (%s)" % (period_ids)) - res=self.cr.fetchall() - result='' - for r in res: - result+=r[0]+"," - return str(result and result[:-1]) or '' + def get_periods(self, form): + period_ids = ",".join([str(x) for x in form['periods'][0][2] if x]) + self.cr.execute("select name from account_period where id in (%s)" % (period_ids)) + res=self.cr.fetchall() + result='' + for r in res: + result+=r[0]+"," + return str(result and result[:-1]) or '' - def lines(self, form, ids={}, done=None, level=1): - if not ids: - ids = self.ids - if not ids: - return [] - if not done: - done={} - result = [] - ctx = self.context.copy() - ctx['fiscalyear'] = form['fiscalyear'] - ctx['periods'] = form['periods'][0][2] - ctx['target_move'] = form['target_move'] - accounts = self.pool.get('account.account').browse(self.cr, self.uid, ids, ctx) - def cmp_code(x, y): - return cmp(x.code, y.code) - accounts.sort(cmp_code) - for account in accounts: - if account.id in done: - continue - done[account.id] = 1 - res = { - 'code': account.code, - 'name': account.name, - 'level': level, - 'debit': account.debit, - 'credit': account.credit, - 'balance': account.balance, - 'leef': not bool(account.child_id) - } - self.sum_debit += account.debit - self.sum_credit += account.credit - if not (res['credit'] or res['debit']) and not account.child_id: - continue - if account.child_id: - def _check_rec(account): - if not account.child_id: - return bool(account.credit or account.debit) - for c in account.child_id: - if _check_rec(c): - return True - return False - if not _check_rec(account): - continue + def lines(self, form, ids={}, done=None, level=1): + if not ids: + ids = self.ids + if not ids: + return [] + if not done: + done={} + result = [] + ctx = self.context.copy() + ctx['fiscalyear'] = form['fiscalyear'] + ctx['periods'] = form['periods'][0][2] + ctx['target_move'] = form['target_move'] + accounts = self.pool.get('account.account').browse(self.cr, self.uid, ids, ctx) + def cmp_code(x, y): + return cmp(x.code, y.code) + accounts.sort(cmp_code) + for account in accounts: + if account.id in done: + continue + done[account.id] = 1 + res = { + 'code': account.code, + 'name': account.name, + 'level': level, + 'debit': account.debit, + 'credit': account.credit, + 'balance': account.balance, + 'leef': not bool(account.child_id) + } + self.sum_debit += account.debit + self.sum_credit += account.credit + if not (res['credit'] or res['debit']) and not account.child_id: + continue + if account.child_id: + def _check_rec(account): + if not account.child_id: + return bool(account.credit or account.debit) + for c in account.child_id: + if _check_rec(c): + return True + return False + if not _check_rec(account): + continue - result.append(res) - if account.child_id: - ids2 = [(x.code,x.id) for x in account.child_id] - ids2.sort() - result += self.lines(form, [x[1] for x in ids2], done, level+1) - return result + result.append(res) + if account.child_id: + ids2 = [(x.code,x.id) for x in account.child_id] + ids2.sort() + result += self.lines(form, [x[1] for x in ids2], done, level+1) + return result - def _sum_credit(self): - return self.sum_credit + def _sum_credit(self): + return self.sum_credit - def _sum_debit(self): - return self.sum_debit + def _sum_debit(self): + return self.sum_debit report_sxw.report_sxw('report.account.account.balance', 'account.account', 'addons/account/report/account_balance.rml', parser=account_balance, header=2) diff --git a/addons/account/report/account_journal.py b/addons/account/report/account_journal.py index 74e28d698f6..87a6e43ebcf 100644 --- a/addons/account/report/account_journal.py +++ b/addons/account/report/account_journal.py @@ -35,28 +35,28 @@ from report import report_sxw # Use period and Journal for selection or resources # class journal_print(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(journal_print, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time': time, - 'lines': self.lines, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit - }) + def __init__(self, cr, uid, name, context): + super(journal_print, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time': time, + 'lines': self.lines, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit + }) - def lines(self, period_id, journal_id, *args): - self.cr.execute('update account_journal_period set state=%s where journal_id=%d and period_id=%d and state=%s', ('printed',journal_id,period_id,'draft')) - self.cr.commit() - self.cr.execute('select id from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\' order by date,id', (period_id, journal_id)) - ids = map(lambda x: x[0], self.cr.fetchall()) - return self.pool.get('account.move.line').browse(self.cr, self.uid, ids) + def lines(self, period_id, journal_id, *args): + self.cr.execute('update account_journal_period set state=%s where journal_id=%d and period_id=%d and state=%s', ('printed',journal_id,period_id,'draft')) + self.cr.commit() + self.cr.execute('select id from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\' order by date,id', (period_id, journal_id)) + ids = map(lambda x: x[0], self.cr.fetchall()) + return self.pool.get('account.move.line').browse(self.cr, self.uid, ids) - def _sum_debit(self, period_id, journal_id): - self.cr.execute('select sum(debit) from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\'', (period_id, journal_id)) - return self.cr.fetchone()[0] or 0.0 + def _sum_debit(self, period_id, journal_id): + self.cr.execute('select sum(debit) from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\'', (period_id, journal_id)) + return self.cr.fetchone()[0] or 0.0 - def _sum_credit(self, period_id, journal_id): - self.cr.execute('select sum(credit) from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\'', (period_id, journal_id)) - return self.cr.fetchone()[0] or 0.0 + def _sum_credit(self, period_id, journal_id): + self.cr.execute('select sum(credit) from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\'', (period_id, journal_id)) + return self.cr.fetchone()[0] or 0.0 report_sxw.report_sxw('report.account.journal.period.print', 'account.journal.period', 'addons/account/report/account_journal.rml', parser=journal_print) diff --git a/addons/account/report/aged_trial_balance.py b/addons/account/report/aged_trial_balance.py index f5737a673d9..7c4710c9710 100644 --- a/addons/account/report/aged_trial_balance.py +++ b/addons/account/report/aged_trial_balance.py @@ -32,160 +32,160 @@ import pooler from report import report_sxw class aged_trial_report(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(aged_trial_report, self).__init__(cr, uid, name, context) - self.localcontext.update({ - 'time': time, - 'get_lines': self._get_lines, - 'get_total': self._get_total, - 'get_before': self._get_before, - 'get_for_period': self._get_for_period, - 'get_company': self._get_company, - 'get_currency': self._get_currency, - }) + def __init__(self, cr, uid, name, context): + super(aged_trial_report, self).__init__(cr, uid, name, context) + self.localcontext.update({ + 'time': time, + 'get_lines': self._get_lines, + 'get_total': self._get_total, + 'get_before': self._get_before, + 'get_for_period': self._get_for_period, + 'get_company': self._get_company, + 'get_currency': self._get_currency, + }) - def _add_header(self, node): - return True + def _add_header(self, node): + return True - def _get_lines(self, form): - self.form=form - res = [] - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', - context={'fiscalyear': form['fiscalyear']}) - self.cr.execute("SELECT DISTINCT res_partner.id AS id, " \ - "res_partner.name AS name, res_partner.ref AS code " \ - "FROM res_partner, account_move_line AS line, account_account " \ - "WHERE (line.account_id=account_account.id) " \ - "AND (line.reconcile_id IS NULL) " \ - "AND (line.partner_id=res_partner.id) " \ - "AND " + line_query + " " \ - "AND (account_account.company_id = %d) " \ - "AND account_account.active " \ - "ORDER BY res_partner.name", (form['company_id'],)) - partners = self.cr.dictfetchall() - for partner in partners: - values = {} - self.cr.execute("SELECT SUM(debit-credit) " \ - "FROM account_move_line AS line, account_account " \ - "WHERE (line.account_id=account_account.id) " \ - "AND (account_account.type IN (" + form['computation'] +")) " \ - "AND (date < %s) AND (partner_id=%d) " \ - "AND (reconcile_id IS NULL) " \ - "AND " + line_query + " " \ - "AND (account_account.company_id = %d) " \ - "AND account_account.active", - (form['0']['start'], partner['id'], form['company_id'])) - before = self.cr.fetchone() - values['before'] = before and before[0] or "" - for i in range(5): - self.cr.execute("SELECT SUM(debit-credit) " \ - "FROM account_move_line AS line, account_account " \ - "WHERE (line.account_id=account_account.id) " \ - "AND (account_account.type IN (" + form['computation'] + ")) " \ - "AND (date >= %s) AND (date <= %s) " \ - "AND (partner_id = %d) " \ - "AND (reconcile_id IS NULL) " \ - "AND " + line_query + " " \ - "AND (account_account.company_id = %d) " \ - "AND account_account.active", - (form[str(i)]['start'], form[str(i)]['stop'], - partner['id'], form['company_id'])) - during = self.cr.fetchone() - values[str(i)] = during and during[0] or "" + def _get_lines(self, form): + self.form=form + res = [] + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', + context={'fiscalyear': form['fiscalyear']}) + self.cr.execute("SELECT DISTINCT res_partner.id AS id, " \ + "res_partner.name AS name, res_partner.ref AS code " \ + "FROM res_partner, account_move_line AS line, account_account " \ + "WHERE (line.account_id=account_account.id) " \ + "AND (line.reconcile_id IS NULL) " \ + "AND (line.partner_id=res_partner.id) " \ + "AND " + line_query + " " \ + "AND (account_account.company_id = %d) " \ + "AND account_account.active " \ + "ORDER BY res_partner.name", (form['company_id'],)) + partners = self.cr.dictfetchall() + for partner in partners: + values = {} + self.cr.execute("SELECT SUM(debit-credit) " \ + "FROM account_move_line AS line, account_account " \ + "WHERE (line.account_id=account_account.id) " \ + "AND (account_account.type IN (" + form['computation'] +")) " \ + "AND (date < %s) AND (partner_id=%d) " \ + "AND (reconcile_id IS NULL) " \ + "AND " + line_query + " " \ + "AND (account_account.company_id = %d) " \ + "AND account_account.active", + (form['0']['start'], partner['id'], form['company_id'])) + before = self.cr.fetchone() + values['before'] = before and before[0] or "" + for i in range(5): + self.cr.execute("SELECT SUM(debit-credit) " \ + "FROM account_move_line AS line, account_account " \ + "WHERE (line.account_id=account_account.id) " \ + "AND (account_account.type IN (" + form['computation'] + ")) " \ + "AND (date >= %s) AND (date <= %s) " \ + "AND (partner_id = %d) " \ + "AND (reconcile_id IS NULL) " \ + "AND " + line_query + " " \ + "AND (account_account.company_id = %d) " \ + "AND account_account.active", + (form[str(i)]['start'], form[str(i)]['stop'], + partner['id'], form['company_id'])) + during = self.cr.fetchone() + values[str(i)] = during and during[0] or "" - self.cr.execute("SELECT SUM(debit-credit) " \ - "FROM account_move_line AS line, account_account " \ - "WHERE (line.account_id = account_account.id) " \ - "AND (account_account.type IN (" + form['computation'] + ")) " \ - "AND (partner_id = %d) " \ - "AND (reconcile_id IS NULL) " \ - "AND " + line_query + " " \ - "AND (account_account.company_id = %d) " \ - "AND account_account.active", - (partner['id'], form['company_id'])) - total = self.cr.fetchone() - values['total'] = total and total[0] or 0.0 - values['name'] = partner['name'] - values['ref'] = partner['code'] - t = 0.0 - for i in range(5)+['before']: - t+= float(values.get(str(i), 0.0) or 0.0) - if values['total']: - res.append(values) - total = 0.0 - totals = {} - for r in res: - total += float(r['total'] or 0.0) - for i in range(5)+['before']: - totals.setdefault(str(i), 0.0) - totals[str(i)] += float(r[str(i)] or 0.0) - if form['sorting_on']=='amount': - res.sort(lambda x,y:cmp(y['total'],x['total'])) - return res + self.cr.execute("SELECT SUM(debit-credit) " \ + "FROM account_move_line AS line, account_account " \ + "WHERE (line.account_id = account_account.id) " \ + "AND (account_account.type IN (" + form['computation'] + ")) " \ + "AND (partner_id = %d) " \ + "AND (reconcile_id IS NULL) " \ + "AND " + line_query + " " \ + "AND (account_account.company_id = %d) " \ + "AND account_account.active", + (partner['id'], form['company_id'])) + total = self.cr.fetchone() + values['total'] = total and total[0] or 0.0 + values['name'] = partner['name'] + values['ref'] = partner['code'] + t = 0.0 + for i in range(5)+['before']: + t+= float(values.get(str(i), 0.0) or 0.0) + if values['total']: + res.append(values) + total = 0.0 + totals = {} + for r in res: + total += float(r['total'] or 0.0) + for i in range(5)+['before']: + totals.setdefault(str(i), 0.0) + totals[str(i)] += float(r[str(i)] or 0.0) + if form['sorting_on']=='amount': + res.sort(lambda x,y:cmp(y['total'],x['total'])) + return res - def _get_total(self, fiscalyear, company_id): - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', - context={'fiscalyear': fiscalyear}) - self.cr.execute("SELECT SUM(debit - credit) " \ - "FROM account_move_line AS line, account_account " \ - "WHERE (line.account_id = account_account.id) " \ - "AND (account_account.type IN (" + self.form['computation'] + ")) "\ - "AND reconcile_id IS NULL " \ - "AND partner_id is NOT NULL " \ - "AND " + line_query + " " \ - "AND (account_account.company_id = %d) " \ - "AND account_account.active", - (company_id,)) - total = self.cr.fetchone() - return total and total[0] or 0.0 + def _get_total(self, fiscalyear, company_id): + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', + context={'fiscalyear': fiscalyear}) + self.cr.execute("SELECT SUM(debit - credit) " \ + "FROM account_move_line AS line, account_account " \ + "WHERE (line.account_id = account_account.id) " \ + "AND (account_account.type IN (" + self.form['computation'] + ")) "\ + "AND reconcile_id IS NULL " \ + "AND partner_id is NOT NULL " \ + "AND " + line_query + " " \ + "AND (account_account.company_id = %d) " \ + "AND account_account.active", + (company_id,)) + total = self.cr.fetchone() + return total and total[0] or 0.0 - def _get_before(self, date, fiscalyear, company_id): - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', - context={'fiscalyear': fiscalyear}) - self.cr.execute("SELECT SUM(debit - credit) " \ - "FROM account_move_line AS line, account_account " \ - "WHERE (line.account_id = account_account.id) " \ - "AND (account_account.type IN (" + self.form['computation'] + ")) " \ - "AND reconcile_id IS NULL " \ - "AND (date < %s) " \ - "AND partner_id IS NOT NULL " \ - "AND " + line_query + " " \ - "AND (account_account.company_id = %d) " \ - "AND account_account.active", - (date, company_id)) - before = self.cr.fetchone() - return before and before[0] or 0.0 + def _get_before(self, date, fiscalyear, company_id): + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', + context={'fiscalyear': fiscalyear}) + self.cr.execute("SELECT SUM(debit - credit) " \ + "FROM account_move_line AS line, account_account " \ + "WHERE (line.account_id = account_account.id) " \ + "AND (account_account.type IN (" + self.form['computation'] + ")) " \ + "AND reconcile_id IS NULL " \ + "AND (date < %s) " \ + "AND partner_id IS NOT NULL " \ + "AND " + line_query + " " \ + "AND (account_account.company_id = %d) " \ + "AND account_account.active", + (date, company_id)) + before = self.cr.fetchone() + return before and before[0] or 0.0 - def _get_for_period(self, period, fiscalyear, company_id): - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', - context={'fiscalyear': fiscalyear}) - self.cr.execute("SELECT SUM(debit - credit) " \ - "FROM account_move_line AS line, account_account " \ - "WHERE (line.account_id = account_account.id) " \ - "AND (account_account.type IN (" + self.form['computation'] + ")) " \ - "AND reconcile_id IS NULL " \ - "AND (date >= %s) " \ - "AND (date <= %s) " \ - "AND partner_id IS NOT NULL " \ - "AND " + line_query + " " \ - "AND (account_account.company_id = %d) " \ - "AND account_account.active", - (period['start'], period['stop'], company_id)) - period = self.cr.fetchone() - return period and period[0] or 0.0 + def _get_for_period(self, period, fiscalyear, company_id): + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', + context={'fiscalyear': fiscalyear}) + self.cr.execute("SELECT SUM(debit - credit) " \ + "FROM account_move_line AS line, account_account " \ + "WHERE (line.account_id = account_account.id) " \ + "AND (account_account.type IN (" + self.form['computation'] + ")) " \ + "AND reconcile_id IS NULL " \ + "AND (date >= %s) " \ + "AND (date <= %s) " \ + "AND partner_id IS NOT NULL " \ + "AND " + line_query + " " \ + "AND (account_account.company_id = %d) " \ + "AND account_account.active", + (period['start'], period['stop'], company_id)) + period = self.cr.fetchone() + return period and period[0] or 0.0 - def _get_company(self, form): - return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).name + def _get_company(self, form): + return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).name - def _get_currency(self, form): - return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).currency_id.name + def _get_currency(self, form): + return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).currency_id.name report_sxw.report_sxw( - 'report.account.aged.trial.balance', - 'res.partner', - 'addons/account/report/aged_trial_balance.rml', - parser=aged_trial_report, header=False) + 'report.account.aged.trial.balance', + 'res.partner', + 'addons/account/report/aged_trial_balance.rml', + parser=aged_trial_report, header=False) diff --git a/addons/account/report/budget_report.py b/addons/account/report/budget_report.py index 699142455ac..e2a19276d02 100644 --- a/addons/account/report/budget_report.py +++ b/addons/account/report/budget_report.py @@ -33,42 +33,42 @@ import datetime import operator class budget_report(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(budget_report, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'lines': self.lines, - 'budget_total': self.budget_total, - 'post_total': self.post_total, - 'time': time, - }) + def __init__(self, cr, uid, name, context): + super(budget_report, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'lines': self.lines, + 'budget_total': self.budget_total, + 'post_total': self.post_total, + 'time': time, + }) - def post_total(self, post_obj, date1, date2): - def str2date(date_str): - return datetime.date.fromtimestamp(time.mktime(time.strptime(date_str, '%Y-%m-%d'))) - def interval(d1str, d2str): - return (str2date(d2str) - str2date(d1str) + datetime.timedelta(days=1)).days - prev = reduce(lambda x,d: x + d.amount, post_obj.dotation_ids, 0.0) - period_days = interval(date1, date2) - for d in post_obj.dotation_ids: - i = interval(d.period_id.date_start, d.period_id.date_stop) - total_days = reduce(lambda x,d: x+interval(d.period_id.date_start, d.period_id.date_stop), post_obj.dotation_ids, 0) - achievements = reduce(lambda x,l: x+l['achievements'], self.lines(post_obj, date1, date2), 0.0) - return [{'prev': prev, 'prev_period': prev * period_days / total_days, 'achievements': achievements}] + def post_total(self, post_obj, date1, date2): + def str2date(date_str): + return datetime.date.fromtimestamp(time.mktime(time.strptime(date_str, '%Y-%m-%d'))) + def interval(d1str, d2str): + return (str2date(d2str) - str2date(d1str) + datetime.timedelta(days=1)).days + prev = reduce(lambda x,d: x + d.amount, post_obj.dotation_ids, 0.0) + period_days = interval(date1, date2) + for d in post_obj.dotation_ids: + i = interval(d.period_id.date_start, d.period_id.date_stop) + total_days = reduce(lambda x,d: x+interval(d.period_id.date_start, d.period_id.date_stop), post_obj.dotation_ids, 0) + achievements = reduce(lambda x,l: x+l['achievements'], self.lines(post_obj, date1, date2), 0.0) + return [{'prev': prev, 'prev_period': prev * period_days / total_days, 'achievements': achievements}] - def budget_total(self, post_objs, date1, date2): - res = {'prev': 0.0, 'prev_period': 0.0, 'achievements': 0.0} - for post_obj in post_objs: - r = self.post_total(post_obj, date1, date2)[0] - for k in r: - res[k] += r[k] - return [res] - - def lines(self, post_obj, date1, date2): - res = [] - for a in post_obj.account_ids: - self.cr.execute("SELECT COALESCE(SUM(debit-credit), 0) FROM account_move_line WHERE account_id=%d AND date>=%s AND date<=%s and state<>'draft'", (a.id, date1, date2)) - achievements = float(self.cr.fetchone()[0]) * (post_obj.sens=='produit' and -1 or 1) - res.append({'name': a.name, 'code': a.code, 'achievements': achievements}) - return res + def budget_total(self, post_objs, date1, date2): + res = {'prev': 0.0, 'prev_period': 0.0, 'achievements': 0.0} + for post_obj in post_objs: + r = self.post_total(post_obj, date1, date2)[0] + for k in r: + res[k] += r[k] + return [res] + + def lines(self, post_obj, date1, date2): + res = [] + for a in post_obj.account_ids: + self.cr.execute("SELECT COALESCE(SUM(debit-credit), 0) FROM account_move_line WHERE account_id=%d AND date>=%s AND date<=%s and state<>'draft'", (a.id, date1, date2)) + achievements = float(self.cr.fetchone()[0]) * (post_obj.sens=='produit' and -1 or 1) + res.append({'name': a.name, 'code': a.code, 'achievements': achievements}) + return res report_sxw.report_sxw('report.account.budget', 'account.budget.post', 'addons/account/report/budget_report.rml',parser=budget_report) diff --git a/addons/account/report/central_journal.py b/addons/account/report/central_journal.py index 7a198b1c524..7cff84e6ef6 100644 --- a/addons/account/report/central_journal.py +++ b/addons/account/report/central_journal.py @@ -34,25 +34,25 @@ from report import report_sxw # Use period and Journal for selection or resources # class journal_print(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(journal_print, self).__init__(cr, uid, name, context) - self.localcontext.update({ - 'time': time, - 'lines': self.lines, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit - }) - - def lines(self, period_id, journal_id, *args): - self.cr.execute('select a.code, a.name, sum(debit) as debit, sum(credit) as credit from account_move_line l left join account_account a on (l.account_id=a.id) where l.period_id=%d and l.journal_id=%d and l.state<>\'draft\' group by a.id, a.code, a.name', (period_id, journal_id)) - return self.cr.dictfetchall() - - def _sum_debit(self, period_id, journal_id): - self.cr.execute('select sum(debit) from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\'', (period_id, journal_id)) - return self.cr.fetchone()[0] or 0.0 - - def _sum_credit(self, period_id, journal_id): - self.cr.execute('select sum(credit) from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\'', (period_id, journal_id)) - return self.cr.fetchone()[0] or 0.0 + def __init__(self, cr, uid, name, context): + super(journal_print, self).__init__(cr, uid, name, context) + self.localcontext.update({ + 'time': time, + 'lines': self.lines, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit + }) + + def lines(self, period_id, journal_id, *args): + self.cr.execute('select a.code, a.name, sum(debit) as debit, sum(credit) as credit from account_move_line l left join account_account a on (l.account_id=a.id) where l.period_id=%d and l.journal_id=%d and l.state<>\'draft\' group by a.id, a.code, a.name', (period_id, journal_id)) + return self.cr.dictfetchall() + + def _sum_debit(self, period_id, journal_id): + self.cr.execute('select sum(debit) from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\'', (period_id, journal_id)) + return self.cr.fetchone()[0] or 0.0 + + def _sum_credit(self, period_id, journal_id): + self.cr.execute('select sum(credit) from account_move_line where period_id=%d and journal_id=%d and state<>\'draft\'', (period_id, journal_id)) + return self.cr.fetchone()[0] or 0.0 report_sxw.report_sxw('report.account.central.journal', 'account.journal.period', 'addons/account/report/central_journal.rml',parser=journal_print) diff --git a/addons/account/report/general_journal.py b/addons/account/report/general_journal.py index cc7b60d7b93..ef697496a39 100644 --- a/addons/account/report/general_journal.py +++ b/addons/account/report/general_journal.py @@ -35,65 +35,65 @@ from report import report_sxw # Use period and Journal for selection or resources # class journal_print(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(journal_print, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time': time, - 'lines': self.lines, - 'periods': self.periods, - 'sum_debit_period': self._sum_debit_period, - 'sum_credit_period': self._sum_credit_period, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit - }) + def __init__(self, cr, uid, name, context): + super(journal_print, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time': time, + 'lines': self.lines, + 'periods': self.periods, + 'sum_debit_period': self._sum_debit_period, + 'sum_credit_period': self._sum_credit_period, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit + }) - def preprocess(self, objects, datas, ids): - super(journal_print, self).preprocess(objects, datas, ids) - self.cr.execute('select period_id, journal_id from account_journal_period where id in (' + ','.join([str(id) for id in ids]) + ')') - res = self.cr.fetchall() - self.period_ids = ','.join([str(x[0]) for x in res]) - self.journal_ids = ','.join([str(x[1]) for x in res]) + def preprocess(self, objects, datas, ids): + super(journal_print, self).preprocess(objects, datas, ids) + self.cr.execute('select period_id, journal_id from account_journal_period where id in (' + ','.join([str(id) for id in ids]) + ')') + res = self.cr.fetchall() + self.period_ids = ','.join([str(x[0]) for x in res]) + self.journal_ids = ','.join([str(x[1]) for x in res]) - # returns a list of period objs - def periods(self, journal_period_objs): - dic = {} - def filter_unique(o): - key = o.period_id.id - res = key in dic - if not res: - dic[key] = True - return not res - filtered_objs = filter(filter_unique, journal_period_objs) - return map(lambda x: x.period_id, filtered_objs) - - def lines(self, period_id): - if not self.journal_ids: - return [] - self.cr.execute('select j.code, j.name, sum(l.debit) as debit, sum(l.credit) as credit from account_move_line l left join account_journal j on (l.journal_id=j.id) where period_id=%d and journal_id in (' + self.journal_ids + ') and l.state<>\'draft\' group by j.id, j.code, j.name', (period_id,)) - return self.cr.dictfetchall() - - def _sum_debit_period(self, period_id): - if not self.journal_ids: - return 0.0 - self.cr.execute('select sum(debit) from account_move_line where period_id=%d and journal_id in (' + self.journal_ids + ') and state<>\'draft\'', (period_id,)) - return self.cr.fetchone()[0] or 0.0 - - def _sum_credit_period(self, period_id): - if not self.journal_ids: - return 0.0 - self.cr.execute('select sum(credit) from account_move_line where period_id=%d and journal_id in (' + self.journal_ids + ') and state<>\'draft\'', (period_id,)) - return self.cr.fetchone()[0] or 0.0 - - def _sum_debit(self): - if not self.journal_ids or not self.period_ids: - return 0.0 - self.cr.execute('select sum(debit) from account_move_line where period_id in (' + self.period_ids + ') and journal_id in (' + self.journal_ids + ') and state<>\'draft\'') - return self.cr.fetchone()[0] or 0.0 - - def _sum_credit(self): - if not self.journal_ids or not self.period_ids: - return 0.0 - self.cr.execute('select sum(credit) from account_move_line where period_id in (' + self.period_ids + ') and journal_id in (' + self.journal_ids + ') and state<>\'draft\'') - return self.cr.fetchone()[0] or 0.0 + # returns a list of period objs + def periods(self, journal_period_objs): + dic = {} + def filter_unique(o): + key = o.period_id.id + res = key in dic + if not res: + dic[key] = True + return not res + filtered_objs = filter(filter_unique, journal_period_objs) + return map(lambda x: x.period_id, filtered_objs) + + def lines(self, period_id): + if not self.journal_ids: + return [] + self.cr.execute('select j.code, j.name, sum(l.debit) as debit, sum(l.credit) as credit from account_move_line l left join account_journal j on (l.journal_id=j.id) where period_id=%d and journal_id in (' + self.journal_ids + ') and l.state<>\'draft\' group by j.id, j.code, j.name', (period_id,)) + return self.cr.dictfetchall() + + def _sum_debit_period(self, period_id): + if not self.journal_ids: + return 0.0 + self.cr.execute('select sum(debit) from account_move_line where period_id=%d and journal_id in (' + self.journal_ids + ') and state<>\'draft\'', (period_id,)) + return self.cr.fetchone()[0] or 0.0 + + def _sum_credit_period(self, period_id): + if not self.journal_ids: + return 0.0 + self.cr.execute('select sum(credit) from account_move_line where period_id=%d and journal_id in (' + self.journal_ids + ') and state<>\'draft\'', (period_id,)) + return self.cr.fetchone()[0] or 0.0 + + def _sum_debit(self): + if not self.journal_ids or not self.period_ids: + return 0.0 + self.cr.execute('select sum(debit) from account_move_line where period_id in (' + self.period_ids + ') and journal_id in (' + self.journal_ids + ') and state<>\'draft\'') + return self.cr.fetchone()[0] or 0.0 + + def _sum_credit(self): + if not self.journal_ids or not self.period_ids: + return 0.0 + self.cr.execute('select sum(credit) from account_move_line where period_id in (' + self.period_ids + ') and journal_id in (' + self.journal_ids + ') and state<>\'draft\'') + return self.cr.fetchone()[0] or 0.0 report_sxw.report_sxw('report.account.general.journal', 'account.journal.period', 'addons/account/report/general_journal.rml',parser=journal_print) diff --git a/addons/account/report/general_ledger.py b/addons/account/report/general_ledger.py index 7360de69153..be005b64de7 100644 --- a/addons/account/report/general_ledger.py +++ b/addons/account/report/general_ledger.py @@ -32,139 +32,139 @@ from report import report_sxw import pooler class general_ledger(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(general_ledger, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time': time, - 'lines': self.lines, - 'sum_debit_account': self._sum_debit_account, - 'sum_credit_account': self._sum_credit_account, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit, + def __init__(self, cr, uid, name, context): + super(general_ledger, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time': time, + 'lines': self.lines, + 'sum_debit_account': self._sum_debit_account, + 'sum_credit_account': self._sum_credit_account, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit, - }) - self.context = context - self.tmp_list2=[] - self.final_list=[] + }) + self.context = context + self.tmp_list2=[] + self.final_list=[] - def recur(self,list1): - tmp_list3 =list1 - self.tmp_list2 =list1 -# print "self list",self.tmp_list2 - for i in range(0,len(list1)): - if list1[i] in self.final_list: - continue - self.final_list.append(list1[i]) -# print "finallly",self.final_list - if list1[i].child_id: + def recur(self,list1): + tmp_list3 =list1 + self.tmp_list2 =list1 +# print "self list",self.tmp_list2 + for i in range(0,len(list1)): + if list1[i] in self.final_list: + continue + self.final_list.append(list1[i]) +# print "finallly",self.final_list + if list1[i].child_id: - tmp_list4=(hasattr(list1[i],'child_id') and list(list1[i].child_id) or []) + tmp_list4=(hasattr(list1[i],'child_id') and list(list1[i].child_id) or []) - self.tmp_list2 +=tmp_list4 + self.tmp_list2 +=tmp_list4 - self.tmp_list2+=self.recur(tmp_list4) + self.tmp_list2+=self.recur(tmp_list4) - return self.final_list + return self.final_list - def repeatIn(self, lst, name,nodes_parent=False): + def repeatIn(self, lst, name,nodes_parent=False): - if name=='o': - list_final=[] - if not lst: - return super(general_ledger,self).repeatIn(lst, name,nodes_parent) - try: - tmp_list = list(lst) - if tmp_list: - tmp_list = self.recur(tmp_list) - else: - return super(general_ledger,self).repeatIn(lst, name,nodes_parent) + if name=='o': + list_final=[] + if not lst: + return super(general_ledger,self).repeatIn(lst, name,nodes_parent) + try: + tmp_list = list(lst) + if tmp_list: + tmp_list = self.recur(tmp_list) + else: + return super(general_ledger,self).repeatIn(lst, name,nodes_parent) - lst = list(set([x for x in tmp_list])) + lst = list(set([x for x in tmp_list])) - final={} -# for x in lst: -# final[x]=x.id -# final1=sorted(final.items(), lambda x, y: cmp(x[1], y[1])) + final={} +# for x in lst: +# final[x]=x.id +# final1=sorted(final.items(), lambda x, y: cmp(x[1], y[1])) # -# for a in final1: -# list_final.append(a[0]) - list_final=tmp_list +# for a in final1: +# list_final.append(a[0]) + list_final=tmp_list - except: - pass - else: + except: + pass + else: - list_final=lst - ret_data = super(general_ledger,self).repeatIn(list_final, name,nodes_parent) + list_final=lst + ret_data = super(general_ledger,self).repeatIn(list_final, name,nodes_parent) - return ret_data + return ret_data - def lines(self, account, form): + def lines(self, account, form): - ctx = self.context.copy() - ctx['fiscalyear'] = form['fiscalyear'] - ctx['periods'] = form['periods'][0][2] - query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) - self.cr.execute("SELECT l.date, j.code, l.ref, l.name, l.debit, l.credit "\ - "FROM account_move_line l, account_journal j "\ - "WHERE l.journal_id = j.id "\ - "AND account_id = %d AND "+query+" "\ - "ORDER by l.id", (account.id,)) - res = self.cr.dictfetchall() - sum = 0.0 + ctx = self.context.copy() + ctx['fiscalyear'] = form['fiscalyear'] + ctx['periods'] = form['periods'][0][2] + query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) + self.cr.execute("SELECT l.date, j.code, l.ref, l.name, l.debit, l.credit "\ + "FROM account_move_line l, account_journal j "\ + "WHERE l.journal_id = j.id "\ + "AND account_id = %d AND "+query+" "\ + "ORDER by l.id", (account.id,)) + res = self.cr.dictfetchall() + sum = 0.0 - for l in res: - sum += l['debit'] - l ['credit'] - l['progress'] = sum - self.ids +=[account.id] - return res + for l in res: + sum += l['debit'] - l ['credit'] + l['progress'] = sum + self.ids +=[account.id] + return res - def _sum_debit_account(self, account, form): - ctx = self.context.copy() - ctx['fiscalyear'] = form['fiscalyear'] - ctx['periods'] = form['periods'][0][2] - query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) - self.cr.execute("SELECT sum(debit) "\ - "FROM account_move_line l "\ - "WHERE l.account_id = %d AND "+query, (account.id,)) - return self.cr.fetchone()[0] or 0.0 + def _sum_debit_account(self, account, form): + ctx = self.context.copy() + ctx['fiscalyear'] = form['fiscalyear'] + ctx['periods'] = form['periods'][0][2] + query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) + self.cr.execute("SELECT sum(debit) "\ + "FROM account_move_line l "\ + "WHERE l.account_id = %d AND "+query, (account.id,)) + return self.cr.fetchone()[0] or 0.0 - def _sum_credit_account(self, account, form): - ctx = self.context.copy() - ctx['fiscalyear'] = form['fiscalyear'] - ctx['periods'] = form['periods'][0][2] - query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) - self.cr.execute("SELECT sum(credit) "\ - "FROM account_move_line l "\ - "WHERE l.account_id = %d AND "+query, (account.id,)) - return self.cr.fetchone()[0] or 0.0 + def _sum_credit_account(self, account, form): + ctx = self.context.copy() + ctx['fiscalyear'] = form['fiscalyear'] + ctx['periods'] = form['periods'][0][2] + query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) + self.cr.execute("SELECT sum(credit) "\ + "FROM account_move_line l "\ + "WHERE l.account_id = %d AND "+query, (account.id,)) + return self.cr.fetchone()[0] or 0.0 - def _sum_debit(self, form): - if not self.ids: - return 0.0 - ctx = self.context.copy() - ctx['fiscalyear'] = form['fiscalyear'] - ctx['periods'] = form['periods'][0][2] - query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) - self.cr.execute("SELECT sum(debit) "\ - "FROM account_move_line l "\ - "WHERE l.account_id in ("+','.join(map(str, self.ids))+") AND "+query) + def _sum_debit(self, form): + if not self.ids: + return 0.0 + ctx = self.context.copy() + ctx['fiscalyear'] = form['fiscalyear'] + ctx['periods'] = form['periods'][0][2] + query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) + self.cr.execute("SELECT sum(debit) "\ + "FROM account_move_line l "\ + "WHERE l.account_id in ("+','.join(map(str, self.ids))+") AND "+query) - return self.cr.fetchone()[0] or 0.0 + return self.cr.fetchone()[0] or 0.0 - def _sum_credit(self, form): - if not self.ids: - return 0.0 - ctx = self.context.copy() - ctx['fiscalyear'] = form['fiscalyear'] - ctx['periods'] = form['periods'][0][2] - query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) - self.cr.execute("SELECT sum(credit) "\ - "FROM account_move_line l "\ - "WHERE l.account_id in ("+','.join(map(str, self.ids))+") AND "+query) - return self.cr.fetchone()[0] or 0.0 + def _sum_credit(self, form): + if not self.ids: + return 0.0 + ctx = self.context.copy() + ctx['fiscalyear'] = form['fiscalyear'] + ctx['periods'] = form['periods'][0][2] + query = self.pool.get('account.move.line')._query_get(self.cr, self.uid, context=ctx) + self.cr.execute("SELECT sum(credit) "\ + "FROM account_move_line l "\ + "WHERE l.account_id in ("+','.join(map(str, self.ids))+") AND "+query) + return self.cr.fetchone()[0] or 0.0 report_sxw.report_sxw('report.account.general.ledger', 'account.account', 'addons/account/report/general_ledger.rml', parser=general_ledger, header=False) diff --git a/addons/account/report/invoice.py b/addons/account/report/invoice.py index f8d1bbc036c..786ea6153ca 100644 --- a/addons/account/report/invoice.py +++ b/addons/account/report/invoice.py @@ -31,15 +31,15 @@ import time from report import report_sxw class account_invoice(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(account_invoice, self).__init__(cr, uid, name, context) - self.localcontext.update({ - 'time': time, - }) + def __init__(self, cr, uid, name, context): + super(account_invoice, self).__init__(cr, uid, name, context) + self.localcontext.update({ + 'time': time, + }) report_sxw.report_sxw( - 'report.account.invoice', - 'account.invoice', - 'addons/account/report/invoice.rml', - parser=account_invoice, - ) + 'report.account.invoice', + 'account.invoice', + 'addons/account/report/invoice.rml', + parser=account_invoice, + ) diff --git a/addons/account/report/overdue.py b/addons/account/report/overdue.py index afd0c32794c..f551811de60 100644 --- a/addons/account/report/overdue.py +++ b/addons/account/report/overdue.py @@ -35,30 +35,30 @@ from report import report_sxw import pooler class Overdue(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(Overdue, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time' : time, - 'adr_get' : self._adr_get, - 'getLines' : self._lines_get, - }) + def __init__(self, cr, uid, name, context): + super(Overdue, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time' : time, + 'adr_get' : self._adr_get, + 'getLines' : self._lines_get, + }) - def _adr_get(self, partner, type): - res_partner = pooler.get_pool(self.cr.dbname).get('res.partner') - res_partner_address = pooler.get_pool(self.cr.dbname).get('res.partner.address') - addresses = res_partner.address_get(self.cr, self.uid, [partner.id], [type]) - adr_id = addresses and addresses[type] or False - return adr_id and res_partner_address.read(self.cr, self.uid, [adr_id])[0] or False + def _adr_get(self, partner, type): + res_partner = pooler.get_pool(self.cr.dbname).get('res.partner') + res_partner_address = pooler.get_pool(self.cr.dbname).get('res.partner.address') + addresses = res_partner.address_get(self.cr, self.uid, [partner.id], [type]) + adr_id = addresses and addresses[type] or False + return adr_id and res_partner_address.read(self.cr, self.uid, [adr_id])[0] or False - def _lines_get(self, partner): - moveline_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - movelines = moveline_obj.search(self.cr, self.uid, - [('partner_id', '=', partner.id), - ('account_id.type', 'in', ['receivable', 'payable']), - ('state', '<>', 'draft'), ('reconcile_id', '=', False)]) - movelines = moveline_obj.browse(self.cr, self.uid, movelines) - return movelines + def _lines_get(self, partner): + moveline_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + movelines = moveline_obj.search(self.cr, self.uid, + [('partner_id', '=', partner.id), + ('account_id.type', 'in', ['receivable', 'payable']), + ('state', '<>', 'draft'), ('reconcile_id', '=', False)]) + movelines = moveline_obj.browse(self.cr, self.uid, movelines) + return movelines report_sxw.report_sxw('report.account.overdue', 'res.partner', - 'addons/account/report/overdue.rml', parser=Overdue) + 'addons/account/report/overdue.rml', parser=Overdue) diff --git a/addons/account/report/partner_balance.py b/addons/account/report/partner_balance.py index 236debed330..6d50da8ff7a 100644 --- a/addons/account/report/partner_balance.py +++ b/addons/account/report/partner_balance.py @@ -32,201 +32,201 @@ import time from report import report_sxw class partner_balance(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(partner_balance, self).__init__(cr, uid, name, context) - self.localcontext.update( { - 'time': time, - 'lines': self.lines, - 'sum_debit': self._sum_debit, - 'sum_credit': self._sum_credit, - 'sum_litige': self._sum_litige, - 'sum_sdebit': self._sum_sdebit, - 'sum_scredit': self._sum_scredit, - 'solde_debit': self._solde_balance_debit, - 'solde_credit': self._solde_balance_credit, - 'get_company': self._get_company, - 'get_currency': self._get_currency, - }) + def __init__(self, cr, uid, name, context): + super(partner_balance, self).__init__(cr, uid, name, context) + self.localcontext.update( { + 'time': time, + 'lines': self.lines, + 'sum_debit': self._sum_debit, + 'sum_credit': self._sum_credit, + 'sum_litige': self._sum_litige, + 'sum_sdebit': self._sum_sdebit, + 'sum_scredit': self._sum_scredit, + 'solde_debit': self._solde_balance_debit, + 'solde_credit': self._solde_balance_credit, + 'get_company': self._get_company, + 'get_currency': self._get_currency, + }) - def preprocess(self, objects, data, ids): - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', - context={'fiscalyear': data['form']['fiscalyear']}) - self.cr.execute('SELECT DISTINCT line.partner_id ' \ - 'FROM account_move_line AS line, account_account AS account ' \ - 'WHERE line.partner_id IS NOT NULL ' \ - 'AND line.date >= %s ' \ - 'AND line.date <= %s ' \ - 'AND ' + line_query + ' ' \ - 'AND line.account_id = account.id ' \ - 'AND account.company_id = %d ' \ - 'AND account.active', - (data['form']['date1'], data['form']['date2'], - data['form']['company_id'])) - new_ids = [id for (id,) in self.cr.fetchall()] - self.cr.execute('SELECT a.id ' \ - 'FROM account_account a ' \ - 'LEFT JOIN account_account_type t ' \ - 'ON (a.type = t.code) ' \ - 'WHERE t.partner_account = TRUE ' \ - 'AND a.company_id = %d ' \ - 'AND a.active', (data['form']['company_id'],)) - self.account_ids = ','.join([str(a) for (a,) in self.cr.fetchall()]) - self.partner_ids = ','.join(map(str, new_ids)) - objects = self.pool.get('res.partner').browse(self.cr, self.uid, new_ids) - super(partner_balance, self).preprocess(objects, data, new_ids) + def preprocess(self, objects, data, ids): + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', + context={'fiscalyear': data['form']['fiscalyear']}) + self.cr.execute('SELECT DISTINCT line.partner_id ' \ + 'FROM account_move_line AS line, account_account AS account ' \ + 'WHERE line.partner_id IS NOT NULL ' \ + 'AND line.date >= %s ' \ + 'AND line.date <= %s ' \ + 'AND ' + line_query + ' ' \ + 'AND line.account_id = account.id ' \ + 'AND account.company_id = %d ' \ + 'AND account.active', + (data['form']['date1'], data['form']['date2'], + data['form']['company_id'])) + new_ids = [id for (id,) in self.cr.fetchall()] + self.cr.execute('SELECT a.id ' \ + 'FROM account_account a ' \ + 'LEFT JOIN account_account_type t ' \ + 'ON (a.type = t.code) ' \ + 'WHERE t.partner_account = TRUE ' \ + 'AND a.company_id = %d ' \ + 'AND a.active', (data['form']['company_id'],)) + self.account_ids = ','.join([str(a) for (a,) in self.cr.fetchall()]) + self.partner_ids = ','.join(map(str, new_ids)) + objects = self.pool.get('res.partner').browse(self.cr, self.uid, new_ids) + super(partner_balance, self).preprocess(objects, data, new_ids) - def lines(self): - if not self.partner_ids: - return [] - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='l', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - "SELECT p.ref, p.name, sum(debit) as debit, sum(credit) as credit, " \ - "CASE WHEN sum(debit) > sum(credit) " \ - "THEN sum(debit) - sum(credit) " \ - "ELSE 0 " \ - "END AS sdebit, " \ - "CASE WHEN sum(debit) < sum(credit) " \ - "THEN sum(credit) - sum(debit) " \ - "ELSE 0 " \ - "END AS scredit, " \ - "(SELECT sum(debit-credit) " \ - "FROM account_move_line l " \ - "WHERE partner_id = p.id " \ - "AND date >= %s " \ - "AND date <= %s " \ - "AND blocked = TRUE " \ - "AND " + line_query + " " \ - ") AS enlitige " \ - "FROM account_move_line l LEFT JOIN res_partner p ON (l.partner_id=p.id) " \ - "WHERE partner_id IN (" + self.partner_ids + ") " \ - "AND account_id IN (" + self.account_ids + ") " \ - "AND l.date >= %s " \ - "AND l.date <= %s " \ - "AND " + line_query + " " \ - "GROUP BY p.id, p.ref, p.name " \ - "ORDER BY p.ref, p.name", - (self.datas['form']['date1'], self.datas['form']['date2'], - self.datas['form']['date1'], self.datas['form']['date2'])) - res = self.cr.dictfetchall() - return res + def lines(self): + if not self.partner_ids: + return [] + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='l', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + "SELECT p.ref, p.name, sum(debit) as debit, sum(credit) as credit, " \ + "CASE WHEN sum(debit) > sum(credit) " \ + "THEN sum(debit) - sum(credit) " \ + "ELSE 0 " \ + "END AS sdebit, " \ + "CASE WHEN sum(debit) < sum(credit) " \ + "THEN sum(credit) - sum(debit) " \ + "ELSE 0 " \ + "END AS scredit, " \ + "(SELECT sum(debit-credit) " \ + "FROM account_move_line l " \ + "WHERE partner_id = p.id " \ + "AND date >= %s " \ + "AND date <= %s " \ + "AND blocked = TRUE " \ + "AND " + line_query + " " \ + ") AS enlitige " \ + "FROM account_move_line l LEFT JOIN res_partner p ON (l.partner_id=p.id) " \ + "WHERE partner_id IN (" + self.partner_ids + ") " \ + "AND account_id IN (" + self.account_ids + ") " \ + "AND l.date >= %s " \ + "AND l.date <= %s " \ + "AND " + line_query + " " \ + "GROUP BY p.id, p.ref, p.name " \ + "ORDER BY p.ref, p.name", + (self.datas['form']['date1'], self.datas['form']['date2'], + self.datas['form']['date1'], self.datas['form']['date2'])) + res = self.cr.dictfetchall() + return res - def _sum_debit(self): - if not self.ids: - return 0.0 - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - 'SELECT sum(debit) ' \ - 'FROM account_move_line ' \ - 'WHERE partner_id IN (' + self.partner_ids + ') ' \ - 'AND account_id IN (' + self.account_ids + ') ' \ - 'AND date >=%s ' \ - 'AND date <= %s ' \ - 'AND ' + line_query, - (self.datas['form']['date1'], self.datas['form']['date2'])) - return self.cr.fetchone()[0] or 0.0 + def _sum_debit(self): + if not self.ids: + return 0.0 + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + 'SELECT sum(debit) ' \ + 'FROM account_move_line ' \ + 'WHERE partner_id IN (' + self.partner_ids + ') ' \ + 'AND account_id IN (' + self.account_ids + ') ' \ + 'AND date >=%s ' \ + 'AND date <= %s ' \ + 'AND ' + line_query, + (self.datas['form']['date1'], self.datas['form']['date2'])) + return self.cr.fetchone()[0] or 0.0 - def _sum_credit(self): - if not self.ids: - return 0.0 - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - 'SELECT sum(credit) ' \ - 'FROM account_move_line ' \ - 'WHERE partner_id IN (' + self.partner_ids + ') ' \ - 'AND account_id IN (' + self.account_ids + ') ' \ - 'AND date >= %s ' \ - 'AND date <= %s ' \ - 'AND ' + line_query, - (self.datas['form']['date1'], self.datas['form']['date2'])) - return self.cr.fetchone()[0] or 0.0 + def _sum_credit(self): + if not self.ids: + return 0.0 + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + 'SELECT sum(credit) ' \ + 'FROM account_move_line ' \ + 'WHERE partner_id IN (' + self.partner_ids + ') ' \ + 'AND account_id IN (' + self.account_ids + ') ' \ + 'AND date >= %s ' \ + 'AND date <= %s ' \ + 'AND ' + line_query, + (self.datas['form']['date1'], self.datas['form']['date2'])) + return self.cr.fetchone()[0] or 0.0 - def _sum_litige(self): - if not self.ids: - return 0.0 - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - 'SELECT sum(debit-credit) ' \ - 'FROM account_move_line ' \ - 'WHERE partner_id IN (' + self.partner_ids + ') ' \ - 'AND account_id IN (' + self.account_ids + ') ' \ - 'AND date >= %s ' \ - 'AND date <= %s ' \ - 'AND blocked=TRUE ' \ - 'AND ' + line_query, - (self.datas['form']['date1'], self.datas['form']['date2'])) - return self.cr.fetchone()[0] or 0.0 + def _sum_litige(self): + if not self.ids: + return 0.0 + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + 'SELECT sum(debit-credit) ' \ + 'FROM account_move_line ' \ + 'WHERE partner_id IN (' + self.partner_ids + ') ' \ + 'AND account_id IN (' + self.account_ids + ') ' \ + 'AND date >= %s ' \ + 'AND date <= %s ' \ + 'AND blocked=TRUE ' \ + 'AND ' + line_query, + (self.datas['form']['date1'], self.datas['form']['date2'])) + return self.cr.fetchone()[0] or 0.0 - def _sum_sdebit(self): - if not self.ids: - return 0.0 - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - 'SELECT CASE WHEN sum(debit) > sum(credit) ' \ - 'THEN sum(debit - credit) ' \ - 'ELSE 0 ' \ - 'END ' \ - 'FROM account_move_line ' \ - 'WHERE partner_id IN (' + self.partner_ids + ') ' \ - 'AND account_id IN (' + self.account_ids + ') ' \ - 'AND date >= %s ' \ - 'AND date <= %s ' \ - 'AND ' + line_query + ' ' \ - 'GROUP BY partner_id', - (self.datas['form']['date1'], self.datas['form']['date2'])) - return self.cr.fetchone()[0] or 0.0 + def _sum_sdebit(self): + if not self.ids: + return 0.0 + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + 'SELECT CASE WHEN sum(debit) > sum(credit) ' \ + 'THEN sum(debit - credit) ' \ + 'ELSE 0 ' \ + 'END ' \ + 'FROM account_move_line ' \ + 'WHERE partner_id IN (' + self.partner_ids + ') ' \ + 'AND account_id IN (' + self.account_ids + ') ' \ + 'AND date >= %s ' \ + 'AND date <= %s ' \ + 'AND ' + line_query + ' ' \ + 'GROUP BY partner_id', + (self.datas['form']['date1'], self.datas['form']['date2'])) + return self.cr.fetchone()[0] or 0.0 - def _sum_scredit(self): - if not self.ids: - return 0.0 - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - 'SELECT CASE WHEN sum(debit) < sum(credit) ' \ - 'THEN sum(credit - debit) ' \ - 'ELSE 0 ' \ - 'END ' \ - 'FROM account_move_line ' \ - 'WHERE partner_id IN (' + self.partner_ids + ') ' \ - 'AND account_id IN (' + self.account_ids + ') ' \ - 'AND date >= %s ' \ - 'AND date <= %s ' \ - 'AND ' + line_query + ' ' \ - 'GROUP BY partner_id', - (self.datas['form']['date1'], self.datas['form']['date2'])) - return self.cr.fetchone()[0] or 0.0 + def _sum_scredit(self): + if not self.ids: + return 0.0 + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + 'SELECT CASE WHEN sum(debit) < sum(credit) ' \ + 'THEN sum(credit - debit) ' \ + 'ELSE 0 ' \ + 'END ' \ + 'FROM account_move_line ' \ + 'WHERE partner_id IN (' + self.partner_ids + ') ' \ + 'AND account_id IN (' + self.account_ids + ') ' \ + 'AND date >= %s ' \ + 'AND date <= %s ' \ + 'AND ' + line_query + ' ' \ + 'GROUP BY partner_id', + (self.datas['form']['date1'], self.datas['form']['date2'])) + return self.cr.fetchone()[0] or 0.0 - def _solde_balance_debit(self): - debit, credit = self._sum_debit(), self._sum_credit() - return debit > credit and debit - credit - - def _solde_balance_credit(self): - debit, credit = self._sum_debit(), self._sum_credit() - return credit > debit and credit - debit + def _solde_balance_debit(self): + debit, credit = self._sum_debit(), self._sum_credit() + return debit > credit and debit - credit + + def _solde_balance_credit(self): + debit, credit = self._sum_debit(), self._sum_credit() + return credit > debit and credit - debit - def _get_company(self, form): - return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).name + def _get_company(self, form): + return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).name - def _get_currency(self, form): - return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).currency_id.name + def _get_currency(self, form): + return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).currency_id.name report_sxw.report_sxw('report.account.partner.balance', 'res.partner', - 'addons/account/report/partner_balance.rml',parser=partner_balance, - header=False) + 'addons/account/report/partner_balance.rml',parser=partner_balance, + header=False) diff --git a/addons/account/report/tax_report.py b/addons/account/report/tax_report.py index 6fd442e4394..dc08fe36c9a 100644 --- a/addons/account/report/tax_report.py +++ b/addons/account/report/tax_report.py @@ -33,85 +33,85 @@ from report import report_sxw class tax_report(report_sxw.rml_parse): - def __init__(self, cr, uid, name, context): - super(tax_report, self).__init__(cr, uid, name, context) - self.localcontext.update({ - 'time': time, - 'get_period': self._get_period, - 'get_codes': self._get_codes, - 'get_general': self._get_general, - 'get_company': self._get_company, - 'get_currency': self._get_currency, - }) + def __init__(self, cr, uid, name, context): + super(tax_report, self).__init__(cr, uid, name, context) + self.localcontext.update({ + 'time': time, + 'get_period': self._get_period, + 'get_codes': self._get_codes, + 'get_general': self._get_general, + 'get_company': self._get_company, + 'get_currency': self._get_currency, + }) - def _add_header(self, node): - return True + def _add_header(self, node): + return True - def _get_period(self, period_id): - return self.pool.get('account.period').browse(self.cr, self.uid, period_id).name + def _get_period(self, period_id): + return self.pool.get('account.period').browse(self.cr, self.uid, period_id).name - def _get_general(self, tax_code_id, period_id, company_id, based_on): - res=[] - if based_on == 'payments': - self.cr.execute('SELECT SUM(line.tax_amount) AS tax_amount, \ - SUM(line.debit) AS debit, \ - SUM(line.credit) AS credit, \ - COUNT(*) AS count, \ - account.id AS account_id \ - FROM account_move_line AS line, \ - account_account AS account, \ - account_move AS move \ - LEFT JOIN account_invoice invoice ON \ - (invoice.move_id = move.id) \ - WHERE line.state<>%s \ - AND line.period_id = %d \ - AND line.tax_code_id = %d \ - AND line.account_id = account.id \ - AND account.company_id = %d \ - AND move.id = line.move_id \ - AND ((invoice.state = %s) \ - OR (invoice.id IS NULL)) \ - GROUP BY account.id', ('draft', period_id, tax_code_id, - company_id, 'paid')) - else : - self.cr.execute('SELECT SUM(line.tax_amount) AS tax_amount, \ - SUM(line.debit) AS debit, \ - SUM(line.credit) AS credit, \ - COUNT(*) AS count, \ - account.id AS account_id \ - FROM account_move_line AS line, \ - account_account AS account \ - WHERE line.state <> %s \ - AND line.period_id = %d \ - AND line.tax_code_id = %d \ - AND line.account_id = account.id \ - AND account.company_id = %d \ - AND account.active \ - GROUP BY account.id', ('draft', period_id, tax_code_id, - company_id)) - res = self.cr.dictfetchall() - i = 0 - while i%s \ + AND line.period_id = %d \ + AND line.tax_code_id = %d \ + AND line.account_id = account.id \ + AND account.company_id = %d \ + AND move.id = line.move_id \ + AND ((invoice.state = %s) \ + OR (invoice.id IS NULL)) \ + GROUP BY account.id', ('draft', period_id, tax_code_id, + company_id, 'paid')) + else : + self.cr.execute('SELECT SUM(line.tax_amount) AS tax_amount, \ + SUM(line.debit) AS debit, \ + SUM(line.credit) AS credit, \ + COUNT(*) AS count, \ + account.id AS account_id \ + FROM account_move_line AS line, \ + account_account AS account \ + WHERE line.state <> %s \ + AND line.period_id = %d \ + AND line.tax_code_id = %d \ + AND line.account_id = account.id \ + AND account.company_id = %d \ + AND account.active \ + GROUP BY account.id', ('draft', period_id, tax_code_id, + company_id)) + res = self.cr.dictfetchall() + i = 0 + while i= %s " \ - "AND line.date <= %s " \ - "AND " + line_query + " " \ - "AND line.account_id = account.id " \ - "AND account.company_id = %d " \ - "AND account.active", - (data['form']['date1'], data['form']['date2'], - data['form']['company_id'])) - new_ids = [id for (id,) in self.cr.fetchall()] - self.cr.execute( - "SELECT a.id " \ - "FROM account_account a " \ - "LEFT JOIN account_account_type t " \ - "ON (a.type=t.code) " \ - "WHERE t.partner_account=TRUE " \ - "AND a.company_id = %d " \ - "AND a.active", (data['form']['company_id'],)) - self.account_ids = ','.join([str(a) for (a,) in self.cr.fetchall()]) - self.partner_ids = ','.join(map(str, new_ids)) - objects = self.pool.get('res.partner').browse(self.cr, self.uid, new_ids) - super(third_party_ledger, self).preprocess(objects, data, new_ids) + def preprocess(self, objects, data, ids): + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='line', + context={'fiscalyear': data['form']['fiscalyear']}) + self.cr.execute( + "SELECT DISTINCT line.partner_id " \ + "FROM account_move_line AS line, account_account AS account " \ + "WHERE line.partner_id IS NOT NULL " \ + "AND line.date >= %s " \ + "AND line.date <= %s " \ + "AND " + line_query + " " \ + "AND line.account_id = account.id " \ + "AND account.company_id = %d " \ + "AND account.active", + (data['form']['date1'], data['form']['date2'], + data['form']['company_id'])) + new_ids = [id for (id,) in self.cr.fetchall()] + self.cr.execute( + "SELECT a.id " \ + "FROM account_account a " \ + "LEFT JOIN account_account_type t " \ + "ON (a.type=t.code) " \ + "WHERE t.partner_account=TRUE " \ + "AND a.company_id = %d " \ + "AND a.active", (data['form']['company_id'],)) + self.account_ids = ','.join([str(a) for (a,) in self.cr.fetchall()]) + self.partner_ids = ','.join(map(str, new_ids)) + objects = self.pool.get('res.partner').browse(self.cr, self.uid, new_ids) + super(third_party_ledger, self).preprocess(objects, data, new_ids) - def lines(self, partner): - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='l', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - "SELECT l.date, j.code, l.ref, l.name, l.debit, l.credit " \ - "FROM account_move_line l " \ - "LEFT JOIN account_journal j " \ - "ON (l.journal_id = j.id) " \ - "WHERE l.partner_id = %d " \ - "AND l.account_id IN (" + self.account_ids + ") " \ - "AND l.date >= %s " \ - "AND l.date <= %s " - "AND " + line_query + " " \ - "ORDER BY l.id", - (partner.id, self.datas['form']['date1'], self.datas['form']['date2'])) - res = self.cr.dictfetchall() - sum = 0.0 - for r in res: - sum += r['debit'] - r['credit'] - r['progress'] = sum - return res + def lines(self, partner): + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, obj='l', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + "SELECT l.date, j.code, l.ref, l.name, l.debit, l.credit " \ + "FROM account_move_line l " \ + "LEFT JOIN account_journal j " \ + "ON (l.journal_id = j.id) " \ + "WHERE l.partner_id = %d " \ + "AND l.account_id IN (" + self.account_ids + ") " \ + "AND l.date >= %s " \ + "AND l.date <= %s " + "AND " + line_query + " " \ + "ORDER BY l.id", + (partner.id, self.datas['form']['date1'], self.datas['form']['date2'])) + res = self.cr.dictfetchall() + sum = 0.0 + for r in res: + sum += r['debit'] - r['credit'] + r['progress'] = sum + return res - def _sum_debit_partner(self, partner): - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - "SELECT sum(debit) " \ - "FROM account_move_line " \ - "WHERE partner_id = %d " \ - "AND account_id IN (" + self.account_ids + ") " \ - "AND date >= %s " \ - "AND date <= %s " \ - "AND " + line_query, - (partner.id, self.datas['form']['date1'], self.datas['form']['date2'])) - return self.cr.fetchone()[0] or 0.0 - - def _sum_credit_partner(self, partner): - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - "SELECT sum(credit) " \ - "FROM account_move_line " \ - "WHERE partner_id=%d " \ - "AND account_id IN (" + self.account_ids + ") " \ - "AND date >= %s " \ - "AND date <= %s " \ - "AND " + line_query, - (partner.id, self.datas["form"]["date1"], self.datas["form"]["date2"])) - return self.cr.fetchone()[0] or 0.0 - - def _sum_debit(self): - if not self.ids: - return 0.0 - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - "SELECT sum(debit) " \ - "FROM account_move_line " \ - "WHERE partner_id IN (" + self.partner_ids + ") " \ - "AND account_id IN (" + self.account_ids + ") " \ - "AND date >= %s " \ - "AND date <= %s " \ - "AND " + line_query, - (self.datas['form']['date1'], self.datas['form']['date2'])) - return self.cr.fetchone()[0] or 0.0 - - def _sum_credit(self): - if not self.ids: - return 0.0 - account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') - line_query = account_move_line_obj._query_get(self.cr, self.uid, - obj='account_move_line', - context={'fiscalyear': self.datas['form']['fiscalyear']}) - self.cr.execute( - "SELECT sum(credit) " \ - "FROM account_move_line " \ - "WHERE partner_id IN (" + self.partner_ids + ") " \ - "AND account_id IN (" + self.account_ids + ") " \ - "AND date >= %s " \ - "AND date <= %s " \ - "AND " + line_query, - (self.datas['form']['date1'], self.datas['form']['date2'])) - return self.cr.fetchone()[0] or 0.0 + def _sum_debit_partner(self, partner): + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + "SELECT sum(debit) " \ + "FROM account_move_line " \ + "WHERE partner_id = %d " \ + "AND account_id IN (" + self.account_ids + ") " \ + "AND date >= %s " \ + "AND date <= %s " \ + "AND " + line_query, + (partner.id, self.datas['form']['date1'], self.datas['form']['date2'])) + return self.cr.fetchone()[0] or 0.0 + + def _sum_credit_partner(self, partner): + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + "SELECT sum(credit) " \ + "FROM account_move_line " \ + "WHERE partner_id=%d " \ + "AND account_id IN (" + self.account_ids + ") " \ + "AND date >= %s " \ + "AND date <= %s " \ + "AND " + line_query, + (partner.id, self.datas["form"]["date1"], self.datas["form"]["date2"])) + return self.cr.fetchone()[0] or 0.0 + + def _sum_debit(self): + if not self.ids: + return 0.0 + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + "SELECT sum(debit) " \ + "FROM account_move_line " \ + "WHERE partner_id IN (" + self.partner_ids + ") " \ + "AND account_id IN (" + self.account_ids + ") " \ + "AND date >= %s " \ + "AND date <= %s " \ + "AND " + line_query, + (self.datas['form']['date1'], self.datas['form']['date2'])) + return self.cr.fetchone()[0] or 0.0 + + def _sum_credit(self): + if not self.ids: + return 0.0 + account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line') + line_query = account_move_line_obj._query_get(self.cr, self.uid, + obj='account_move_line', + context={'fiscalyear': self.datas['form']['fiscalyear']}) + self.cr.execute( + "SELECT sum(credit) " \ + "FROM account_move_line " \ + "WHERE partner_id IN (" + self.partner_ids + ") " \ + "AND account_id IN (" + self.account_ids + ") " \ + "AND date >= %s " \ + "AND date <= %s " \ + "AND " + line_query, + (self.datas['form']['date1'], self.datas['form']['date2'])) + return self.cr.fetchone()[0] or 0.0 - def _get_company(self, form): - return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).name + def _get_company(self, form): + return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).name - def _get_currency(self, form): - return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).currency_id.name + def _get_currency(self, form): + return pooler.get_pool(self.cr.dbname).get('res.company').browse(self.cr, self.uid, form['company_id']).currency_id.name report_sxw.report_sxw('report.account.third_party_ledger', 'res.partner', - 'addons/account/report/third_party_ledger.rml',parser=third_party_ledger, - header=False) + 'addons/account/report/third_party_ledger.rml',parser=third_party_ledger, + header=False) diff --git a/addons/account/wizard/wizard_account_balance_report.py b/addons/account/wizard/wizard_account_balance_report.py index 47d515ef144..f3ff3f72a2b 100644 --- a/addons/account/wizard/wizard_account_balance_report.py +++ b/addons/account/wizard/wizard_account_balance_report.py @@ -32,35 +32,35 @@ import pooler dates_form = '''
- - + + ''' dates_fields = { - 'fiscalyear': {'string': 'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear', - 'help': 'Keep empty for all open fiscal year'}, - 'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty'} + 'fiscalyear': {'string': 'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear', + 'help': 'Keep empty for all open fiscal year'}, + 'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty'} } class wizard_report(wizard.interface): - def _get_defaults(self, cr, uid, data, context): - fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') - data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) - data['form']['target_move'] = False - if context.has_key('target_move'): - data['form']['target_move'] = context['target_move'] - return data['form'] + def _get_defaults(self, cr, uid, data, context): + fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') + data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) + data['form']['target_move'] = False + if context.has_key('target_move'): + data['form']['target_move'] = context['target_move'] + return data['form'] - states = { - 'init': { - 'actions': [_get_defaults], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.account.balance', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_get_defaults], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.account.balance', 'state':'end'} + } + } wizard_report('account.account.balance.report') diff --git a/addons/account/wizard/wizard_account_chart.py b/addons/account/wizard/wizard_account_chart.py index 4809382a019..48854c62255 100644 --- a/addons/account/wizard/wizard_account_chart.py +++ b/addons/account/wizard/wizard_account_chart.py @@ -31,52 +31,52 @@ import wizard import pooler class wizard_account_chart(wizard.interface): - _account_chart_arch = ''' -
- - - ''' - - _account_chart_fields = { - 'fiscalyear': { - 'string': 'Fiscal year', - 'type': 'many2one', - 'relation': 'account.fiscalyear', - 'help': 'Keep empty for all open fiscal year', - }, - 'target_move': { - 'string': 'Target Moves', - 'type': 'selection', - 'selection': [('all','All Entries'),('posted_only','All Posted Entries')], - 'required': True, - 'default': lambda *a:"all", - }, - } + _account_chart_arch = ''' +
+ + + ''' + + _account_chart_fields = { + 'fiscalyear': { + 'string': 'Fiscal year', + 'type': 'many2one', + 'relation': 'account.fiscalyear', + 'help': 'Keep empty for all open fiscal year', + }, + 'target_move': { + 'string': 'Target Moves', + 'type': 'selection', + 'selection': [('all','All Entries'),('posted_only','All Posted Entries')], + 'required': True, + 'default': lambda *a:"all", + }, + } - def _get_defaults(self, cr, uid, data, context): - fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') - data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) - return data['form'] + def _get_defaults(self, cr, uid, data, context): + fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') + data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) + return data['form'] - def _account_chart_open_window(self, cr, uid, data, context): - mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data') - act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window') + def _account_chart_open_window(self, cr, uid, data, context): + mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data') + act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window') - result = mod_obj._get_id(cr, uid, 'account', 'action_account_tree') - id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id'] - result = act_obj.read(cr, uid, [id])[0] - result['context'] = str({'fiscalyear': data['form']['fiscalyear'],'target_move':data['form']['target_move']}) - return result + result = mod_obj._get_id(cr, uid, 'account', 'action_account_tree') + id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id'] + result = act_obj.read(cr, uid, [id])[0] + result['context'] = str({'fiscalyear': data['form']['fiscalyear'],'target_move':data['form']['target_move']}) + return result - states = { - 'init': { - 'actions': [_get_defaults], - 'result': {'type': 'form', 'arch':_account_chart_arch, 'fields':_account_chart_fields, 'state': [('end', 'Cancel'), ('open', 'Open Charts')]} - }, - 'open': { - 'actions': [], - 'result': {'type': 'action', 'action':_account_chart_open_window, 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_get_defaults], + 'result': {'type': 'form', 'arch':_account_chart_arch, 'fields':_account_chart_fields, 'state': [('end', 'Cancel'), ('open', 'Open Charts')]} + }, + 'open': { + 'actions': [], + 'result': {'type': 'action', 'action':_account_chart_open_window, 'state':'end'} + } + } wizard_account_chart('account.chart') diff --git a/addons/account/wizard/wizard_account_duplicate.py b/addons/account/wizard/wizard_account_duplicate.py index 279c091db57..5b14b8dc904 100644 --- a/addons/account/wizard/wizard_account_duplicate.py +++ b/addons/account/wizard/wizard_account_duplicate.py @@ -32,27 +32,27 @@ import pooler duplicate_form = '''
- + ''' duplicate_fields = { - 'company_id': {'string': 'Company', 'type': 'many2one', 'relation': 'res.company', 'required': True}, + 'company_id': {'string': 'Company', 'type': 'many2one', 'relation': 'res.company', 'required': True}, } def _do_duplicate(self, cr, uid, data, context): - account_obj = pooler.get_pool(cr.dbname).get('account.account') - account_obj.copy(cr, uid, data['id'], data['form'], context=context) - return {} + account_obj = pooler.get_pool(cr.dbname).get('account.account') + account_obj.copy(cr, uid, data['id'], data['form'], context=context) + return {} class wizard_account_duplicate(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type': 'form', 'arch': duplicate_form, 'fields': duplicate_fields, 'state': (('end', 'Cancel'), ('duplicate', 'Duplicate'))}, - }, - 'duplicate': { - 'actions': [_do_duplicate], - 'result': {'type': 'state', 'state': 'end'}, - }, - } + states = { + 'init': { + 'actions': [], + 'result': {'type': 'form', 'arch': duplicate_form, 'fields': duplicate_fields, 'state': (('end', 'Cancel'), ('duplicate', 'Duplicate'))}, + }, + 'duplicate': { + 'actions': [_do_duplicate], + 'result': {'type': 'state', 'state': 'end'}, + }, + } wizard_account_duplicate('account.wizard.account.duplicate') diff --git a/addons/account/wizard/wizard_aged_trial_balance.py b/addons/account/wizard/wizard_aged_trial_balance.py index cf9af968671..26bbecd803b 100644 --- a/addons/account/wizard/wizard_aged_trial_balance.py +++ b/addons/account/wizard/wizard_aged_trial_balance.py @@ -37,67 +37,67 @@ from tools.translate import _ _aged_trial_form = """
- - - - - - - - - + + + + + + + + + """ _aged_trial_fields = { - 'company_id': {'string': 'Company', 'type': 'many2one', 'relation': 'res.company', 'required': True}, - 'fiscalyear': {'string': 'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear', - 'help': 'Keep empty for all open fiscal year'}, - 'period_length': {'string': 'Period length (days)', 'type': 'integer', 'required': True, 'default': lambda *a:30}, - 'sorting_on':{'string': 'Sorting On', 'type': 'selection', 'selection': [('partner','By Partner Name (asc)'), ('amount','By Amount (desc)')],'required': True, 'default': lambda *a:'partner'}, - 'computation':{'string': 'Computational Method', 'type': 'selection', 'selection': [("\'receivable\'",'On Receivables Only'), ("\'payable\'",'On Payables Only'), ("\'receivable\',\'payable\'",'On Receivables & Payables')], 'required': True, 'default': lambda *a:"\'receivable\'"} + 'company_id': {'string': 'Company', 'type': 'many2one', 'relation': 'res.company', 'required': True}, + 'fiscalyear': {'string': 'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear', + 'help': 'Keep empty for all open fiscal year'}, + 'period_length': {'string': 'Period length (days)', 'type': 'integer', 'required': True, 'default': lambda *a:30}, + 'sorting_on':{'string': 'Sorting On', 'type': 'selection', 'selection': [('partner','By Partner Name (asc)'), ('amount','By Amount (desc)')],'required': True, 'default': lambda *a:'partner'}, + 'computation':{'string': 'Computational Method', 'type': 'selection', 'selection': [("\'receivable\'",'On Receivables Only'), ("\'payable\'",'On Payables Only'), ("\'receivable\',\'payable\'",'On Receivables & Payables')], 'required': True, 'default': lambda *a:"\'receivable\'"} } def _calc_dates(self, cr, uid, data, context): - res = {} - period_length = data['form']['period_length'] - if period_length<=0: - raise wizard.except_wizard(_('UserError'), _('You must enter a period length that cannot be 0 or below !')) - start = now() - for i in range(5)[::-1]: - stop = start-RelativeDateTime(days=period_length) - res[str(i)] = { - 'name' : str((5-i)*period_length)+' days', - 'stop': start.strftime('%Y-%m-%d'), - 'start' : stop.strftime('%Y-%m-%d'), - } - start = stop - RelativeDateTime(days=1) - return res + res = {} + period_length = data['form']['period_length'] + if period_length<=0: + raise wizard.except_wizard(_('UserError'), _('You must enter a period length that cannot be 0 or below !')) + start = now() + for i in range(5)[::-1]: + stop = start-RelativeDateTime(days=period_length) + res[str(i)] = { + 'name' : str((5-i)*period_length)+' days', + 'stop': start.strftime('%Y-%m-%d'), + 'start' : stop.strftime('%Y-%m-%d'), + } + start = stop - RelativeDateTime(days=1) + return res class wizard_report(wizard.interface): - def _get_defaults(self, cr, uid, data, context): - fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') - data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) + def _get_defaults(self, cr, uid, data, context): + fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') + data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) - user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid, context=context) - if user.company_id: - company_id = user.company_id.id - else: - company_id = pooler.get_pool(cr.dbname).get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] - data['form']['company_id'] = company_id + user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid, context=context) + if user.company_id: + company_id = user.company_id.id + else: + company_id = pooler.get_pool(cr.dbname).get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] + data['form']['company_id'] = company_id - return data['form'] + return data['form'] - states = { - 'init': { - 'actions': [_get_defaults], - 'result': {'type':'form', 'arch':_aged_trial_form, 'fields':_aged_trial_fields, 'state':[('end','Cancel'),('print','Print Aged Partner Balance')]}, - }, - 'print': { - 'actions': [_calc_dates], - 'result': {'type':'print', 'report':'account.aged.trial.balance', 'state':'end'}, - }, - } + states = { + 'init': { + 'actions': [_get_defaults], + 'result': {'type':'form', 'arch':_aged_trial_form, 'fields':_aged_trial_fields, 'state':[('end','Cancel'),('print','Print Aged Partner Balance')]}, + }, + 'print': { + 'actions': [_calc_dates], + 'result': {'type':'print', 'report':'account.aged.trial.balance', 'state':'end'}, + }, + } wizard_report('account.aged.trial.balance') diff --git a/addons/account/wizard/wizard_automatic_reconcile.py b/addons/account/wizard/wizard_automatic_reconcile.py index 8b3c1d7080a..867de1a228f 100644 --- a/addons/account/wizard/wizard_automatic_reconcile.py +++ b/addons/account/wizard/wizard_automatic_reconcile.py @@ -40,11 +40,11 @@ import time # - journal # - compte d'ajustement # - montant max (0,03) - # + # # - libelle write-off # - devise principale ou secondaire - # devise secondaire = amount_currency - # si devise: pas prendre ceux avec montant_devise = 0 + # devise secondaire = amount_currency + # si devise: pas prendre ceux avec montant_devise = 0 # a demander à fabien: # - checkbox (comme ds sage) "lettrage rapide des comptes soldés"? @@ -54,273 +54,273 @@ import time _reconcile_form = '''
- - - - - - - - - - - + + + + + + + + + + + ''' _reconcile_fields = { - 'account_ids': { - 'string': 'Account to reconcile', - 'type': 'many2many', - 'relation': 'account.account', - 'domain': [('reconcile','=',1)], - 'required': True - }, - 'writeoff_acc_id': { - 'string': 'Account', - 'type': 'many2one', - 'relation': 'account.account', - 'required': True - }, - 'journal_id': { - 'string': 'Journal', - 'type': 'many2one', - 'relation': 'account.journal', - 'required': True - }, - 'period_id': { - 'string': 'Period', - 'type': 'many2one', - 'relation': 'account.period', - 'required': True - }, - 'max_amount': { - 'string': 'Maximum write-off amount', - 'type': 'float', - }, - #'currency': { - # 'string': 'Reconcile in', - # 'type': 'selection', - # 'selection': [('current','current currency'), ('secondary','secondary currency')], - # 'required': True - #}, - 'power': { - 'string': 'Power', - 'type': 'selection', - 'selection': [(p,str(p)) for p in range(2, 10)], - 'required': True - }, - 'date1': { - 'string': 'Start of period', - 'type': 'date', - 'required': True, - 'default': lambda *a: time.strftime('%Y-01-01') - }, - 'date2': { - 'string': 'End of period', - 'type': 'date', - 'required': True, - 'default': lambda *a: time.strftime('%Y-%m-%d') - }, + 'account_ids': { + 'string': 'Account to reconcile', + 'type': 'many2many', + 'relation': 'account.account', + 'domain': [('reconcile','=',1)], + 'required': True + }, + 'writeoff_acc_id': { + 'string': 'Account', + 'type': 'many2one', + 'relation': 'account.account', + 'required': True + }, + 'journal_id': { + 'string': 'Journal', + 'type': 'many2one', + 'relation': 'account.journal', + 'required': True + }, + 'period_id': { + 'string': 'Period', + 'type': 'many2one', + 'relation': 'account.period', + 'required': True + }, + 'max_amount': { + 'string': 'Maximum write-off amount', + 'type': 'float', + }, + #'currency': { + # 'string': 'Reconcile in', + # 'type': 'selection', + # 'selection': [('current','current currency'), ('secondary','secondary currency')], + # 'required': True + #}, + 'power': { + 'string': 'Power', + 'type': 'selection', + 'selection': [(p,str(p)) for p in range(2, 10)], + 'required': True + }, + 'date1': { + 'string': 'Start of period', + 'type': 'date', + 'required': True, + 'default': lambda *a: time.strftime('%Y-01-01') + }, + 'date2': { + 'string': 'End of period', + 'type': 'date', + 'required': True, + 'default': lambda *a: time.strftime('%Y-%m-%d') + }, } _result_form = '''
- - - + + + ''' _result_fields = { - 'reconciled': { - 'string': 'Reconciled transactions', - 'type': 'integer', - 'readonly': True - }, - 'unreconciled': { - 'string': 'Not reconciled transactions', - 'type': 'integer', - 'readonly': True - }, + 'reconciled': { + 'string': 'Reconciled transactions', + 'type': 'integer', + 'readonly': True + }, + 'unreconciled': { + 'string': 'Not reconciled transactions', + 'type': 'integer', + 'readonly': True + }, } #TODO: cleanup and comment this code... For now, it is awfulllll # (way too complex, and really slow)... def do_reconcile(cr, uid, credits, debits, max_amount, power, writeoff_acc_id, period_id, journal_id, context={}): - # for one value of a credit, check all debits, and combination of them - # depending on the power. It starts with a power of one and goes up - # to the max power allowed - def check2(value, move_list, power): - def check(value, move_list, power): - for i in range(len(move_list)): - move = move_list[i] - if power == 1: - if abs(value - move[1]) <= max_amount + 0.00001: - return [move[0]] - else: - del move_list[i] - res = check(value - move[1], move_list, power-1) - move_list[i:i] = [move] - if res: - res.append(move[0]) - return res - return False + # for one value of a credit, check all debits, and combination of them + # depending on the power. It starts with a power of one and goes up + # to the max power allowed + def check2(value, move_list, power): + def check(value, move_list, power): + for i in range(len(move_list)): + move = move_list[i] + if power == 1: + if abs(value - move[1]) <= max_amount + 0.00001: + return [move[0]] + else: + del move_list[i] + res = check(value - move[1], move_list, power-1) + move_list[i:i] = [move] + if res: + res.append(move[0]) + return res + return False - for p in range(1, power+1): - res = check(value, move_list, p) - if res: - return res - return False + for p in range(1, power+1): + res = check(value, move_list, p) + if res: + return res + return False - # for a list of credit and debit and a given power, check if there - # are matching tuples of credit and debits, check all debits, and combination of them - # depending on the power. It starts with a power of one and goes up - # to the max power allowed - def check4(list1, list2, power): - def check3(value, list1, list2, list1power, power): - for i in range(len(list1)): - move = list1[i] - if list1power == 1: - res = check2(value + move[1], list2, power - 1) - if res: - return ([move[0]], res) - else: - del list1[i] - res = check3(value + move[1], list1, list2, list1power-1, power-1) - list1[i:i] = [move] - if res: - x, y = res - x.append(move[0]) - return (x, y) - return False + # for a list of credit and debit and a given power, check if there + # are matching tuples of credit and debits, check all debits, and combination of them + # depending on the power. It starts with a power of one and goes up + # to the max power allowed + def check4(list1, list2, power): + def check3(value, list1, list2, list1power, power): + for i in range(len(list1)): + move = list1[i] + if list1power == 1: + res = check2(value + move[1], list2, power - 1) + if res: + return ([move[0]], res) + else: + del list1[i] + res = check3(value + move[1], list1, list2, list1power-1, power-1) + list1[i:i] = [move] + if res: + x, y = res + x.append(move[0]) + return (x, y) + return False - for p in range(1, power): - res = check3(0, list1, list2, p, power) - if res: - return res - return False - - def check5(list1, list2, max_power): - for p in range(2, max_power+1): - res = check4(list1, list2, p) - if res: - return res + for p in range(1, power): + res = check3(0, list1, list2, p, power) + if res: + return res + return False + + def check5(list1, list2, max_power): + for p in range(2, max_power+1): + res = check4(list1, list2, p) + if res: + return res - ok = True - reconciled = 0 - move_line_obj = pooler.get_pool(cr.dbname).get('account.move.line') - while credits and debits and ok: - res = check5(credits, debits, power) - if res: - move_line_obj.reconcile(cr, uid, res[0] + res[1], 'auto', writeoff_acc_id, period_id, journal_id, context) - reconciled += len(res[0]) + len(res[1]) - credits = [(id, credit) for (id, credit) in credits if id not in res[0]] - debits = [(id, debit) for (id, debit) in debits if id not in res[1]] - else: - ok = False - return (reconciled, len(credits)+len(debits)) - + ok = True + reconciled = 0 + move_line_obj = pooler.get_pool(cr.dbname).get('account.move.line') + while credits and debits and ok: + res = check5(credits, debits, power) + if res: + move_line_obj.reconcile(cr, uid, res[0] + res[1], 'auto', writeoff_acc_id, period_id, journal_id, context) + reconciled += len(res[0]) + len(res[1]) + credits = [(id, credit) for (id, credit) in credits if id not in res[0]] + debits = [(id, debit) for (id, debit) in debits if id not in res[1]] + else: + ok = False + return (reconciled, len(credits)+len(debits)) + def _reconcile(self, cr, uid, data, context): - service = netsvc.LocalService("object_proxy") - move_line_obj = pooler.get_pool(cr.dbname).get('account.move.line') - form = data['form'] - max_amount = form.get('max_amount', 0.0) - power = form['power'] - reconciled = unreconciled = 0 - if not form['account_ids']: - return {'reconciled':0, 'unreconciled':[0]} - for account_id in form['account_ids'][0][2]: - - # reconcile automatically all transactions from partners whose balance is 0 - cr.execute( - "SELECT partner_id " \ - "FROM account_move_line " \ - "WHERE account_id=%d " \ - "AND reconcile_id IS NULL " \ - "AND state <> 'draft' " \ - "GROUP BY partner_id " \ - "HAVING ABS(SUM(debit-credit)) < %f AND count(*)>0", - (account_id, max_amount)) - partner_ids = [id for (id,) in cr.fetchall()] + service = netsvc.LocalService("object_proxy") + move_line_obj = pooler.get_pool(cr.dbname).get('account.move.line') + form = data['form'] + max_amount = form.get('max_amount', 0.0) + power = form['power'] + reconciled = unreconciled = 0 + if not form['account_ids']: + return {'reconciled':0, 'unreconciled':[0]} + for account_id in form['account_ids'][0][2]: + + # reconcile automatically all transactions from partners whose balance is 0 + cr.execute( + "SELECT partner_id " \ + "FROM account_move_line " \ + "WHERE account_id=%d " \ + "AND reconcile_id IS NULL " \ + "AND state <> 'draft' " \ + "GROUP BY partner_id " \ + "HAVING ABS(SUM(debit-credit)) < %f AND count(*)>0", + (account_id, max_amount)) + partner_ids = [id for (id,) in cr.fetchall()] - for partner_id in partner_ids: - cr.execute( - "SELECT id " \ - "FROM account_move_line " \ - "WHERE account_id=%d " \ - "AND partner_id=%d " \ - "AND state <> 'draft' " \ - "AND reconcile_id IS NULL", - (account_id, partner_id)) - line_ids = [id for (id,) in cr.fetchall()] - - if len(line_ids): - move_line_obj.reconcile(cr, uid, line_ids, 'auto', form['writeoff_acc_id'], form['period_id'], form['journal_id'], context) - reconciled += len(line_ids) - - # get the list of partners who have more than one unreconciled transaction - cr.execute( - "SELECT partner_id " \ - "FROM account_move_line " \ - "WHERE account_id=%d " \ - "AND reconcile_id IS NULL " \ - "AND state <> 'draft' " \ - "GROUP BY partner_id " \ - "HAVING count(*)>1", - (account_id,)) - partner_ids = [id for (id,) in cr.fetchall()] - #filter? - for partner_id in partner_ids: - # get the list of unreconciled 'debit transactions' for this partner - cr.execute( - "SELECT id, debit " \ - "FROM account_move_line " \ - "WHERE account_id=%d " \ - "AND partner_id=%d " \ - "AND reconcile_id IS NULL " \ - "AND state <> 'draft' " \ - "AND debit > 0", - (account_id, partner_id)) - debits = cr.fetchall() - - # get the list of unreconciled 'credit transactions' for this partner - cr.execute( - "SELECT id, credit " \ - "FROM account_move_line " \ - "WHERE account_id=%d " \ - "AND partner_id=%d " \ - "AND reconcile_id IS NULL " \ - "AND state <> 'draft' " \ - "AND credit > 0", - (account_id, partner_id)) - credits = cr.fetchall() - - (rec, unrec) = do_reconcile(cr, uid, credits, debits, max_amount, power, form['writeoff_acc_id'], form['period_id'], form['journal_id'], context) - reconciled += rec - unreconciled += unrec + for partner_id in partner_ids: + cr.execute( + "SELECT id " \ + "FROM account_move_line " \ + "WHERE account_id=%d " \ + "AND partner_id=%d " \ + "AND state <> 'draft' " \ + "AND reconcile_id IS NULL", + (account_id, partner_id)) + line_ids = [id for (id,) in cr.fetchall()] + + if len(line_ids): + move_line_obj.reconcile(cr, uid, line_ids, 'auto', form['writeoff_acc_id'], form['period_id'], form['journal_id'], context) + reconciled += len(line_ids) + + # get the list of partners who have more than one unreconciled transaction + cr.execute( + "SELECT partner_id " \ + "FROM account_move_line " \ + "WHERE account_id=%d " \ + "AND reconcile_id IS NULL " \ + "AND state <> 'draft' " \ + "GROUP BY partner_id " \ + "HAVING count(*)>1", + (account_id,)) + partner_ids = [id for (id,) in cr.fetchall()] + #filter? + for partner_id in partner_ids: + # get the list of unreconciled 'debit transactions' for this partner + cr.execute( + "SELECT id, debit " \ + "FROM account_move_line " \ + "WHERE account_id=%d " \ + "AND partner_id=%d " \ + "AND reconcile_id IS NULL " \ + "AND state <> 'draft' " \ + "AND debit > 0", + (account_id, partner_id)) + debits = cr.fetchall() + + # get the list of unreconciled 'credit transactions' for this partner + cr.execute( + "SELECT id, credit " \ + "FROM account_move_line " \ + "WHERE account_id=%d " \ + "AND partner_id=%d " \ + "AND reconcile_id IS NULL " \ + "AND state <> 'draft' " \ + "AND credit > 0", + (account_id, partner_id)) + credits = cr.fetchall() + + (rec, unrec) = do_reconcile(cr, uid, credits, debits, max_amount, power, form['writeoff_acc_id'], form['period_id'], form['journal_id'], context) + reconciled += rec + unreconciled += unrec - # add the number of transactions for partners who have only one - # unreconciled transactions to the unreconciled count - partner_filter = partner_ids and 'AND partner_id not in (%s)' % ','.join(map(str, filter(None, partner_ids))) or '' - cr.execute( - "SELECT count(*) " \ - "FROM account_move_line " \ - "WHERE account_id=%d " \ - "AND reconcile_id IS NULL " \ - "AND state <> 'draft' " + partner_filter, - (account_id,)) - additional_unrec = cr.fetchone()[0] - return {'reconciled':reconciled, 'unreconciled':unreconciled+additional_unrec} + # add the number of transactions for partners who have only one + # unreconciled transactions to the unreconciled count + partner_filter = partner_ids and 'AND partner_id not in (%s)' % ','.join(map(str, filter(None, partner_ids))) or '' + cr.execute( + "SELECT count(*) " \ + "FROM account_move_line " \ + "WHERE account_id=%d " \ + "AND reconcile_id IS NULL " \ + "AND state <> 'draft' " + partner_filter, + (account_id,)) + additional_unrec = cr.fetchone()[0] + return {'reconciled':reconciled, 'unreconciled':unreconciled+additional_unrec} class wiz_reconcile(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type':'form', 'arch':_reconcile_form, 'fields':_reconcile_fields, 'state':[('end','Cancel'),('reconcile','Reconcile')]} - }, - 'reconcile': { - 'actions': [_reconcile], - 'result': {'type':'form', 'arch':_result_form, 'fields':_result_fields, 'state':[('end','OK')]} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type':'form', 'arch':_reconcile_form, 'fields':_reconcile_fields, 'state':[('end','Cancel'),('reconcile','Reconcile')]} + }, + 'reconcile': { + 'actions': [_reconcile], + 'result': {'type':'form', 'arch':_result_form, 'fields':_result_fields, 'state':[('end','OK')]} + } + } wiz_reconcile('account.automatic.reconcile') diff --git a/addons/account/wizard/wizard_bank_reconcile.py b/addons/account/wizard/wizard_bank_reconcile.py index 30bcea5510b..8b93fdc791e 100644 --- a/addons/account/wizard/wizard_bank_reconcile.py +++ b/addons/account/wizard/wizard_bank_reconcile.py @@ -32,40 +32,40 @@ from tools.translate import _ _journal_form = '''
- + ''' % ('Bank reconciliation',) _journal_fields = { - 'journal_id': {'string':'Journal', 'type':'many2one', 'relation':'account.journal', 'required':True}, + 'journal_id': {'string':'Journal', 'type':'many2one', 'relation':'account.journal', 'required':True}, } def _action_open_window(self, cr, uid, data, context): - form = data['form'] - cr.execute('select default_credit_account_id from account_journal where id=%d', (form['journal_id'],)) - account_id = cr.fetchone()[0] - if not account_id: - raise Exception, _('You have to define the bank account\nin the journal definition for reconciliation.') - return { - 'domain': "[('journal_id','=',%d), ('account_id','=',%d), ('state','<>','draft')]" % (form['journal_id'],account_id), - 'name': 'Saisie Standard', - 'view_type': 'form', - 'view_mode': 'tree,form', - 'res_model': 'account.move.line', - 'view_id': False, - 'context': "{'journal_id':%d}" % (form['journal_id'],), - 'type': 'ir.actions.act_window' - } + form = data['form'] + cr.execute('select default_credit_account_id from account_journal where id=%d', (form['journal_id'],)) + account_id = cr.fetchone()[0] + if not account_id: + raise Exception, _('You have to define the bank account\nin the journal definition for reconciliation.') + return { + 'domain': "[('journal_id','=',%d), ('account_id','=',%d), ('state','<>','draft')]" % (form['journal_id'],account_id), + 'name': 'Saisie Standard', + 'view_type': 'form', + 'view_mode': 'tree,form', + 'res_model': 'account.move.line', + 'view_id': False, + 'context': "{'journal_id':%d}" % (form['journal_id'],), + 'type': 'ir.actions.act_window' + } class wiz_journal(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end','Cancel'),('open','Open for bank reconciliation')]} - }, - 'open': { - 'actions': [], - 'result': {'type': 'action', 'action': _action_open_window, 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end','Cancel'),('open','Open for bank reconciliation')]} + }, + 'open': { + 'actions': [], + 'result': {'type': 'action', 'action': _action_open_window, 'state':'end'} + } + } wiz_journal('account.move.bank.reconcile') diff --git a/addons/account/wizard/wizard_budget_report.py b/addons/account/wizard/wizard_budget_report.py index 1ddc8188ecf..2c1f1214d2f 100644 --- a/addons/account/wizard/wizard_budget_report.py +++ b/addons/account/wizard/wizard_budget_report.py @@ -32,26 +32,26 @@ import wizard dates_form = '''
- - + + ''' dates_fields = { - 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, - 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, + 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, + 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, } class wizard_report(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.budget', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.budget', 'state':'end'} + } + } wizard_report('account.budget.report') diff --git a/addons/account/wizard/wizard_budget_spread.py b/addons/account/wizard/wizard_budget_spread.py index b6431f94b3b..1ca2edf4682 100644 --- a/addons/account/wizard/wizard_budget_spread.py +++ b/addons/account/wizard/wizard_budget_spread.py @@ -32,31 +32,31 @@ import netsvc _spread_form = '''
- - + + ''' _spread_fields = { - 'fiscalyear': {'string':'Fiscal Year', 'type':'many2one', 'relation':'account.fiscalyear', 'required':True}, - 'amount': {'string':'Amount', 'type':'float', 'digits':(16,2)}, + 'fiscalyear': {'string':'Fiscal Year', 'type':'many2one', 'relation':'account.fiscalyear', 'required':True}, + 'amount': {'string':'Amount', 'type':'float', 'digits':(16,2)}, } class wizard_budget_spread(wizard.interface): - def _spread(self, cr, uid, data, context): - service = netsvc.LocalService("object_proxy") - form = data['form'] - res = service.execute(cr.dbname, uid, 'account.budget.post', 'spread', data['ids'], form['fiscalyear'], form['amount']) - return {} + def _spread(self, cr, uid, data, context): + service = netsvc.LocalService("object_proxy") + form = data['form'] + res = service.execute(cr.dbname, uid, 'account.budget.post', 'spread', data['ids'], form['fiscalyear'], form['amount']) + return {} - states = { - 'init': { - 'actions': [], - 'result': {'type':'form', 'arch':_spread_form, 'fields':_spread_fields, 'state':[('end','Cancel'),('spread','Spread')]} - }, - 'spread': { - 'actions': [_spread], - 'result': {'type':'state', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type':'form', 'arch':_spread_form, 'fields':_spread_fields, 'state':[('end','Cancel'),('spread','Spread')]} + }, + 'spread': { + 'actions': [_spread], + 'result': {'type':'state', 'state':'end'} + } + } wizard_budget_spread('account.budget.spread') diff --git a/addons/account/wizard/wizard_fiscalyear_close.py b/addons/account/wizard/wizard_fiscalyear_close.py index 490473af2b5..0b61b28b574 100644 --- a/addons/account/wizard/wizard_fiscalyear_close.py +++ b/addons/account/wizard/wizard_fiscalyear_close.py @@ -34,142 +34,142 @@ from tools.translate import _ _transaction_form = '''
- - - - + + + + - - + + ''' _transaction_fields = { - 'fy_id': {'string':'Fiscal Year to close', 'type':'many2one', 'relation': 'account.fiscalyear','required':True, 'domain':[('state','=','draft')]}, - 'fy2_id': {'string':'New Fiscal Year', 'type':'many2one', 'relation': 'account.fiscalyear', 'domain':[('state','=','draft')], 'required':True}, - 'report_new': {'string':'Create new entries', 'type':'boolean', 'required':True, 'default': lambda *a:True}, - 'report_name': {'string':'Name of new entries', 'type':'char', 'size': 64, 'required':True}, - 'sure': {'string':'Check this box', 'type':'boolean'}, + 'fy_id': {'string':'Fiscal Year to close', 'type':'many2one', 'relation': 'account.fiscalyear','required':True, 'domain':[('state','=','draft')]}, + 'fy2_id': {'string':'New Fiscal Year', 'type':'many2one', 'relation': 'account.fiscalyear', 'domain':[('state','=','draft')], 'required':True}, + 'report_new': {'string':'Create new entries', 'type':'boolean', 'required':True, 'default': lambda *a:True}, + 'report_name': {'string':'Name of new entries', 'type':'char', 'size': 64, 'required':True}, + 'sure': {'string':'Check this box', 'type':'boolean'}, } def _data_load(self, cr, uid, data, context): - data['form']['report_new'] = True - data['form']['report_name'] = 'End of Fiscal Year Entry' - return data['form'] + data['form']['report_new'] = True + data['form']['report_name'] = 'End of Fiscal Year Entry' + return data['form'] def _data_save(self, cr, uid, data, context): - if not data['form']['sure']: - raise wizard.except_wizard(_('UserError'), _('Closing of fiscal year canceled, please check the box !')) - pool = pooler.get_pool(cr.dbname) + if not data['form']['sure']: + raise wizard.except_wizard(_('UserError'), _('Closing of fiscal year canceled, please check the box !')) + pool = pooler.get_pool(cr.dbname) - fy_id = data['form']['fy_id'] - if data['form']['report_new']: - period = pool.get('account.fiscalyear').browse(cr, uid, data['form']['fy2_id']).period_ids[0] - new_fyear = pool.get('account.fiscalyear').browse(cr, uid, data['form']['fy2_id']) - start_jp = new_fyear.start_journal_period_id - if not start_jp: - raise wizard.except_wizard(_('UserError'), - _('The new fiscal year should have a journal for new entries define on it')) + fy_id = data['form']['fy_id'] + if data['form']['report_new']: + period = pool.get('account.fiscalyear').browse(cr, uid, data['form']['fy2_id']).period_ids[0] + new_fyear = pool.get('account.fiscalyear').browse(cr, uid, data['form']['fy2_id']) + start_jp = new_fyear.start_journal_period_id + if not start_jp: + raise wizard.except_wizard(_('UserError'), + _('The new fiscal year should have a journal for new entries define on it')) - new_journal = start_jp.journal_id + new_journal = start_jp.journal_id - if not new_journal.default_credit_account_id or not new_journal.default_debit_account_id: - raise wizard.except_wizard(_('UserError'), - _('The journal must have default credit and debit account')) - if not new_journal.centralisation: - raise wizard.except_wizard(_('UserError'), - _('The journal must have centralised counterpart')) + if not new_journal.default_credit_account_id or not new_journal.default_debit_account_id: + raise wizard.except_wizard(_('UserError'), + _('The journal must have default credit and debit account')) + if not new_journal.centralisation: + raise wizard.except_wizard(_('UserError'), + _('The journal must have centralised counterpart')) - query_line = pool.get('account.move.line')._query_get(cr, uid, - obj='account_move_line', context={'fiscalyear': fy_id}) - cr.execute('select id from account_account WHERE active') - ids = map(lambda x: x[0], cr.fetchall()) - for account in pool.get('account.account').browse(cr, uid, ids, - context={'fiscalyear': fy_id}): - if account.close_method=='none' or account.type == 'view': - continue - if account.close_method=='balance': - if abs(account.balance)>0.0001: - pool.get('account.move.line').create(cr, uid, { - 'debit': account.balance>0 and account.balance, - 'credit': account.balance<0 and -account.balance, - 'name': data['form']['report_name'], - 'date': period.date_start, - 'journal_id': new_journal.id, - 'period_id': period.id, - 'account_id': account.id - }, {'journal_id': new_journal.id, 'period_id':period.id}) - if account.close_method=='unreconciled': - offset = 0 - limit = 100 - while True: - cr.execute('SELECT name, quantity, debit, credit, account_id, ref, ' \ - 'amount_currency, currency_id, blocked, partner_id, ' \ - 'date_maturity, date_created ' \ - 'FROM account_move_line ' \ - 'WHERE account_id = %d ' \ - 'AND ' + query_line + ' ' \ - 'AND reconcile_id is NULL ' \ - 'ORDER BY id ' \ - 'LIMIT %d OFFSET %d', (account.id, limit, offset)) - result = cr.dictfetchall() - if not result: - break - for move in result: - move.update({ - 'date': period.date_start, - 'journal_id': new_journal.id, - 'period_id': period.id, - }) - pool.get('account.move.line').create(cr, uid, move, { - 'journal_id': new_journal.id, - 'period_id': period.id, - }) - offset += limit - if account.close_method=='detail': - offset = 0 - limit = 100 - while True: - cr.execute('SELECT name, quantity, debit, credit, account_id, ref, ' \ - 'amount_currency, currency_id, blocked, partner_id, ' \ - 'date_maturity, date_created ' \ - 'FROM account_move_line ' \ - 'WHERE account_id = %d ' \ - 'AND ' + query_line + ' ' \ - 'ORDER BY id ' \ - 'LIMIT %d OFFSET %d', (account.id,fy_id, limit, offset)) - result = cr.dictfetchall() - if not result: - break - for move in result: - move.update({ - 'date': period.date_start, - 'journal_id': new_journal.id, - 'period_id': period.id, - }) - pool.get('account.move.line').create(cr, uid, move) - offset += limit + query_line = pool.get('account.move.line')._query_get(cr, uid, + obj='account_move_line', context={'fiscalyear': fy_id}) + cr.execute('select id from account_account WHERE active') + ids = map(lambda x: x[0], cr.fetchall()) + for account in pool.get('account.account').browse(cr, uid, ids, + context={'fiscalyear': fy_id}): + if account.close_method=='none' or account.type == 'view': + continue + if account.close_method=='balance': + if abs(account.balance)>0.0001: + pool.get('account.move.line').create(cr, uid, { + 'debit': account.balance>0 and account.balance, + 'credit': account.balance<0 and -account.balance, + 'name': data['form']['report_name'], + 'date': period.date_start, + 'journal_id': new_journal.id, + 'period_id': period.id, + 'account_id': account.id + }, {'journal_id': new_journal.id, 'period_id':period.id}) + if account.close_method=='unreconciled': + offset = 0 + limit = 100 + while True: + cr.execute('SELECT name, quantity, debit, credit, account_id, ref, ' \ + 'amount_currency, currency_id, blocked, partner_id, ' \ + 'date_maturity, date_created ' \ + 'FROM account_move_line ' \ + 'WHERE account_id = %d ' \ + 'AND ' + query_line + ' ' \ + 'AND reconcile_id is NULL ' \ + 'ORDER BY id ' \ + 'LIMIT %d OFFSET %d', (account.id, limit, offset)) + result = cr.dictfetchall() + if not result: + break + for move in result: + move.update({ + 'date': period.date_start, + 'journal_id': new_journal.id, + 'period_id': period.id, + }) + pool.get('account.move.line').create(cr, uid, move, { + 'journal_id': new_journal.id, + 'period_id': period.id, + }) + offset += limit + if account.close_method=='detail': + offset = 0 + limit = 100 + while True: + cr.execute('SELECT name, quantity, debit, credit, account_id, ref, ' \ + 'amount_currency, currency_id, blocked, partner_id, ' \ + 'date_maturity, date_created ' \ + 'FROM account_move_line ' \ + 'WHERE account_id = %d ' \ + 'AND ' + query_line + ' ' \ + 'ORDER BY id ' \ + 'LIMIT %d OFFSET %d', (account.id,fy_id, limit, offset)) + result = cr.dictfetchall() + if not result: + break + for move in result: + move.update({ + 'date': period.date_start, + 'journal_id': new_journal.id, + 'period_id': period.id, + }) + pool.get('account.move.line').create(cr, uid, move) + offset += limit - cr.execute('UPDATE account_journal_period ' \ - 'SET state = %s ' \ - 'WHERE period_id IN (SELECT id FROM account_period WHERE fiscalyear_id = %d)', - ('done',fy_id)) - cr.execute('UPDATE account_period SET state = %s ' \ - 'WHERE fiscalyear_id = %d', ('done',fy_id)) - cr.execute('UPDATE account_fiscalyear ' \ - 'SET state = %s, end_journal_period_id = %d' \ - 'WHERE id = %d', ('done',start_jp,fy_id)) - return {} + cr.execute('UPDATE account_journal_period ' \ + 'SET state = %s ' \ + 'WHERE period_id IN (SELECT id FROM account_period WHERE fiscalyear_id = %d)', + ('done',fy_id)) + cr.execute('UPDATE account_period SET state = %s ' \ + 'WHERE fiscalyear_id = %d', ('done',fy_id)) + cr.execute('UPDATE account_fiscalyear ' \ + 'SET state = %s, end_journal_period_id = %d' \ + 'WHERE id = %d', ('done',start_jp,fy_id)) + return {} class wiz_journal_close(wizard.interface): - states = { - 'init': { - 'actions': [_data_load], - 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Close Fiscal Year')]} - }, - 'close': { - 'actions': [_data_save], - 'result': {'type': 'state', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_data_load], + 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Close Fiscal Year')]} + }, + 'close': { + 'actions': [_data_save], + 'result': {'type': 'state', 'state':'end'} + } + } wiz_journal_close('account.fiscalyear.close') diff --git a/addons/account/wizard/wizard_general_ledger_report.py b/addons/account/wizard/wizard_general_ledger_report.py index a0f4f626b13..080bf493c30 100644 --- a/addons/account/wizard/wizard_general_ledger_report.py +++ b/addons/account/wizard/wizard_general_ledger_report.py @@ -32,31 +32,31 @@ import pooler dates_form = '''
- - + + ''' dates_fields = { - 'fiscalyear': {'string': 'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear', - 'help': 'Keep empty for all open fiscal year'}, - 'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty'} + 'fiscalyear': {'string': 'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear', + 'help': 'Keep empty for all open fiscal year'}, + 'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty'} } class wizard_report(wizard.interface): - def _get_defaults(self, cr, uid, data, context): - fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') - data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) - return data['form'] + def _get_defaults(self, cr, uid, data, context): + fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') + data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) + return data['form'] - states = { - 'init': { - 'actions': [_get_defaults], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.general.ledger', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_get_defaults], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.general.ledger', 'state':'end'} + } + } wizard_report('account.general.ledger.report') diff --git a/addons/account/wizard/wizard_invoice_state.py b/addons/account/wizard/wizard_invoice_state.py index aed413a1309..dd73059c038 100644 --- a/addons/account/wizard/wizard_invoice_state.py +++ b/addons/account/wizard/wizard_invoice_state.py @@ -31,34 +31,34 @@ import wizard import netsvc def _invoice_confirm(self, cr, uid, data, context): - wf_service = netsvc.LocalService('workflow') - for id in data['ids']: - wf_service.trg_validate(uid, 'account.invoice', id, 'invoice_open', cr) - return {} + wf_service = netsvc.LocalService('workflow') + for id in data['ids']: + wf_service.trg_validate(uid, 'account.invoice', id, 'invoice_open', cr) + return {} class wizard_invoice_confirm(wizard.interface): - states = { - 'init': { - 'actions': [_invoice_confirm], - 'result': {'type':'state', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_invoice_confirm], + 'result': {'type':'state', 'state':'end'} + } + } wizard_invoice_confirm('account.invoice.state.confirm') def _invoice_cancel(self, cr, uid, data, context): - wf_service = netsvc.LocalService('workflow') - for id in data['ids']: - wf_service.trg_validate(uid, 'account.invoice', id, 'invoice_cancel', cr) - return {} + wf_service = netsvc.LocalService('workflow') + for id in data['ids']: + wf_service.trg_validate(uid, 'account.invoice', id, 'invoice_cancel', cr) + return {} class wizard_invoice_cancel(wizard.interface): - states = { - 'init': { - 'actions': [_invoice_cancel], - 'result': {'type':'state', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_invoice_cancel], + 'result': {'type':'state', 'state':'end'} + } + } wizard_invoice_cancel('account.invoice.state.cancel') diff --git a/addons/account/wizard/wizard_journal.py b/addons/account/wizard/wizard_journal.py index 5f7693c134a..61554405d88 100644 --- a/addons/account/wizard/wizard_journal.py +++ b/addons/account/wizard/wizard_journal.py @@ -34,65 +34,65 @@ from tools.translate import _ _journal_form = '''
- - - + + + ''' def _period_get(self, cr, uid, datas, ctx={}): - try: - pool = pooler.get_pool(cr.dbname) - ids = pool.get('account.period').find(cr, uid, context=ctx) - return {'period_id': ids[0]} - except: - return {} + try: + pool = pooler.get_pool(cr.dbname) + ids = pool.get('account.period').find(cr, uid, context=ctx) + return {'period_id': ids[0]} + except: + return {} _journal_fields = { - 'journal_id': {'string':'Journal', 'type':'many2one', 'relation':'account.journal', 'required':True}, - 'period_id': { - 'string':'Period', - 'type':'many2one', - 'relation':'account.period', - 'required':True, - } + 'journal_id': {'string':'Journal', 'type':'many2one', 'relation':'account.journal', 'required':True}, + 'period_id': { + 'string':'Period', + 'type':'many2one', + 'relation':'account.period', + 'required':True, + } } def _action_open_window(self, cr, uid, data, context): - form = data['form'] - cr.execute('select id,name from ir_ui_view where model=%s and type=%s', ('account.move.line', 'form')) - view_res = cr.fetchone() - jp = pooler.get_pool(cr.dbname).get('account.journal.period') - ids = jp.search(cr, uid, [('journal_id','=',form['journal_id']), ('period_id','=',form['period_id'])]) - if not len(ids): - name = pooler.get_pool(cr.dbname).get('account.journal').read(cr, uid, [form['journal_id']])[0]['name'] - state = pooler.get_pool(cr.dbname).get('account.period').read(cr, uid, [form['period_id']])[0]['state'] - if state == 'done': - raise wizard.except_wizard(_('UserError'), _('This period is already closed !')) - jp.create(cr, uid, {'name':name, 'period_id': form['period_id'], 'journal_id':form['journal_id']}) - ids = jp.search(cr, uid, [('journal_id','=',form['journal_id']), ('period_id','=',form['period_id'])]) - jp = jp.browse(cr, uid, ids, context=context)[0] - name = (jp.journal_id.code or '') + ':' + (jp.period_id.code or '') - return { - 'domain': "[('journal_id','=',%d), ('period_id','=',%d)]" % (form['journal_id'],form['period_id']), - 'name': name, - 'view_type': 'form', - 'view_mode': 'tree,form', - 'res_model': 'account.move.line', - 'view_id': view_res, - 'context': "{'journal_id':%d, 'period_id':%d}" % (form['journal_id'],form['period_id']), - 'type': 'ir.actions.act_window' - } + form = data['form'] + cr.execute('select id,name from ir_ui_view where model=%s and type=%s', ('account.move.line', 'form')) + view_res = cr.fetchone() + jp = pooler.get_pool(cr.dbname).get('account.journal.period') + ids = jp.search(cr, uid, [('journal_id','=',form['journal_id']), ('period_id','=',form['period_id'])]) + if not len(ids): + name = pooler.get_pool(cr.dbname).get('account.journal').read(cr, uid, [form['journal_id']])[0]['name'] + state = pooler.get_pool(cr.dbname).get('account.period').read(cr, uid, [form['period_id']])[0]['state'] + if state == 'done': + raise wizard.except_wizard(_('UserError'), _('This period is already closed !')) + jp.create(cr, uid, {'name':name, 'period_id': form['period_id'], 'journal_id':form['journal_id']}) + ids = jp.search(cr, uid, [('journal_id','=',form['journal_id']), ('period_id','=',form['period_id'])]) + jp = jp.browse(cr, uid, ids, context=context)[0] + name = (jp.journal_id.code or '') + ':' + (jp.period_id.code or '') + return { + 'domain': "[('journal_id','=',%d), ('period_id','=',%d)]" % (form['journal_id'],form['period_id']), + 'name': name, + 'view_type': 'form', + 'view_mode': 'tree,form', + 'res_model': 'account.move.line', + 'view_id': view_res, + 'context': "{'journal_id':%d, 'period_id':%d}" % (form['journal_id'],form['period_id']), + 'type': 'ir.actions.act_window' + } class wiz_journal(wizard.interface): - states = { - 'init': { - 'actions': [_period_get], - 'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end','Cancel'),('open','Open Journal')]} - }, - 'open': { - 'actions': [], - 'result': {'type': 'action', 'action': _action_open_window, 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_period_get], + 'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end','Cancel'),('open','Open Journal')]} + }, + 'open': { + 'actions': [], + 'result': {'type': 'action', 'action': _action_open_window, 'state':'end'} + } + } wiz_journal('account.move.journal') diff --git a/addons/account/wizard/wizard_journal_select.py b/addons/account/wizard/wizard_journal_select.py index e35c40628a3..20a8ad1cbb7 100644 --- a/addons/account/wizard/wizard_journal_select.py +++ b/addons/account/wizard/wizard_journal_select.py @@ -31,26 +31,26 @@ import wizard import pooler def _action_open_window(self, cr, uid, data, context): - mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data') - act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window') + mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data') + act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window') - result = mod_obj._get_id(cr, uid, 'account', 'action_move_line_select') - id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id'] - result = act_obj.read(cr, uid, [id])[0] + result = mod_obj._get_id(cr, uid, 'account', 'action_move_line_select') + id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id'] + result = act_obj.read(cr, uid, [id])[0] - cr.execute('select journal_id,period_id from account_journal_period where id=%d', (data['id'],)) - journal_id,period_id = cr.fetchone() + cr.execute('select journal_id,period_id from account_journal_period where id=%d', (data['id'],)) + journal_id,period_id = cr.fetchone() - result['domain'] = str([('journal_id', '=', journal_id), ('period_id', '=', period_id)]) - result['context'] = str({'journal_id': journal_id, 'period_id': period_id}) - return result + result['domain'] = str([('journal_id', '=', journal_id), ('period_id', '=', period_id)]) + result['context'] = str({'journal_id': journal_id, 'period_id': period_id}) + return result class wiz_journal(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type': 'action', 'action': _action_open_window, 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type': 'action', 'action': _action_open_window, 'state':'end'} + } + } wiz_journal('account.move.journal.select') diff --git a/addons/account/wizard/wizard_move_line_select.py b/addons/account/wizard/wizard_move_line_select.py index 6642901fbf8..cc1763c9e9b 100644 --- a/addons/account/wizard/wizard_move_line_select.py +++ b/addons/account/wizard/wizard_move_line_select.py @@ -31,35 +31,35 @@ import wizard import pooler class wizard_move_line_select(wizard.interface): - def _open_window(self, cr, uid, data, context): - mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data') - act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window') - fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') + def _open_window(self, cr, uid, data, context): + mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data') + act_obj = pooler.get_pool(cr.dbname).get('ir.actions.act_window') + fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') - if not context.get('fiscalyear', False): - fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')]) - else: - fiscalyear_ids = [context['fiscalyear']] + if not context.get('fiscalyear', False): + fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')]) + else: + fiscalyear_ids = [context['fiscalyear']] - fiscalyears = fiscalyear_obj.browse(cr, uid, fiscalyear_ids) - period_ids = [] - for fiscalyear in fiscalyears: - for period in fiscalyear.period_ids: - period_ids.append(period.id) - domain = str(('period_id', 'in', period_ids)) + fiscalyears = fiscalyear_obj.browse(cr, uid, fiscalyear_ids) + period_ids = [] + for fiscalyear in fiscalyears: + for period in fiscalyear.period_ids: + period_ids.append(period.id) + domain = str(('period_id', 'in', period_ids)) - result = mod_obj._get_id(cr, uid, 'account', 'action_move_line_tree1') - id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id'] - result = act_obj.read(cr, uid, [id])[0] - result['context'] = str({'fiscalyear': context.get('fiscalyear', False)}) - result['domain']=result['domain'][0:-1]+','+domain+result['domain'][-1] - return result + result = mod_obj._get_id(cr, uid, 'account', 'action_move_line_tree1') + id = mod_obj.read(cr, uid, [result], ['res_id'])[0]['res_id'] + result = act_obj.read(cr, uid, [id])[0] + result['context'] = str({'fiscalyear': context.get('fiscalyear', False)}) + result['domain']=result['domain'][0:-1]+','+domain+result['domain'][-1] + return result - states = { - 'init': { - 'actions': [], - 'result': {'type': 'action', 'action': _open_window, 'state': 'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type': 'action', 'action': _open_window, 'state': 'end'} + } + } wizard_move_line_select('account.move.line.select') diff --git a/addons/account/wizard/wizard_open_closed_fiscalyear.py b/addons/account/wizard/wizard_open_closed_fiscalyear.py index 0e2549e3e93..c758498bf76 100644 --- a/addons/account/wizard/wizard_open_closed_fiscalyear.py +++ b/addons/account/wizard/wizard_open_closed_fiscalyear.py @@ -33,53 +33,53 @@ from tools.translate import _ form = """
- + """ fields = { - 'fyear_id': {'string': 'Fiscal Year to Open', 'type': 'many2one', 'relation': 'account.fiscalyear', 'required': True}, + 'fyear_id': {'string': 'Fiscal Year to Open', 'type': 'many2one', 'relation': 'account.fiscalyear', 'required': True}, } def _remove_entries(self, cr, uid, data, context): - pool = pooler.get_pool(cr.dbname) - data_fyear = pool.get('account.fiscalyear').browse(cr,uid,data['form']['fyear_id']) - if not data_fyear.end_journal_period_id: - raise wizard.except_wizard(_('Error'), _('No journal for ending writings have been defined for the fiscal year')) - period_journal = data_fyear.end_journal_period_id - if not period_journal.journal_id.centralisation: - raise wizard.except_wizard(_('UserError'), _('The journal must have centralised counterpart')) - ids_move = pool.get('account.move').search(cr,uid,[('journal_id','=',period_journal.journal_id.id),('period_id','=',period_journal.period_id.id)]) - pool.get('account.move').unlink(cr,uid,ids_move) - cr.execute('UPDATE account_journal_period ' \ - 'SET state = %s ' \ - 'WHERE period_id IN (SELECT id FROM account_period WHERE fiscalyear_id = %d)', - ('draft',data_fyear)) - cr.execute('UPDATE account_period SET state = %s ' \ - 'WHERE fiscalyear_id = %d', ('draft',data_fyear)) - cr.execute('UPDATE account_fiscalyear ' \ - 'SET state = %s, end_journal_period_id = null '\ - 'WHERE id = %d', ('draft',data_fyear)) - return {} + pool = pooler.get_pool(cr.dbname) + data_fyear = pool.get('account.fiscalyear').browse(cr,uid,data['form']['fyear_id']) + if not data_fyear.end_journal_period_id: + raise wizard.except_wizard(_('Error'), _('No journal for ending writings have been defined for the fiscal year')) + period_journal = data_fyear.end_journal_period_id + if not period_journal.journal_id.centralisation: + raise wizard.except_wizard(_('UserError'), _('The journal must have centralised counterpart')) + ids_move = pool.get('account.move').search(cr,uid,[('journal_id','=',period_journal.journal_id.id),('period_id','=',period_journal.period_id.id)]) + pool.get('account.move').unlink(cr,uid,ids_move) + cr.execute('UPDATE account_journal_period ' \ + 'SET state = %s ' \ + 'WHERE period_id IN (SELECT id FROM account_period WHERE fiscalyear_id = %d)', + ('draft',data_fyear)) + cr.execute('UPDATE account_period SET state = %s ' \ + 'WHERE fiscalyear_id = %d', ('draft',data_fyear)) + cr.execute('UPDATE account_fiscalyear ' \ + 'SET state = %s, end_journal_period_id = null '\ + 'WHERE id = %d', ('draft',data_fyear)) + return {} class open_closed_fiscal(wizard.interface): - states = { - 'init' : { - 'actions' : [], - 'result': { - 'type': 'form', - 'arch': form, - 'fields': fields, - 'state':[('end','Cancel'),('open','Open')] - } - }, - 'open': { - 'actions': [], - 'result': { - 'type':'action', - 'action':_remove_entries, - 'state':'end' - }, - }, - } + states = { + 'init' : { + 'actions' : [], + 'result': { + 'type': 'form', + 'arch': form, + 'fields': fields, + 'state':[('end','Cancel'),('open','Open')] + } + }, + 'open': { + 'actions': [], + 'result': { + 'type':'action', + 'action':_remove_entries, + 'state':'end' + }, + }, + } open_closed_fiscal("account.open_closed_fiscalyear") diff --git a/addons/account/wizard/wizard_partner_balance_report.py b/addons/account/wizard/wizard_partner_balance_report.py index 689f6cbc39a..49979b1098b 100644 --- a/addons/account/wizard/wizard_partner_balance_report.py +++ b/addons/account/wizard/wizard_partner_balance_report.py @@ -33,45 +33,45 @@ import pooler dates_form = '''
- - - - - - + + + + + + ''' dates_fields = { - 'company_id': {'string': 'Company', 'type': 'many2one', 'relation': 'res.company', 'required': True}, - 'fiscalyear': {'string': 'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear', - 'help': 'Keep empty for all open fiscal year'}, - 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, - 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, + 'company_id': {'string': 'Company', 'type': 'many2one', 'relation': 'res.company', 'required': True}, + 'fiscalyear': {'string': 'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear', + 'help': 'Keep empty for all open fiscal year'}, + 'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')}, + 'date2': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}, } class wizard_report(wizard.interface): - def _get_defaults(self, cr, uid, data, context): - fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') - data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) + def _get_defaults(self, cr, uid, data, context): + fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear') + data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid) - user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid, context=context) - if user.company_id: - company_id = user.company_id.id - else: - company_id = pooler.get_pool(cr.dbname).get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] - data['form']['company_id'] = company_id + user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid, context=context) + if user.company_id: + company_id = user.company_id.id + else: + company_id = pooler.get_pool(cr.dbname).get('res.company').search(cr, uid, [('parent_id', '=', False)])[0] + data['form']['company_id'] = company_id - return data['form'] + return data['form'] - states = { - 'init': { - 'actions': [_get_defaults], - 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print') ]} - }, - 'report': { - 'actions': [], - 'result': {'type':'print', 'report':'account.partner.balance', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_get_defaults], + 'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print') ]} + }, + 'report': { + 'actions': [], + 'result': {'type':'print', 'report':'account.partner.balance', 'state':'end'} + } + } wizard_report('account.partner.balance.report') diff --git a/addons/account/wizard/wizard_pay_invoice.py b/addons/account/wizard/wizard_pay_invoice.py index adfc7211b0a..1971a98bffe 100644 --- a/addons/account/wizard/wizard_pay_invoice.py +++ b/addons/account/wizard/wizard_pay_invoice.py @@ -35,105 +35,105 @@ from tools.translate import _ pay_form = '''
- - - - - - + + + + + + ''' pay_fields = { - 'amount': {'string': 'Amount paid', 'type':'float', 'required':True}, - 'name': {'string': 'Entry Name', 'type':'char', 'size': 64, 'required':True}, - 'date': {'string': 'Payment date', 'type':'date', 'required':True, 'default':lambda *args: time.strftime('%Y-%m-%d')}, - 'journal_id': {'string': 'Journal', 'type': 'many2one', 'relation':'account.journal', 'required':True, 'domain':[('type','=','cash')]}, - 'period_id': {'string': 'Period', 'type': 'many2one', 'relation':'account.period', 'required':True}, + 'amount': {'string': 'Amount paid', 'type':'float', 'required':True}, + 'name': {'string': 'Entry Name', 'type':'char', 'size': 64, 'required':True}, + 'date': {'string': 'Payment date', 'type':'date', 'required':True, 'default':lambda *args: time.strftime('%Y-%m-%d')}, + 'journal_id': {'string': 'Journal', 'type': 'many2one', 'relation':'account.journal', 'required':True, 'domain':[('type','=','cash')]}, + 'period_id': {'string': 'Period', 'type': 'many2one', 'relation':'account.period', 'required':True}, } def _pay_and_reconcile(self, cr, uid, data, context): - form = data['form'] - period_id = form.get('period_id', False) - journal_id = form.get('journal_id', False) - writeoff_account_id = form.get('writeoff_acc_id', False) - writeoff_journal_id = form.get('writeoff_journal_id', False) - pool = pooler.get_pool(cr.dbname) - cur_obj = pool.get('res.currency') - amount = form['amount'] + form = data['form'] + period_id = form.get('period_id', False) + journal_id = form.get('journal_id', False) + writeoff_account_id = form.get('writeoff_acc_id', False) + writeoff_journal_id = form.get('writeoff_journal_id', False) + pool = pooler.get_pool(cr.dbname) + cur_obj = pool.get('res.currency') + amount = form['amount'] - invoice = pool.get('account.invoice').browse(cr, uid, data['id'], context) - journal = pool.get('account.journal').browse(cr, uid, data['form']['journal_id'], context) - if journal.currency and invoice.company_id.currency_id.id<>journal.currency.id: - ctx = {'date':data['form']['date']} - amount = cur_obj.compute(cr, uid, journal.currency.id, invoice.company_id.currency_id.id, amount, context=ctx) + invoice = pool.get('account.invoice').browse(cr, uid, data['id'], context) + journal = pool.get('account.journal').browse(cr, uid, data['form']['journal_id'], context) + if journal.currency and invoice.company_id.currency_id.id<>journal.currency.id: + ctx = {'date':data['form']['date']} + amount = cur_obj.compute(cr, uid, journal.currency.id, invoice.company_id.currency_id.id, amount, context=ctx) - acc_id = journal.default_credit_account_id and journal.default_credit_account_id.id - if not acc_id: - raise wizard.except_wizard(_('Error !'), _('Your journal must have a default credit and debit account.')) - pool.get('account.invoice').pay_and_reconcile(cr, uid, [data['id']], - amount, acc_id, period_id, journal_id, writeoff_account_id, - period_id, writeoff_journal_id, context, data['form']['name']) - return {} + acc_id = journal.default_credit_account_id and journal.default_credit_account_id.id + if not acc_id: + raise wizard.except_wizard(_('Error !'), _('Your journal must have a default credit and debit account.')) + pool.get('account.invoice').pay_and_reconcile(cr, uid, [data['id']], + amount, acc_id, period_id, journal_id, writeoff_account_id, + period_id, writeoff_journal_id, context, data['form']['name']) + return {} def _wo_check(self, cr, uid, data, context): - pool = pooler.get_pool(cr.dbname) - invoice = pool.get('account.invoice').browse(cr, uid, data['id'], context) - journal = pool.get('account.journal').browse(cr, uid, data['form']['journal_id'], context) - if invoice.company_id.currency_id.id<>journal.currency.id: - return 'addendum' - if pool.get('res.currency').is_zero(cr, uid, invoice.currency_id, - (data['form']['amount'] - invoice.amount_total)): - return 'reconcile' - return 'addendum' + pool = pooler.get_pool(cr.dbname) + invoice = pool.get('account.invoice').browse(cr, uid, data['id'], context) + journal = pool.get('account.journal').browse(cr, uid, data['form']['journal_id'], context) + if invoice.company_id.currency_id.id<>journal.currency.id: + return 'addendum' + if pool.get('res.currency').is_zero(cr, uid, invoice.currency_id, + (data['form']['amount'] - invoice.amount_total)): + return 'reconcile' + return 'addendum' _transaction_add_form = '''
- - - + + + ''' _transaction_add_fields = { - 'writeoff_acc_id': {'string':'Write-Off account', 'type':'many2one', 'relation':'account.account', 'required':True}, - 'writeoff_journal_id': {'string': 'Write-Off journal', 'type': 'many2one', 'relation':'account.journal', 'required':True}, + 'writeoff_acc_id': {'string':'Write-Off account', 'type':'many2one', 'relation':'account.account', 'required':True}, + 'writeoff_journal_id': {'string': 'Write-Off journal', 'type': 'many2one', 'relation':'account.journal', 'required':True}, } def _get_value_addendum(self, cr, uid, data, context={}): - return {} + return {} def _get_period(self, cr, uid, data, context={}): - pool = pooler.get_pool(cr.dbname) - ids = pool.get('account.period').find(cr, uid, context=context) - period_id = False - if len(ids): - period_id = ids[0] - invoice = pool.get('account.invoice').browse(cr, uid, data['id'], context) - if invoice.state == 'draft': - raise wizard.except_wizard(_('Error !'), _('Can not pay draft invoice.')) - return { - 'period_id': period_id, - 'amount': invoice.amount_total, - 'date': time.strftime('%Y-%m-%d') - } + pool = pooler.get_pool(cr.dbname) + ids = pool.get('account.period').find(cr, uid, context=context) + period_id = False + if len(ids): + period_id = ids[0] + invoice = pool.get('account.invoice').browse(cr, uid, data['id'], context) + if invoice.state == 'draft': + raise wizard.except_wizard(_('Error !'), _('Can not pay draft invoice.')) + return { + 'period_id': period_id, + 'amount': invoice.amount_total, + 'date': time.strftime('%Y-%m-%d') + } class wizard_pay_invoice(wizard.interface): - states = { - 'init': { - 'actions': [_get_period], - 'result': {'type':'form', 'arch':pay_form, 'fields':pay_fields, 'state':[('end','Cancel'),('reconcile','Partial Payment'),('writeoff_check','Full Payment')]} - }, - 'writeoff_check': { - 'actions': [], - 'result' : {'type': 'choice', 'next_state': _wo_check } - }, - 'addendum': { - 'actions': [_get_value_addendum], - 'result': {'type': 'form', 'arch':_transaction_add_form, 'fields':_transaction_add_fields, 'state':[('end','Cancel'),('reconcile','Pay and reconcile')]} - }, - 'reconcile': { - 'actions': [_pay_and_reconcile], - 'result': {'type':'state', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [_get_period], + 'result': {'type':'form', 'arch':pay_form, 'fields':pay_fields, 'state':[('end','Cancel'),('reconcile','Partial Payment'),('writeoff_check','Full Payment')]} + }, + 'writeoff_check': { + 'actions': [], + 'result' : {'type': 'choice', 'next_state': _wo_check } + }, + 'addendum': { + 'actions': [_get_value_addendum], + 'result': {'type': 'form', 'arch':_transaction_add_form, 'fields':_transaction_add_fields, 'state':[('end','Cancel'),('reconcile','Pay and reconcile')]} + }, + 'reconcile': { + 'actions': [_pay_and_reconcile], + 'result': {'type':'state', 'state':'end'} + } + } wizard_pay_invoice('account.invoice.pay') diff --git a/addons/account/wizard/wizard_period_close.py b/addons/account/wizard/wizard_period_close.py index ff32fce3284..a7d15f154a0 100644 --- a/addons/account/wizard/wizard_period_close.py +++ b/addons/account/wizard/wizard_period_close.py @@ -31,32 +31,32 @@ import wizard _transaction_form = '''
- - + + ''' _transaction_fields = { - 'sure': {'string':'Check this box', 'type':'boolean'}, + 'sure': {'string':'Check this box', 'type':'boolean'}, } def _data_save(self, cr, uid, data, context): - mode = 'done' - if data['form']['sure']: - for id in data['ids']: - cr.execute('update account_journal_period set state=%s where period_id=%d', (mode, id)) - cr.execute('update account_period set state=%s where id=%d', (mode, id)) - return {} + mode = 'done' + if data['form']['sure']: + for id in data['ids']: + cr.execute('update account_journal_period set state=%s where period_id=%d', (mode, id)) + cr.execute('update account_period set state=%s where id=%d', (mode, id)) + return {} class wiz_journal_close(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Close Period')]} - }, - 'close': { - 'actions': [_data_save], - 'result': {'type': 'state', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Close Period')]} + }, + 'close': { + 'actions': [_data_save], + 'result': {'type': 'state', 'state':'end'} + } + } wiz_journal_close('account.period.close') diff --git a/addons/account/wizard/wizard_reconcile.py b/addons/account/wizard/wizard_reconcile.py index b4fe58063d2..d67ddf168fe 100644 --- a/addons/account/wizard/wizard_reconcile.py +++ b/addons/account/wizard/wizard_reconcile.py @@ -35,108 +35,108 @@ import pooler _transaction_form = '''
- - - - - - - + + + + + + + ''' _transaction_fields = { - 'trans_nbr': {'string':'# of Transaction', 'type':'integer', 'readonly':True}, - 'credit': {'string':'Credit amount', 'type':'float', 'readonly':True}, - 'debit': {'string':'Debit amount', 'type':'float', 'readonly':True}, - 'writeoff': {'string':'Write-Off amount', 'type':'float', 'readonly':True}, + 'trans_nbr': {'string':'# of Transaction', 'type':'integer', 'readonly':True}, + 'credit': {'string':'Credit amount', 'type':'float', 'readonly':True}, + 'debit': {'string':'Debit amount', 'type':'float', 'readonly':True}, + 'writeoff': {'string':'Write-Off amount', 'type':'float', 'readonly':True}, } def _trans_rec_get(self, cr, uid, data, context=None): - pool = pooler.get_pool(cr.dbname) - account_move_line_obj = pool.get('account.move.line') - credit = debit = 0 - account_id = False - count = 0 - for line in account_move_line_obj.browse(cr, uid, data['ids'], context=context): - if not line.reconcile_id and not line.reconcile_id.id: - count += 1 - credit += line.credit - debit += line.debit - account_id = line.account_id.id - return {'trans_nbr': count, 'account_id': account_id, 'credit': credit, 'debit': debit, 'writeoff': debit - credit} + pool = pooler.get_pool(cr.dbname) + account_move_line_obj = pool.get('account.move.line') + credit = debit = 0 + account_id = False + count = 0 + for line in account_move_line_obj.browse(cr, uid, data['ids'], context=context): + if not line.reconcile_id and not line.reconcile_id.id: + count += 1 + credit += line.credit + debit += line.debit + account_id = line.account_id.id + return {'trans_nbr': count, 'account_id': account_id, 'credit': credit, 'debit': debit, 'writeoff': debit - credit} def _trans_rec_reconcile_partial(self, cr, uid, data, context=None): - pool = pooler.get_pool(cr.dbname) - account_move_line_obj = pool.get('account.move.line') - account_move_line_obj.reconcile_partial(cr, uid, data['ids'], 'manual', context=context) - return {} + pool = pooler.get_pool(cr.dbname) + account_move_line_obj = pool.get('account.move.line') + account_move_line_obj.reconcile_partial(cr, uid, data['ids'], 'manual', context=context) + return {} def _trans_rec_reconcile(self, cr, uid, data, context=None): - pool = pooler.get_pool(cr.dbname) - account_move_line_obj = pool.get('account.move.line') + pool = pooler.get_pool(cr.dbname) + account_move_line_obj = pool.get('account.move.line') - form = data['form'] - account_id = form.get('writeoff_acc_id', False) - period_id = form.get('period_id', False) - journal_id = form.get('journal_id', False) - account_move_line_obj.reconcile(cr, uid, data['ids'], 'manual', account_id, - period_id, journal_id, context=context) - return {} + form = data['form'] + account_id = form.get('writeoff_acc_id', False) + period_id = form.get('period_id', False) + journal_id = form.get('journal_id', False) + account_move_line_obj.reconcile(cr, uid, data['ids'], 'manual', account_id, + period_id, journal_id, context=context) + return {} def _partial_check(self, cr, uid, data, context): - if _trans_rec_get(self,cr,uid, data, context)['writeoff'] == 0: - return 'init_full' - return 'init_partial' + if _trans_rec_get(self,cr,uid, data, context)['writeoff'] == 0: + return 'init_full' + return 'init_partial' _transaction_add_form = '''
- - - - + + + + ''' _transaction_add_fields = { - 'journal_id': {'string': 'Write-Off Journal', 'type': 'many2one', 'relation':'account.journal', 'required':True}, - 'period_id': {'string': 'Write-Off Period', 'type': 'many2one', 'relation':'account.period', 'required':True}, - 'writeoff_acc_id': {'string':'Write-Off account', 'type':'many2one', 'relation':'account.account', 'required':True}, + 'journal_id': {'string': 'Write-Off Journal', 'type': 'many2one', 'relation':'account.journal', 'required':True}, + 'period_id': {'string': 'Write-Off Period', 'type': 'many2one', 'relation':'account.period', 'required':True}, + 'writeoff_acc_id': {'string':'Write-Off account', 'type':'many2one', 'relation':'account.account', 'required':True}, } def _trans_rec_addendum(self, cr, uid, data, context={}): - pool = pooler.get_pool(cr.dbname) - ids = pool.get('account.period').find(cr, uid, context=context) - period_id = False - if len(ids): - period_id = ids[0] - return {'period_id':period_id} + pool = pooler.get_pool(cr.dbname) + ids = pool.get('account.period').find(cr, uid, context=context) + period_id = False + if len(ids): + period_id = ids[0] + return {'period_id':period_id} class wiz_reconcile(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type': 'choice', 'next_state': _partial_check} - }, - 'init_full': { - 'actions': [_trans_rec_get], - 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('reconcile','Reconcile')]} - }, - 'init_partial': { - 'actions': [_trans_rec_get], - 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('addendum','Reconcile With Write-Off'),('partial','Partial Reconcile')]} - }, - 'addendum': { - 'actions': [_trans_rec_addendum], - 'result': {'type': 'form', 'arch':_transaction_add_form, 'fields':_transaction_add_fields, 'state':[('end','Cancel'),('reconcile','Reconcile')]} - }, - 'reconcile': { - 'actions': [_trans_rec_reconcile], - 'result': {'type': 'state', 'state':'end'} - }, - 'partial': { - 'actions': [_trans_rec_reconcile_partial], - 'result': {'type': 'state', 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type': 'choice', 'next_state': _partial_check} + }, + 'init_full': { + 'actions': [_trans_rec_get], + 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('reconcile','Reconcile')]} + }, + 'init_partial': { + 'actions': [_trans_rec_get], + 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('addendum','Reconcile With Write-Off'),('partial','Partial Reconcile')]} + }, + 'addendum': { + 'actions': [_trans_rec_addendum], + 'result': {'type': 'form', 'arch':_transaction_add_form, 'fields':_transaction_add_fields, 'state':[('end','Cancel'),('reconcile','Reconcile')]} + }, + 'reconcile': { + 'actions': [_trans_rec_reconcile], + 'result': {'type': 'state', 'state':'end'} + }, + 'partial': { + 'actions': [_trans_rec_reconcile_partial], + 'result': {'type': 'state', 'state':'end'} + } + } wiz_reconcile('account.move.line.reconcile') diff --git a/addons/account/wizard/wizard_reconcile_select.py b/addons/account/wizard/wizard_reconcile_select.py index be3849666e3..1ec1a675226 100644 --- a/addons/account/wizard/wizard_reconcile_select.py +++ b/addons/account/wizard/wizard_reconcile_select.py @@ -31,34 +31,34 @@ import wizard _journal_form = '''
- + ''' % ('Reconciliation',) _journal_fields = { - 'account_id': {'string':'Account', 'type':'many2one', 'relation':'account.account','domain': [('reconcile','=',1)], 'required':True}, + 'account_id': {'string':'Account', 'type':'many2one', 'relation':'account.account','domain': [('reconcile','=',1)], 'required':True}, } def _action_open_window(self, cr, uid, data, context): - return { - 'domain': "[('account_id','=',%d),('reconcile_id','=',False),('state','<>','draft')]" % data['form']['account_id'], - 'name': 'Reconciliation', - 'view_type': 'form', - 'view_mode': 'tree,form', - 'view_id': False, - 'res_model': 'account.move.line', - 'type': 'ir.actions.act_window' - } + return { + 'domain': "[('account_id','=',%d),('reconcile_id','=',False),('state','<>','draft')]" % data['form']['account_id'], + 'name': 'Reconciliation', + 'view_type': 'form', + 'view_mode': 'tree,form', + 'view_id': False, + 'res_model': 'account.move.line', + 'type': 'ir.actions.act_window' + } class wiz_rec_select(wizard.interface): - states = { - 'init': { - 'actions': [], - 'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end','Cancel'),('open','Open for reconciliation')]} - }, - 'open': { - 'actions': [], - 'result': {'type': 'action', 'action': _action_open_window, 'state':'end'} - } - } + states = { + 'init': { + 'actions': [], + 'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end','Cancel'),('open','Open for reconciliation')]} + }, + 'open': { + 'actions': [], + 'result': {'type': 'action', 'action': _action_open_window, 'state':'end'} + } + } wiz_rec_select('account.move.line.reconcile.select') diff --git a/addons/account/wizard/wizard_refund.py b/addons/account/wizard/wizard_refund.py index 81b653c9939..f65d82d4402 100644 --- a/addons/account/wizard/wizard_refund.py +++ b/addons/account/wizard/wizard_refund.py @@ -32,35 +32,35 @@ import pooler sur_form = '''
-