[CLEAN] Set Withespaces to PEP8 format

bzr revid: greg-apieum-20100224085404-j1onx0jxchv3m51a
This commit is contained in:
greg-apieum 2010-02-24 09:54:04 +01:00
parent 5ce261d56e
commit f15d0a6895
628 changed files with 14215 additions and 14216 deletions

File diff suppressed because it is too large Load Diff

View File

@ -30,12 +30,12 @@ from tools import config
class account_analytic_line(osv.osv):
_name = 'account.analytic.line'
_description = 'Analytic lines'
def _amount_currency(self, cr, uid, ids, field_name, arg, context={}):
result = {}
for rec in self.browse(cr, uid, ids, context):
cmp_cur_id=rec.company_id.currency_id.id
aa_cur_id=rec.account_id.currency_id.id
cmp_cur_id = rec.company_id.currency_id.id
aa_cur_id = rec.account_id.currency_id.id
# Always provide the amount in currency
if cmp_cur_id != aa_cur_id:
cur_obj = self.pool.get('res.currency')
@ -46,23 +46,23 @@ class account_analytic_line(osv.osv):
rec.account_id.currency_id.id, rec.amount,
context=ctx)
else:
result[rec.id]=rec.amount
result[rec.id] = rec.amount
return result
def _get_account_currency(self, cr, uid, ids, field_name, arg, context={}):
result = {}
for rec in self.browse(cr, uid, ids, context):
# Always provide second currency
result[rec.id] = (rec.account_id.currency_id.id,rec.account_id.currency_id.code)
result[rec.id] = (rec.account_id.currency_id.id, rec.account_id.currency_id.code)
return result
def _get_account_line(self, cr, uid, ids, context={}):
aac_ids = {}
for acc in self.pool.get('account.analytic.account').browse(cr, uid, ids):
aac_ids[acc.id] = True
aal_ids = []
if aac_ids:
aal_ids = self.pool.get('account.analytic.line').search(cr, uid, [('account_id','in',aac_ids.keys())], context=context)
aal_ids = self.pool.get('account.analytic.line').search(cr, uid, [('account_id', 'in', aac_ids.keys())], context=context)
return aal_ids
_columns = {
@ -81,37 +81,37 @@ class account_analytic_line(osv.osv):
'currency_id': fields.function(_get_account_currency, method=True, type='many2one', relation='res.currency', string='Account currency',
store={
'account.analytic.account': (_get_account_line, ['company_id'], 50),
'account.analytic.line': (lambda self,cr,uid,ids,c={}: ids, ['amount','unit_amount'],10),
'account.analytic.line': (lambda self, cr, uid, ids, c={}: ids, ['amount', 'unit_amount'], 10),
},
help="The related account currency if not equal to the company one."),
'company_id': fields.many2one('res.company','Company',required=True),
'company_id': fields.many2one('res.company', 'Company', required=True),
'amount_currency': fields.function(_amount_currency, method=True, digits=(16, int(config['price_accuracy'])), string='Amount currency',
store={
'account.analytic.account': (_get_account_line, ['company_id'], 50),
'account.analytic.line': (lambda self,cr,uid,ids,c={}: ids, ['amount','unit_amount'],10),
'account.analytic.line': (lambda self, cr, uid, ids, c={}: ids, ['amount', 'unit_amount'], 10),
},
help="The amount expressed in the related account currency if not equal to the company one."),
'ref': fields.char('Ref.', size=64),
}
_defaults = {
'date': lambda *a: time.strftime('%Y-%m-%d'),
'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.analytic.line', c),
'date': lambda * a: time.strftime('%Y-%m-%d'),
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.analytic.line', c),
}
_order = 'date'
def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
if context is None:
context = {}
if context.get('from_date',False):
args.append(['date', '>=',context['from_date']])
if context.get('to_date',False):
args.append(['date','<=',context['to_date']])
if context.get('from_date', False):
args.append(['date', '>=', context['from_date']])
if context.get('to_date', False):
args.append(['date', '<=', context['to_date']])
return super(account_analytic_line, self).search(cr, uid, args, offset, limit,
order, context=context, count=count)
def _check_company(self, cr, uid, ids):
lines = self.browse(cr, uid, ids)
for l in lines:
@ -121,16 +121,16 @@ class account_analytic_line(osv.osv):
_constraints = [
# (_check_company, 'You can not create analytic line that is not in the same company than the account line', ['account_id'])
]
# Compute the cost based on the price type define into company
# property_valuation_price_type property
def on_change_unit_amount(self, cr, uid, id, prod_id, unit_amount,company_id,
def on_change_unit_amount(self, cr, uid, id, prod_id, unit_amount, company_id,
unit=False, context=None):
if context==None:
context={}
if context == None:
context = {}
uom_obj = self.pool.get('product.uom')
product_obj = self.pool.get('product.product')
company_obj=self.pool.get('res.company')
company_obj = self.pool.get('res.company')
if prod_id:
prod = product_obj.browse(cr, uid, prod_id)
a = prod.product_tmpl_id.property_account_expense.id
@ -142,15 +142,15 @@ class account_analytic_line(osv.osv):
'for this product: "%s" (id:%d)') % \
(prod.name, prod.id,))
if not company_id:
company_id=company_obj._company_default_get(cr, uid, 'account.analytic.line', context)
# Compute based on pricetype
pricetype=self.pool.get('product.price.type').browse(cr,uid,company_obj.browse(cr,uid,company_id).property_valuation_price_type.id)
amount_unit=prod.price_get(pricetype.field, context)[prod.id]
company_id = company_obj._company_default_get(cr, uid, 'account.analytic.line', context)
amount=amount_unit*unit_amount or 1.0
# Compute based on pricetype
pricetype = self.pool.get('product.price.type').browse(cr, uid, company_obj.browse(cr, uid, company_id).property_valuation_price_type.id)
amount_unit = prod.price_get(pricetype.field, context)[prod.id]
amount = amount_unit * unit_amount or 1.0
return {'value': {
'amount': - round(amount, 2),
'amount':-round(amount, 2),
'general_account_id': a,
}}
return {}
@ -161,7 +161,7 @@ class account_analytic_line(osv.osv):
cr.execute('select name from account_analytic_account where id=%s', (context['account_id'],))
res = cr.fetchone()
if res:
res = _('Entries: ')+ (res[0] or '')
res = _('Entries: ') + (res[0] or '')
return res
return False
@ -173,14 +173,14 @@ class timesheet_invoice(osv.osv):
_description = "Analytic account costs and revenues"
_auto = False
_columns = {
'name': fields.char('Year',size=64,required=False, readonly=True),
'name': fields.char('Year', size=64, required=False, 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),
'month':fields.selection([('01','January'), ('02','February'), ('03','March'), ('04','April'), ('05','May'), ('06','June'),
('07','July'), ('08','August'), ('09','September'), ('10','October'), ('11','November'), ('12','December')],'Month',readonly=True),
'month':fields.selection([('01', 'January'), ('02', 'February'), ('03', 'March'), ('04', 'April'), ('05', 'May'), ('06', 'June'),
('07', 'July'), ('08', 'August'), ('09', 'September'), ('10', 'October'), ('11', 'November'), ('12', 'December')], 'Month', readonly=True),
}
_order = 'name desc, account_id'
def init(self, cr):

View File

@ -114,17 +114,17 @@ class account_bank_statement(osv.osv):
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),
'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', 'Confirmed')],
'Entry lines', states={'confirm':[('readonly', True)]}),
'state': fields.selection([('draft', 'Draft'), ('confirm', 'Confirmed')],
'State', required=True,
states={'confirm': [('readonly', True)]}, readonly="1",
help='When new statement is created the state will be \'Draft\'. \
@ -134,10 +134,10 @@ class account_bank_statement(osv.osv):
}
_defaults = {
'name': lambda self, cr, uid, context=None: \
'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',
'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,
@ -156,7 +156,7 @@ class account_bank_statement(osv.osv):
context=context).company_id.currency_id.id
for st in self.browse(cr, uid, ids, context):
if not st.state=='draft':
if not st.state == 'draft':
continue
if not (abs((st.balance_end or 0.0) - st.balance_end_real) < 0.0001):
@ -183,7 +183,7 @@ class account_bank_statement(osv.osv):
'date': move.date,
}, context=context)
account_bank_statement_line_obj.write(cr, uid, [move.id], {
'move_ids': [(4,move_id, False)]
'move_ids': [(4, move_id, False)]
})
if not move.amount:
continue
@ -193,7 +193,7 @@ class account_bank_statement(osv.osv):
account_id = st.journal_id.default_credit_account_id.id
else:
account_id = st.journal_id.default_debit_account_id.id
acc_cur = ((move.amount<=0) and st.journal_id.default_debit_account_id) or move.account_id
acc_cur = ((move.amount <= 0) and st.journal_id.default_debit_account_id) or move.account_id
amount = res_currency_obj.compute(cr, uid, st.currency.id,
company_currency_id, move.amount, context=context,
account=acc_cur)
@ -208,8 +208,8 @@ class account_bank_statement(osv.osv):
'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,
'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,
@ -227,7 +227,7 @@ class account_bank_statement(osv.osv):
if move.account_id and move.account_id.currency_id and move.account_id.currency_id.id <> company_currency_id:
val['currency_id'] = move.account_id.currency_id.id
if company_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,
@ -246,8 +246,8 @@ class account_bank_statement(osv.osv):
'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,
'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,
@ -269,7 +269,7 @@ class account_bank_statement(osv.osv):
'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,
'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,
@ -289,7 +289,7 @@ class account_bank_statement(osv.osv):
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:
if abs(move.reconcile_amount - move.amount) < 0.0001:
writeoff_acc_id = False
#There should only be one write-off account!
@ -312,7 +312,7 @@ class account_bank_statement(osv.osv):
def button_cancel(self, cr, uid, ids, context={}):
done = []
for st in self.browse(cr, uid, ids, context):
if st.state=='draft':
if st.state == 'draft':
continue
ids = []
for line in st.line_ids:
@ -356,7 +356,7 @@ class account_bank_statement(osv.osv):
raise osv.except_osv(_('Invalid action !'), _('Cannot delete bank statement which are already confirmed !'))
osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
return True
account_bank_statement()
@ -396,10 +396,10 @@ class account_bank_statement_reconcile(osv.osv):
currency_id = context.get('currency_id', company_currency_id)
acc_cur = None
if context.get('journal_id', False) and context.get('account_id',False):
st =self.pool.get('account.journal').browse(cursor, user, context['journal_id'])
if context.get('journal_id', False) and context.get('account_id', False):
st = self.pool.get('account.journal').browse(cursor, user, context['journal_id'])
acc = self.pool.get('account.account').browse(cursor, user, context['account_id'])
acc_cur = (( context.get('amount',0.0)<=0) and st.default_debit_account_id) or acc
acc_cur = ((context.get('amount', 0.0) <= 0) and st.default_debit_account_id) or acc
for reconcile_id in ids:
res[reconcile_id] = res_currency_obj.compute(cursor, user,
@ -418,10 +418,10 @@ class account_bank_statement_reconcile(osv.osv):
currency_id = context.get('currency_id', company_currency_id)
acc_cur = None
if context.get('journal_id', False) and context.get('account_id',False):
st =self.pool.get('account.journal').browse(cursor, user, context['journal_id'])
if context.get('journal_id', False) and context.get('account_id', False):
st = self.pool.get('account.journal').browse(cursor, user, context['journal_id'])
acc = self.pool.get('account.account').browse(cursor, user, context['account_id'])
acc_cur = (( context.get('amount',0.0)<=0) and st.default_debit_account_id) or acc
acc_cur = ((context.get('amount', 0.0) <= 0) and st.default_debit_account_id) or acc
return res_currency_obj.compute(cursor, user,
currency_id, company_currency_id,
@ -459,7 +459,7 @@ class account_bank_statement_reconcile(osv.osv):
return res
def name_get(self, cursor, user, ids, context=None):
res= []
res = []
for o in self.browse(cursor, user, ids, context=context):
result = 0.0
res_currency = ''
@ -471,7 +471,7 @@ class account_bank_statement_reconcile(osv.osv):
result += line.debit - line.credit
if res_currency:
res_currency = ' ' + res_currency
res.append((o.id, '[%.2f'% (result - o.total_new,) + res_currency + ']' ))
res.append((o.id, '[%.2f' % (result - o.total_new,) + res_currency + ']'))
return res
_columns = {
@ -500,14 +500,14 @@ class account_bank_statement_reconcile(osv.osv):
'reconcile_id', 'Bank Statement Line'),
}
_defaults = {
'name': lambda *a: time.strftime('%Y-%m-%d'),
'partner_id': lambda obj, cursor, user, context=None: \
'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: \
'total_second_amount': lambda obj, cursor, user, context = None: \
context.get('amount', 0.0),
'total_second_currency': lambda obj, cursor, user, context=None: \
'total_second_currency': lambda obj, cursor, user, context = None: \
context.get('currency_id', False),
'total_balance': _default_amount,
}
@ -521,10 +521,10 @@ class account_bank_statement_reconcile_line(osv.osv):
'account_id': fields.many2one('account.account', 'Account', required=True),
'line_id': fields.many2one('account.bank.statement.reconcile', 'Reconcile'),
'amount': fields.float('Amount', required=True),
'analytic_id': fields.many2one('account.analytic.account',"Analytic Account")
'analytic_id': fields.many2one('account.analytic.account', "Analytic Account")
}
_defaults = {
'name': lambda *a: 'Write-Off',
'name': lambda * a: 'Write-Off',
}
account_bank_statement_reconcile_line()
@ -549,7 +549,7 @@ class account_bank_statement_line(osv.osv):
if type == 'supplier':
account_id = part.property_account_payable.id
else:
account_id = part.property_account_receivable.id
account_id = part.property_account_receivable.id
cursor.execute('SELECT sum(debit-credit) \
FROM account_move_line \
@ -590,19 +590,19 @@ class account_bank_statement_line(osv.osv):
'date': fields.date('Date', required=True),
'amount': fields.float('Amount'),
'type': fields.selection([
('supplier','Supplier'),
('customer','Customer'),
('general','General')
('supplier', 'Supplier'),
('customer', 'Customer'),
('general', 'General')
], 'Type', required=True),
'partner_id': fields.many2one('res.partner', 'Partner'),
'account_id': fields.many2one('account.account','Account',
'account_id': fields.many2one('account.account', 'Account',
required=True),
'statement_id': fields.many2one('account.bank.statement', 'Statement',
select=True, required=True, ondelete='cascade'),
'reconcile_id': fields.many2one('account.bank.statement.reconcile',
'Reconcile', states={'confirm':[('readonly',True)]}),
'Reconcile', states={'confirm':[('readonly', True)]}),
'move_ids': fields.many2many('account.move',
'account_bank_statement_line_move_rel', 'move_id','statement_id',
'account_bank_statement_line_move_rel', 'move_id', 'statement_id',
'Moves'),
'ref': fields.char('Reference', size=32),
'note': fields.text('Notes'),
@ -611,10 +611,10 @@ class account_bank_statement_line(osv.osv):
'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of bank statement line."),
}
_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',
'sequence': lambda *a: 10,
'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',
'sequence': lambda * a: 10,
}
account_bank_statement_line()

View File

@ -40,23 +40,23 @@ class account_move_line(osv.osv):
fiscalyear_clause = (','.join([str(x) for x in fiscalyear_ids])) or '0'
else:
fiscalyear_clause = '%s' % context['fiscalyear']
state=context.get('state',False)
state = context.get('state', False)
where_move_state = ''
where_move_lines_by_date = ''
if context.get('date_from', False) and context.get('date_to', False):
where_move_lines_by_date = " AND " +obj+".move_id in ( select id from account_move where date >= '" +context['date_from']+"' AND date <= '"+context['date_to']+"')"
where_move_lines_by_date = " AND " + obj + ".move_id in ( select id from account_move where date >= '" + context['date_from'] + "' AND date <= '" + context['date_to'] + "')"
if state:
if state.lower() not in ['all']:
where_move_state= " AND "+obj+".move_id in (select id from account_move where account_move.state = '"+state+"')"
where_move_state = " AND " + obj + ".move_id in (select id from account_move where account_move.state = '" + state + "')"
if context.get('periods', False):
ids = ','.join([str(x) for x in context['periods']])
return obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) AND id in (%s)) %s %s" % (fiscalyear_clause, ids,where_move_state,where_move_lines_by_date)
return obj + ".state<>'draft' AND " + obj + ".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) AND id in (%s)) %s %s" % (fiscalyear_clause, ids, where_move_state, where_move_lines_by_date)
else:
return obj+".state<>'draft' AND "+obj+".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) %s %s)" % (fiscalyear_clause,where_move_state,where_move_lines_by_date)
return obj + ".state<>'draft' AND " + obj + ".period_id in (SELECT id from account_period WHERE fiscalyear_id in (%s) %s %s)" % (fiscalyear_clause, where_move_state, where_move_lines_by_date)
def default_get(self, cr, uid, fields, context={}):
data = self._default_get(cr, uid, fields, context)
@ -69,9 +69,9 @@ class account_move_line(osv.osv):
for obj_line in self.browse(cr, uid, ids, context):
if obj_line.analytic_account_id:
if not obj_line.journal_id.analytic_journal_id:
raise osv.except_osv(_('No Analytic Journal !'),_("You have to define an analytic journal on the '%s' journal!") % (obj_line.journal_id.name,))
raise osv.except_osv(_('No Analytic Journal !'), _("You have to define an analytic journal on the '%s' journal!") % (obj_line.journal_id.name,))
amt = (obj_line.credit or 0.0) - (obj_line.debit or 0.0)
vals_lines={
vals_lines = {
'name': obj_line.name,
'date': obj_line.date,
'account_id': obj_line.analytic_account_id.id,
@ -84,7 +84,7 @@ class account_move_line(osv.osv):
'ref': obj_line.ref,
'move_id':obj_line.id
}
new_id = self.pool.get('account.analytic.line').create(cr,uid,vals_lines)
new_id = self.pool.get('account.analytic.line').create(cr, uid, vals_lines)
return True
def _default_get_move_form_hook(self, cursor, user, data):
@ -99,23 +99,23 @@ class account_move_line(osv.osv):
# Compute simple values
data = super(account_move_line, self).default_get(cr, uid, fields, context)
# Starts: Manual entry from account.move form
if context.get('lines',[]):
if context.get('lines', []):
total_new=0.00
total_new = 0.00
for i in context['lines']:
if i[2]:
total_new +=(i[2]['debit'] or 0.00)- (i[2]['credit'] or 0.00)
total_new += (i[2]['debit'] or 0.00) - (i[2]['credit'] or 0.00)
for item in i[2]:
data[item]=i[2][item]
data[item] = i[2][item]
if context['journal']:
journal_obj=self.pool.get('account.journal').browse(cr,uid,context['journal'])
journal_obj = self.pool.get('account.journal').browse(cr, uid, context['journal'])
if journal_obj.type == 'purchase':
if total_new>0:
if total_new > 0:
account = journal_obj.default_credit_account_id
else:
account = journal_obj.default_debit_account_id
else:
if total_new>0:
if total_new > 0:
account = journal_obj.default_credit_account_id
else:
account = journal_obj.default_debit_account_id
@ -125,11 +125,11 @@ class account_move_line(osv.osv):
part = self.pool.get('res.partner').browse(cr, uid, data['partner_id'])
account = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, account.id)
account = self.pool.get('account.account').browse(cr, uid, account)
data['account_id'] = account.id
data['account_id'] = account.id
s = -total_new
data['debit'] = s>0 and s or 0.0
data['credit'] = s<0 and -s or 0.0
data['debit'] = s > 0 and s or 0.0
data['credit'] = s < 0 and - s or 0.0
data = self._default_get_move_form_hook(cr, uid, data)
return data
# Ends: Manual entry from account.move form
@ -142,7 +142,7 @@ class account_move_line(osv.osv):
# Compute the current move
move_id = False
partner_id = False
if context.get('journal_id',False) and context.get('period_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 \
@ -195,12 +195,12 @@ class account_move_line(osv.osv):
data['partner_id'] = partner_id
if move.journal_id.type == 'purchase':
if total>0:
if total > 0:
account = move.journal_id.default_credit_account_id
else:
account = move.journal_id.default_debit_account_id
else:
if total>0:
if total > 0:
account = move.journal_id.default_credit_account_id
else:
account = move.journal_id.default_debit_account_id
@ -221,13 +221,13 @@ class account_move_line(osv.osv):
total -= t['amount']
s = -total
data['debit'] = s>0 and s or 0.0
data['credit'] = s<0 and -s or 0.0
data['debit'] = s > 0 and s or 0.0
data['credit'] = s < 0 and - s or 0.0
if account and account.currency_id:
data['currency_id'] = account.currency_id.id
acc = account
if s>0:
if s > 0:
acc = acc1
v = self.pool.get('res.currency').compute(cr, uid,
account.company_id.currency_id.id,
@ -241,12 +241,12 @@ class account_move_line(osv.osv):
return map(lambda x: x.id, ml.move_id.line_id)
def _balance(self, cr, uid, ids, prop, unknow_none, unknow_dict):
res={}
res = {}
# TODO group the foreach in sql
for id in ids:
cr.execute('SELECT date,account_id FROM account_move_line WHERE id=%s', (id,))
dt, acc = cr.fetchone()
cr.execute('SELECT SUM(debit-credit) FROM account_move_line WHERE account_id=%s AND (date<%s OR (date=%s AND id<=%s))', (acc,dt,dt,id))
cr.execute('SELECT SUM(debit-credit) FROM account_move_line WHERE account_id=%s AND (date<%s OR (date=%s AND id<=%s))', (acc, dt, dt, id))
res[id] = cr.fetchone()[0]
return res
@ -258,7 +258,7 @@ class account_move_line(osv.osv):
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 =ANY(%s)',(ids,))
'AND l.id =ANY(%s)', (ids,))
invoice_ids = []
for line_id, invoice_id in cursor.fetchall():
res[line_id] = invoice_id
@ -278,7 +278,7 @@ class account_move_line(osv.osv):
result = []
for line in self.browse(cr, uid, ids, context):
if line.ref:
result.append((line.id, (line.name or '')+' ('+line.ref+')'))
result.append((line.id, (line.name or '') + ' (' + line.ref + ')'))
else:
result.append((line.id, line.name))
return result
@ -289,9 +289,9 @@ class account_move_line(osv.osv):
if not len(args):
return []
where = ' and '.join(map(lambda x: '(abs(sum(debit-credit))'+x[1]+str(x[2])+')',args))
where = ' and '.join(map(lambda x: '(abs(sum(debit-credit))' + x[1] + str(x[2]) + ')', args))
cursor.execute('select id, sum(debit-credit) from account_move_line \
group by id,debit,credit having '+where)
group by id,debit,credit having ' + where)
res = cursor.fetchall()
if not len(res):
return [('id', '=', '0')]
@ -352,19 +352,19 @@ class account_move_line(osv.osv):
_columns = {
'name': fields.char('Name', size=64, required=True),
'quantity': fields.float('Quantity', digits=(16,2), help="The optional quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very useful for some reports."),
'quantity': fields.float('Quantity', digits=(16, 2), help="The optional quantity expressed by this line, eg: number of product sold. The quantity is not a legal requirement but is very useful for some reports."),
'product_uom_id': fields.many2one('product.uom', 'UoM'),
'product_id': fields.many2one('product.product', 'Product'),
'debit': fields.float('Debit', digits=(16,int(tools.config['price_accuracy']))),
'credit': fields.float('Credit', digits=(16,int(tools.config['price_accuracy']))),
'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),
'debit': fields.float('Debit', digits=(16, int(tools.config['price_accuracy']))),
'credit': fields.float('Credit', digits=(16, int(tools.config['price_accuracy']))),
'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),
'ref': fields.char('Ref.', size=64),
'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 optional other currency if it is a multi-currency entry.", digits=(16,int(tools.config['price_accuracy']))),
'amount_currency': fields.float('Amount Currency', help="The amount expressed in an optional other currency if it is a multi-currency entry.", digits=(16, int(tools.config['price_accuracy']))),
'currency_id': fields.many2one('res.currency', 'Currency', help="The optional other currency if it is a multi-currency entry."),
'period_id': fields.many2one('account.period', 'Period', required=True, select=2),
@ -373,26 +373,26 @@ class account_move_line(osv.osv):
'partner_id': fields.many2one('res.partner', 'Partner'),
'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.related('move_id','date', string='Effective date', type='date', required=True,
'date': fields.related('move_id', 'date', string='Effective date', type='date', required=True,
store={
'account.move': (_get_move_lines, ['date'], 20)
}),
'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),
'centralisation': fields.selection([('normal', 'Normal'), ('credit', 'Credit Centralisation'), ('debit', 'Debit Centralisation')], 'Centralisation', size=6),
'balance': fields.function(_balance, fnct_search=_balance_search, method=True, string='Balance'),
'state': fields.selection([('draft','Draft'), ('valid','Valid')], 'State', readonly=True,
'state': fields.selection([('draft', 'Draft'), ('valid', 'Valid')], 'State', readonly=True,
help='When new move line is created the state will be \'Draft\'.\n* When all the payments are done it will be in \'Valid\' state.'),
'tax_code_id': fields.many2one('account.tax.code', 'Tax Account', help="The Account can either be a base tax code or a tax code account."),
'tax_amount': fields.float('Tax/Base Amount', digits=(16,int(tools.config['price_accuracy'])), select=True, help="If the Tax account is a tax code account, this field will contain the taxed amount.If the tax account is base tax code, "\
'tax_amount': fields.float('Tax/Base Amount', digits=(16, int(tools.config['price_accuracy'])), select=True, help="If the Tax account is a tax code account, this field will contain the taxed amount.If the tax account is base tax code, "\
"this field will contain the basic amount(without tax)."),
'invoice': fields.function(_invoice, method=True, string='Invoice',
type='many2one', relation='account.invoice', fnct_search=_invoice_search),
'account_tax_id':fields.many2one('account.tax', 'Tax'),
'analytic_account_id' : fields.many2one('account.analytic.account', 'Analytic Account'),
#TODO: remove this
'amount_taxed':fields.float("Taxed Amount",digits=(16,int(tools.config['price_accuracy']))),
'company_id': fields.related('account_id','company_id',type='many2one',relation='res.company',string='Company',store=True)
'amount_taxed':fields.float("Taxed Amount", digits=(16, int(tools.config['price_accuracy']))),
'company_id': fields.related('account_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True)
}
@ -419,19 +419,19 @@ class account_move_line(osv.osv):
return cur and cur.id or False
_defaults = {
'blocked': lambda *a: False,
'centralisation': lambda *a: 'normal',
'blocked': lambda * a: False,
'centralisation': lambda * a: 'normal',
'date': _get_date,
'date_created': lambda *a: time.strftime('%Y-%m-%d'),
'state': lambda *a: 'draft',
'date_created': lambda * a: time.strftime('%Y-%m-%d'),
'state': lambda * a: 'draft',
'currency_id': _get_currency,
'journal_id': lambda self, cr, uid, c: c.get('journal_id', False),
'period_id': lambda self, cr, uid, c: c.get('period_id', False),
'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.move.line', context=c)
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.move.line', context=c)
}
_order = "date desc,id desc"
_sql_constraints = [
('credit_debit1', 'CHECK (credit*debit=0)', 'Wrong credit or debit value in accounting entry !'),
('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 !'),
]
@ -467,14 +467,14 @@ class account_move_line(osv.osv):
if (not currency_id) or (not account_id):
return {}
result = {}
acc =self.pool.get('account.account').browse(cr, uid, account_id)
if (amount>0) and journal:
acc = self.pool.get('account.account').browse(cr, uid, account_id)
if (amount > 0) and journal:
x = self.pool.get('account.journal').browse(cr, uid, journal).default_credit_account_id
if x: acc = x
v = self.pool.get('res.currency').compute(cr, uid, currency_id,acc.company_id.currency_id.id, amount, account=acc)
v = self.pool.get('res.currency').compute(cr, uid, currency_id, acc.company_id.currency_id.id, amount, account=acc)
result['value'] = {
'debit': v>0 and v or 0.0,
'credit': v<0 and -v or 0.0
'debit': v > 0 and v or 0.0,
'credit': v < 0 and - v or 0.0
}
return result
@ -495,13 +495,13 @@ class account_move_line(osv.osv):
val['date_maturity'] = res[0][0]
if not account_id:
id1 = part.property_account_payable.id
id2 = part.property_account_receivable.id
id2 = part.property_account_receivable.id
if journal:
jt = self.pool.get('account.journal').browse(cr, uid, journal).type
if jt=='sale':
if jt == 'sale':
val['account_id'] = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, id2)
elif jt=='purchase':
elif jt == 'purchase':
val['account_id'] = self.pool.get('account.fiscal.position').map_account(cr, uid, part and part.property_account_position or False, id1)
if val.get('account_id', False):
d = self.onchange_account_id(cr, uid, ids, val['account_id'])
@ -546,11 +546,11 @@ class account_move_line(osv.osv):
unmerge.append(line.id)
total += (line.debit or 0.0) - (line.credit or 0.0)
if not total:
res = self.reconcile(cr, uid, merges+unmerge, context=context)
res = self.reconcile(cr, uid, merges + unmerge, context=context)
return res
r_id = self.pool.get('account.move.reconcile').create(cr, uid, {
'type': type,
'line_partial_ids': map(lambda x: (4,x,False), merges+unmerge)
'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
@ -574,14 +574,14 @@ class account_move_line(osv.osv):
writeoff = debit - credit
# Ifdate_p in context => take this date
if context.has_key('date_p') and context['date_p']:
date=context['date_p']
date = context['date_p']
else:
date = time.strftime('%Y-%m-%d')
cr.execute('SELECT account_id, reconcile_id \
FROM account_move_line \
WHERE id =ANY(%s) \
GROUP BY account_id,reconcile_id',(ids,))
GROUP BY account_id,reconcile_id', (ids,))
r = cr.fetchall()
#TODO: move this check to a constraint in the account_move_reconcile object
if (len(r) != 1) and not context.get('fy_closing', False):
@ -611,9 +611,9 @@ class account_move_line(osv.osv):
# If comment exist in context, take it
if 'comment' in context and context['comment']:
libelle=context['comment']
libelle = context['comment']
else:
libelle='Write-Off'
libelle = 'Write-Off'
writeoff_lines = [
(0, 0, {
@ -624,7 +624,7 @@ class account_move_line(osv.osv):
'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
'amount_currency': account.currency_id.id and - currency or 0.0
}),
(0, 0, {
'name':libelle,
@ -651,8 +651,8 @@ class account_move_line(osv.osv):
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)
'line_id': map(lambda x: (4, x, False), ids),
'line_partial_ids': map(lambda x: (3, x, False), ids)
})
wf_service = netsvc.LocalService("workflow")
# the id of the move.reconcile is written in the move.line (self) by the create method above
@ -665,7 +665,7 @@ class account_move_line(osv.osv):
if context.get('account_id', False):
cr.execute('select code from account_account where id=%s', (context['account_id'],))
res = cr.fetchone()
res = _('Entries: ')+ (res[0] or '')
res = _('Entries: ') + (res[0] or '')
return res
if (not context.get('journal_id', False)) or (not context.get('period_id', False)):
return False
@ -674,12 +674,12 @@ class account_move_line(osv.osv):
cr.execute('select code from account_period where id=%s', (context['period_id'],))
p = cr.fetchone()[0] or ''
if j or p:
return j+(p and (':'+p) or '')
return j + (p and (':' + p) or '')
return False
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False, submenu=False):
result = super(osv.osv, self).fields_view_get(cr, uid, view_id,view_type,context,toolbar=toolbar, submenu=submenu)
if view_type=='tree' and 'journal_id' in context:
result = super(osv.osv, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
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'])
@ -687,7 +687,7 @@ class account_move_line(osv.osv):
# its value
state = ''
for field in journal.view_id.columns_id:
if field.field=='state':
if field.field == 'state':
state = ' colors="red:state==\'draft\'"'
#xml = '''<?xml version="1.0"?>\n<tree string="%s" editable="top" refresh="5"%s>\n\t''' % (title, state)
@ -704,14 +704,14 @@ class account_move_line(osv.osv):
for field in journal.view_id.columns_id:
fields.append(field.field)
attrs = []
if field.field=='debit':
if field.field == 'debit':
attrs.append('sum="Total debit"')
elif field.field=='credit':
elif field.field == 'credit':
attrs.append('sum="Total credit"')
elif field.field=='account_tax_id':
elif field.field == 'account_tax_id':
attrs.append('domain="[(\'parent_id\',\'=\',False)]"')
elif field.field=='account_id' and journal.id:
attrs.append('domain="[(\'journal_id\', \'=\', '+str(journal.id)+'),(\'type\',\'&lt;&gt;\',\'view\'), (\'type\',\'&lt;&gt;\',\'closed\')]" on_change="onchange_account_id(account_id, partner_id)"')
elif field.field == 'account_id' and journal.id:
attrs.append('domain="[(\'journal_id\', \'=\', ' + str(journal.id) + '),(\'type\',\'&lt;&gt;\',\'view\'), (\'type\',\'&lt;&gt;\',\'closed\')]" on_change="onchange_account_id(account_id, partner_id)"')
elif field.field == 'partner_id':
attrs.append('on_change="onchange_partner_id(move_id,partner_id,account_id,debit,credit,date,((\'journal_id\' in context) and context[\'journal_id\']) or {})"')
if field.readonly:
@ -720,12 +720,12 @@ class account_move_line(osv.osv):
attrs.append('required="1"')
else:
attrs.append('required="0"')
if field.field in ('amount_currency','currency_id'):
if field.field in ('amount_currency', 'currency_id'):
attrs.append('on_change="onchange_currency(account_id,amount_currency,currency_id,date,((\'journal_id\' in context) and context[\'journal_id\']) or {})"')
if field.field in widths:
attrs.append('width="'+str(widths[field.field])+'"')
xml += '''<field name="%s" %s/>\n''' % (field.field,' '.join(attrs))
attrs.append('width="' + str(widths[field.field]) + '"')
xml += '''<field name="%s" %s/>\n''' % (field.field, ' '.join(attrs))
xml += '''</tree>'''
result['arch'] = xml
@ -736,8 +736,8 @@ class account_move_line(osv.osv):
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
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)
@ -745,7 +745,7 @@ class account_move_line(osv.osv):
def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
if not context:
context={}
context = {}
if vals.get('account_tax_id', False):
raise osv.except_osv(_('Unable to change tax !'), _('You can not change the tax, you should remove and recreate lines !'))
@ -776,13 +776,13 @@ class account_move_line(osv.osv):
cr.execute('select state from account_journal_period where journal_id=%s and period_id=%s', (journal_id, period_id))
result = cr.fetchall()
for (state,) in result:
if state=='done':
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 ''),
'name': (journal.code or journal.name) + ':' + (period.name or ''),
'journal_id': journal.id,
'period_id': period.id
})
@ -791,7 +791,7 @@ class account_move_line(osv.osv):
def _update_check(self, cr, uid, ids, context={}):
done = {}
for line in self.browse(cr, uid, ids, context):
if line.move_id.state<>'draft':
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 !'))
@ -803,9 +803,9 @@ class account_move_line(osv.osv):
def create(self, cr, uid, vals, context=None, check=True):
if not context:
context={}
context = {}
account_obj = self.pool.get('account.account')
tax_obj=self.pool.get('account.tax')
tax_obj = self.pool.get('account.tax')
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:
@ -826,7 +826,7 @@ class account_move_line(osv.osv):
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=%s and period_id=%s order by id limit 1', (context['journal_id'],context['period_id']))
cr.execute('select id, state, name from account_move where journal_id=%s and period_id=%s order by id limit 1', (context['journal_id'], context['period_id']))
res = cr.fetchone()
if res:
if res[1] != 'draft':
@ -860,7 +860,7 @@ class account_move_line(osv.osv):
break
if journal.account_control_ids and not ok:
for a in journal.account_control_ids:
if a.id==vals['account_id']:
if a.id == vals['account_id']:
ok = True
break
if (account.currency_id) and 'amount_currency' not in vals and account.currency_id.id <> company_currency:
@ -870,14 +870,14 @@ class account_move_line(osv.osv):
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),
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 !'))
if 'analytic_account_id' in vals and vals['analytic_account_id']:
if journal.analytic_journal_id:
vals['analytic_lines'] = [(0,0, {
vals['analytic_lines'] = [(0, 0, {
'name': vals['name'],
'date': vals.get('date', time.strftime('%Y-%m-%d')),
'account_id': vals['analytic_account_id'],
@ -896,7 +896,7 @@ class account_move_line(osv.osv):
result = super(osv.osv, self).create(cr, uid, vals, context)
# CREATE Taxes
if 'account_tax_id' in vals and vals['account_tax_id']:
tax_id=tax_obj.browse(cr,uid,vals['account_tax_id'])
tax_id = tax_obj.browse(cr, uid, vals['account_tax_id'])
total = vals['debit'] - vals['credit']
if journal.refund_journal:
base_code = 'ref_base_code_id'
@ -912,12 +912,12 @@ class account_move_line(osv.osv):
tax_sign = 'tax_sign'
tmp_cnt = 0
for tax in tax_obj.compute(cr,uid,[tax_id],total,1.00):
for tax in tax_obj.compute(cr, uid, [tax_id], total, 1.00):
#create the base movement
if tmp_cnt == 0:
if tax[base_code]:
tmp_cnt += 1
self.write(cr, uid,[result], {
self.write(cr, uid, [result], {
'tax_code_id': tax[base_code],
'tax_amount': tax[base_sign] * abs(total)
})
@ -928,8 +928,8 @@ class account_move_line(osv.osv):
'period_id': vals['period_id'],
'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
'date': vals['date'],
'partner_id': vals.get('partner_id',False),
'ref': vals.get('ref',False),
'partner_id': vals.get('partner_id', False),
'ref': vals.get('ref', False),
'account_tax_id': False,
'tax_code_id': tax[base_code],
'tax_amount': tax[base_sign] * abs(total),
@ -947,14 +947,14 @@ class account_move_line(osv.osv):
'period_id': vals['period_id'],
'name': tools.ustr(vals['name'] or '') + ' ' + tools.ustr(tax['name'] or ''),
'date': vals['date'],
'partner_id': vals.get('partner_id',False),
'ref': vals.get('ref',False),
'partner_id': vals.get('partner_id', False),
'ref': vals.get('ref', False),
'account_tax_id': False,
'tax_code_id': tax[tax_code],
'tax_amount': tax[tax_sign] * abs(tax['amount']),
'account_id': tax[account_id] or vals['account_id'],
'credit': tax['amount']<0 and -tax['amount'] or 0.0,
'debit': tax['amount']>0 and tax['amount'] or 0.0,
'credit': tax['amount'] < 0 and - tax['amount'] or 0.0,
'debit': tax['amount'] > 0 and tax['amount'] or 0.0,
}
if data['tax_code_id']:
self.create(cr, uid, data, context)
@ -968,7 +968,7 @@ class account_move_line(osv.osv):
if check and not context.get('no_store_function'):
tmp = self.pool.get('account.move').validate(cr, uid, [vals['move_id']], context)
if journal.entry_posted and tmp:
self.pool.get('account.move').button_validate(cr,uid, [vals['move_id']],context)
self.pool.get('account.move').button_validate(cr, uid, [vals['move_id']], context)
return result
account_move_line()

View File

@ -28,7 +28,7 @@ class res_company(osv.osv):
}
_defaults = {
'overdue_msg': lambda *a: 'Would your payment have been carried \
'overdue_msg': lambda * a: 'Would your payment have been carried \
out after this mail was sent, please consider the present one as \
void. Do not hesitate to contact our accounting department'
}

View File

@ -29,7 +29,7 @@ class account_installer(osv.osv_memory):
def _get_charts(self, cr, uid, context=None):
modules = self.pool.get('ir.module.module')
ids = modules.search(cr, uid, [('category_id','=','Account Charts')])
ids = modules.search(cr, uid, [('category_id', '=', 'Account Charts')])
return list(
sorted(((m.name, m.shortdesc)
for m in modules.browse(cr, uid, ids)),
@ -71,7 +71,7 @@ class account_installer(osv.osv_memory):
context=context)[0]['charts']
self.logger.notifyChannel(
'installer', netsvc.LOG_DEBUG,
'Installing chart of accounts %s'%chart)
'Installing chart of accounts %s' % chart)
return modules | set([chart])

View File

@ -44,7 +44,7 @@ from tools.translate import _
class account_invoice(osv.osv):
def _amount_all(self, cr, uid, ids, name, args, context=None):
res = {}
for invoice in self.browse(cr,uid,ids, context=context):
for invoice in self.browse(cr, uid, ids, context=context):
res[invoice.id] = {
'amount_untaxed': 0.0,
'amount_tax': 0.0,
@ -67,7 +67,7 @@ class account_invoice(osv.osv):
refund_journal = {'out_invoice': False, 'in_invoice': False, 'out_refund': True, 'in_refund': True}
journal_obj = self.pool.get('account.journal')
res = journal_obj.search(cr, uid, [('type', '=', type2journal.get(type_inv, 'sale')),
('company_id', '=', company_id),('refund_journal', '=', refund_journal.get(type_inv, False))],
('company_id', '=', company_id), ('refund_journal', '=', refund_journal.get(type_inv, False))],
limit=1)
if res:
return res[0]
@ -79,14 +79,14 @@ class account_invoice(osv.osv):
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]
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=None):
type2journal = {'out_invoice': 'sale', 'in_invoice': 'purchase', 'out_refund': 'sale', 'in_refund': 'purchase'}
tt = type2journal.get(type_inv, 'sale')
result = self.pool.get('account.analytic.journal').search(cr, uid, [('type','=',tt)], context=context)
result = self.pool.get('account.analytic.journal').search(cr, uid, [('type', '=', tt)], context=context)
if not result:
raise osv.except_osv(_('No Analytic Journal !'),_("You must define an analytic journal of type '%s' !") % (tt,))
raise osv.except_osv(_('No Analytic Journal !'), _("You must define an analytic journal of type '%s' !") % (tt,))
return result[0]
def _get_type(self, cr, uid, context=None):
@ -111,7 +111,7 @@ class account_invoice(osv.osv):
for inv in data_inv:
debit = credit = 0.0
context.update({'date':inv.date_invoice})
context_unreconciled=context.copy()
context_unreconciled = context.copy()
for lines in inv.move_lines:
debit_tmp = lines.debit
credit_tmp = lines.credit
@ -124,38 +124,38 @@ class account_invoice(osv.osv):
context_unreconciled.update({'date':lines.date})
# If amount currency setted, compute for debit and credit in company currency
if lines.amount_currency < 0:
credit_tmp=abs(cur_obj.compute(cr, uid, lines.currency_id.id, inv.company_id.currency_id.id, lines.amount_currency, round=False,context=context_unreconciled))
credit_tmp = abs(cur_obj.compute(cr, uid, lines.currency_id.id, inv.company_id.currency_id.id, lines.amount_currency, round=False, context=context_unreconciled))
elif lines.amount_currency > 0:
debit_tmp=abs(cur_obj.compute(cr, uid, lines.currency_id.id, inv.company_id.currency_id.id, lines.amount_currency, round=False,context=context_unreconciled))
debit_tmp = abs(cur_obj.compute(cr, uid, lines.currency_id.id, inv.company_id.currency_id.id, lines.amount_currency, round=False, context=context_unreconciled))
# Then, recomput into invoice currency to avoid rounding trouble !
debit += cur_obj.compute(cr, uid, inv.company_id.currency_id.id, inv.currency_id.id, debit_tmp, round=False,context=context)
credit += cur_obj.compute(cr, uid, inv.company_id.currency_id.id, inv.currency_id.id, credit_tmp, round=False,context=context)
debit += cur_obj.compute(cr, uid, inv.company_id.currency_id.id, inv.currency_id.id, debit_tmp, round=False, context=context)
credit += cur_obj.compute(cr, uid, inv.company_id.currency_id.id, inv.currency_id.id, credit_tmp, round=False, context=context)
else:
debit+=debit_tmp
credit+=credit_tmp
debit += debit_tmp
credit += credit_tmp
if not inv.amount_total:
result = 0.0
elif inv.type in ('out_invoice','in_refund'):
amount = credit-debit
elif inv.type in ('out_invoice', 'in_refund'):
amount = credit - debit
result = inv.amount_total - amount
else:
amount = debit-credit
amount = debit - credit
result = inv.amount_total - amount
# Use is_zero function to avoid rounding trouble => should be fixed into ORM
res[inv.id] = not self.pool.get('res.currency').is_zero(cr, uid, inv.company_id.currency_id,result) and result or 0.0
res[inv.id] = not self.pool.get('res.currency').is_zero(cr, uid, inv.company_id.currency_id, result) and result or 0.0
return res
def _get_lines(self, cr, uid, ids, name, arg, context=None):
res = {}
for id in ids:
move_lines = self.move_line_id_payment_get(cr,uid,[id])
move_lines = self.move_line_id_payment_get(cr, uid, [id])
if not move_lines:
res[id] = []
continue
res[id] = []
data_lines = self.pool.get('account.move.line').browse(cr,uid,move_lines)
data_lines = self.pool.get('account.move.line').browse(cr, uid, move_lines)
partial_ids = []# Keeps the track of ids where partial payments are done with payment terms
for line in data_lines:
ids_line = []
@ -165,7 +165,7 @@ class account_invoice(osv.osv):
ids_line = line.reconcile_partial_id.line_partial_ids
l = map(lambda x: x.id, ids_line)
partial_ids.append(line.id)
res[id] =[x for x in l if x <> line.id and x not in partial_ids]
res[id] = [x for x in l if x <> line.id and x not in partial_ids]
return res
def _get_invoice_line(self, cr, uid, ids, context=None):
@ -210,7 +210,7 @@ class account_invoice(osv.osv):
move[line2.move_id.id] = True
invoice_ids = []
if move:
invoice_ids = self.pool.get('account.invoice').search(cr, uid, [('move_id','in',move.keys())], context=context)
invoice_ids = self.pool.get('account.invoice').search(cr, uid, [('move_id', 'in', move.keys())], context=context)
return invoice_ids
def _get_invoice_from_reconcile(self, cr, uid, ids, context={}):
@ -223,21 +223,21 @@ class account_invoice(osv.osv):
invoice_ids = []
if move:
invoice_ids = self.pool.get('account.invoice').search(cr, uid, [('move_id','in',move.keys())], context=context)
invoice_ids = self.pool.get('account.invoice').search(cr, uid, [('move_id', 'in', move.keys())], context=context)
return invoice_ids
_name = "account.invoice"
_description = 'Invoice'
_order = "number"
_columns = {
'name': fields.char('Description', size=64, select=True,readonly=True, states={'draft':[('readonly',False)]}),
'name': fields.char('Description', size=64, select=True, readonly=True, states={'draft':[('readonly', False)]}),
'origin': fields.char('Source Document', size=64, help="Reference of the document that produced this invoice."),
'type': fields.selection([
('out_invoice','Customer Invoice'),
('in_invoice','Supplier Invoice'),
('out_refund','Customer Refund'),
('in_refund','Supplier Refund'),
],'Type', readonly=True, select=True, change_default=True),
('out_invoice', 'Customer Invoice'),
('in_invoice', 'Supplier Invoice'),
('out_refund', 'Customer Refund'),
('in_refund', 'Supplier Refund'),
], 'Type', readonly=True, select=True, change_default=True),
'number': fields.char('Invoice Number', size=32, readonly=True, help="Unique number of the invoice, computed automatically when the invoice is created."),
'reference': fields.char('Invoice Reference', size=64, help="The partner reference of this invoice."),
@ -246,61 +246,61 @@ class account_invoice(osv.osv):
'comment': fields.text('Additional Information', translate=True),
'state': fields.selection([
('draft','Draft'),
('proforma','Pro-forma'),
('proforma2','Pro-forma'),
('open','Open'),
('paid','Done'),
('cancel','Cancelled')
],'State', select=True, readonly=True,
('draft', 'Draft'),
('proforma', 'Pro-forma'),
('proforma2', 'Pro-forma'),
('open', 'Open'),
('paid', 'Done'),
('cancel', 'Cancelled')
], 'State', select=True, readonly=True,
help=' * The \'Draft\' state is used when a user is encoding a new and unconfirmed Invoice. \
\n* The \'Pro-forma\' when invoice is in Pro-forma state,invoice does not have an invoice number. \
\n* The \'Open\' state is used when user create invoice,a invoice number is generated.Its in open state till user does not pay invoice. \
\n* The \'Done\' state is set automatically when invoice is paid.\
\n* The \'Cancelled\' state is used when user cancel invoice.'),
'date_invoice': fields.date('Date Invoiced', states={'open':[('readonly',True)],'close':[('readonly',True)]}, help="Keep empty to use the current date"),
'date_due': fields.date('Due Date', states={'open':[('readonly',True)],'close':[('readonly',True)]},
'date_invoice': fields.date('Date Invoiced', states={'open':[('readonly', True)], 'close':[('readonly', True)]}, help="Keep empty to use the current date"),
'date_due': fields.date('Due Date', states={'open':[('readonly', True)], 'close':[('readonly', True)]},
help="If you use payment terms, the due date will be computed automatically at the generation "\
"of accounting entries. If you keep the payment term and the due date empty, it means direct payment. The payment term may compute several due dates, for example 50% now, 50% in one month."),
'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)]},
'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)]},
help="If you use payment terms, the due date will be computed automatically at the generation "\
"of accounting entries. If you keep the payment term and the due date empty, it means direct payment. "\
"The payment term may compute several due dates, for example 50% now, 50% in one month."),
'period_id': fields.many2one('account.period', 'Force Period', domain=[('state','<>','done')], help="Keep empty to use the period of the validation(invoice) date.", readonly=True, states={'draft':[('readonly',False)]}),
'period_id': fields.many2one('account.period', 'Force Period', domain=[('state', '<>', 'done')], help="Keep empty to use the period of the validation(invoice) date.", readonly=True, states={'draft':[('readonly', False)]}),
'account_id': fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly',False)]}, help="The partner account used for this invoice."),
'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)]}),
'account_id': fields.many2one('account.account', 'Account', required=True, readonly=True, states={'draft':[('readonly', False)]}, help="The partner account used for this invoice."),
'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, help="Links to the automatically generated Ledger Postings."),
'amount_untaxed': fields.function(_amount_all, method=True, digits=(16, int(config['price_accuracy'])),string='Untaxed',
'amount_untaxed': fields.function(_amount_all, method=True, digits=(16, int(config['price_accuracy'])), string='Untaxed',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line, ['price_unit','invoice_line_tax_id','quantity','discount'], 20),
'account.invoice.line': (_get_invoice_line, ['price_unit', 'invoice_line_tax_id', 'quantity', 'discount'], 20),
},
multi='all'),
'amount_tax': fields.function(_amount_all, method=True, digits=(16, int(config['price_accuracy'])), string='Tax',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line, ['price_unit','invoice_line_tax_id','quantity','discount'], 20),
'account.invoice.line': (_get_invoice_line, ['price_unit', 'invoice_line_tax_id', 'quantity', 'discount'], 20),
},
multi='all'),
'amount_total': fields.function(_amount_all, method=True, digits=(16, int(config['price_accuracy'])), string='Total',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_line'], 20),
'account.invoice.tax': (_get_invoice_tax, None, 20),
'account.invoice.line': (_get_invoice_line, ['price_unit','invoice_line_tax_id','quantity','discount'], 20),
'account.invoice.line': (_get_invoice_line, ['price_unit', 'invoice_line_tax_id', 'quantity', 'discount'], 20),
},
multi='all'),
'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)]}),
'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, change_default=True),
'check_total': fields.float('Total', digits=(16, int(config['price_accuracy'])), states={'open':[('readonly',True)],'close':[('readonly',True)]}),
'check_total': fields.float('Total', digits=(16, int(config['price_accuracy'])), states={'open':[('readonly', True)], 'close':[('readonly', True)]}),
'reconciled': fields.function(_reconciled, method=True, string='Paid/Reconciled', type='boolean',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids, None, 50), # Check if we can remove ?
@ -309,12 +309,12 @@ class account_invoice(osv.osv):
}, help="The Ledger Postings of the invoice have been reconciled with Ledger Postings of the payment(s)."),
'partner_bank': fields.many2one('res.partner.bank', 'Bank Account',
help='The bank account to pay to or to be paid from'),
'move_lines':fields.function(_get_lines , method=True,type='many2many' , relation='account.move.line',string='Entry Lines'),
'residual': fields.function(_amount_residual, method=True, digits=(16, int(config['price_accuracy'])),string='Residual',
'move_lines':fields.function(_get_lines , method=True, type='many2many' , relation='account.move.line', string='Entry Lines'),
'residual': fields.function(_amount_residual, method=True, digits=(16, int(config['price_accuracy'])), string='Residual',
store={
'account.invoice': (lambda self, cr, uid, ids, c={}: ids, ['invoice_line'], 50),
'account.invoice.tax': (_get_invoice_tax, None, 50),
'account.invoice.line': (_get_invoice_line, ['price_unit','invoice_line_tax_id','quantity','discount'], 50),
'account.invoice.line': (_get_invoice_line, ['price_unit', 'invoice_line_tax_id', 'quantity', 'discount'], 50),
'account.move.line': (_get_invoice_from_line, None, 50),
'account.move.reconcile': (_get_invoice_from_reconcile, None, 50),
},
@ -326,12 +326,12 @@ class account_invoice(osv.osv):
_defaults = {
'type': _get_type,
#'date_invoice': lambda *a: time.strftime('%Y-%m-%d'),
'state': lambda *a: 'draft',
'state': lambda * a: 'draft',
'journal_id': _get_journal,
'currency_id': _get_currency,
'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.invoice', context=c),
'reference_type': lambda *a: 'none',
'check_total': lambda *a: 0.0,
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.invoice', context=c),
'reference_type': lambda * a: 'none',
'check_total': lambda * a: 0.0,
}
def unlink(self, cr, uid, ids, context=None):
@ -367,21 +367,21 @@ class account_invoice(osv.osv):
p = self.pool.get('res.partner').browse(cr, uid, partner_id)
if company_id:
if p.property_account_receivable.company_id.id != company_id and p.property_account_payable.company_id.id != company_id:
rec_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_receivable'),('res_id','=','res.partner,'+str(partner_id)+''),('company_id','=',company_id)])
pay_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_payable'),('res_id','=','res.partner,'+str(partner_id)+''),('company_id','=',company_id)])
rec_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_receivable'), ('res_id', '=', 'res.partner,' + str(partner_id) + ''), ('company_id', '=', company_id)])
pay_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_payable'), ('res_id', '=', 'res.partner,' + str(partner_id) + ''), ('company_id', '=', company_id)])
if not rec_pro_id:
rec_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_receivable'),('company_id','=',company_id)])
rec_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_receivable'), ('company_id', '=', company_id)])
if not pay_pro_id:
pay_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_payable'),('company_id','=',company_id)])
rec_line_data = self.pool.get('ir.property').read(cr,uid,rec_pro_id,['name','value','res_id'])
pay_line_data = self.pool.get('ir.property').read(cr,uid,pay_pro_id,['name','value','res_id'])
pay_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_payable'), ('company_id', '=', company_id)])
rec_line_data = self.pool.get('ir.property').read(cr, uid, rec_pro_id, ['name', 'value', 'res_id'])
pay_line_data = self.pool.get('ir.property').read(cr, uid, pay_pro_id, ['name', 'value', 'res_id'])
rec_res_id = rec_line_data and int(rec_line_data[0]['value'].split(',')[1]) or False
pay_res_id = pay_line_data and int(pay_line_data[0]['value'].split(',')[1]) or False
if not rec_res_id and not pay_res_id:
raise osv.except_osv(_('Configration Error !'),
_('Can not find account chart for this company, Please Create account.'))
rec_obj_acc=self.pool.get('account.account').browse(cr,uid,[rec_res_id])
pay_obj_acc=self.pool.get('account.account').browse(cr,uid,[pay_res_id])
rec_obj_acc = self.pool.get('account.account').browse(cr, uid, [rec_res_id])
pay_obj_acc = self.pool.get('account.account').browse(cr, uid, [pay_res_id])
p.property_account_receivable = rec_obj_acc[0]
p.property_account_payable = pay_obj_acc[0]
@ -409,7 +409,7 @@ class account_invoice(osv.osv):
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)
cr, uid, ids, partner_payment_term, date_invoice)
result['value'].update(to_update['value'])
else:
result['value']['date_due'] = False
@ -430,8 +430,8 @@ class account_invoice(osv.osv):
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')
res = {}
pt_obj = self.pool.get('account.payment.term')
if not date_invoice :
date_invoice = time.strftime('%Y-%m-%d')
@ -440,7 +440,7 @@ class account_invoice(osv.osv):
if pterm_list:
pterm_list = [line[0] for line in pterm_list]
pterm_list.sort()
res= {'value':{'date_due': pterm_list[-1]}}
res = {'value':{'date_due': pterm_list[-1]}}
else:
raise osv.except_osv(_('Data Insufficient !'), _('The Payment Term of Supplier does not have Payment Term Lines(Computation) defined !'))
@ -453,21 +453,21 @@ class account_invoice(osv.osv):
return {'value': {}}
def onchange_company_id(self, cr, uid, ids, company_id, part_id, type, invoice_line, currency_id):
val={}
dom={}
val = {}
dom = {}
if company_id and part_id and type:
acc_id = False
partner_obj = self.pool.get('res.partner').browse(cr,uid,part_id)
partner_obj = self.pool.get('res.partner').browse(cr, uid, part_id)
if partner_obj.property_account_payable and partner_obj.property_account_receivable:
if partner_obj.property_account_payable.company_id.id != company_id and partner_obj.property_account_receivable.company_id.id != company_id:
rec_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_receivable'),('res_id','=','res.partner,'+str(part_id)+''),('company_id','=',company_id)])
pay_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_payable'),('res_id','=','res.partner,'+str(part_id)+''),('company_id','=',company_id)])
rec_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_receivable'), ('res_id', '=', 'res.partner,' + str(part_id) + ''), ('company_id', '=', company_id)])
pay_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_payable'), ('res_id', '=', 'res.partner,' + str(part_id) + ''), ('company_id', '=', company_id)])
if not rec_pro_id:
rec_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_receivable'),('company_id','=',company_id)])
rec_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_receivable'), ('company_id', '=', company_id)])
if not pay_pro_id:
pay_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_payable'),('company_id','=',company_id)])
rec_line_data = self.pool.get('ir.property').read(cr,uid,rec_pro_id,['name','value','res_id'])
pay_line_data = self.pool.get('ir.property').read(cr,uid,pay_pro_id,['name','value','res_id'])
pay_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_payable'), ('company_id', '=', company_id)])
rec_line_data = self.pool.get('ir.property').read(cr, uid, rec_pro_id, ['name', 'value', 'res_id'])
pay_line_data = self.pool.get('ir.property').read(cr, uid, pay_pro_id, ['name', 'value', 'res_id'])
rec_res_id = rec_line_data and int(rec_line_data[0]['value'].split(',')[1]) or False
pay_res_id = pay_line_data and int(pay_line_data[0]['value'].split(',')[1]) or False
if not rec_res_id and not rec_res_id:
@ -477,49 +477,49 @@ class account_invoice(osv.osv):
acc_id = rec_res_id
else:
acc_id = pay_res_id
val= {'account_id': acc_id}
val = {'account_id': acc_id}
if ids:
if company_id:
inv_obj = self.browse(cr,uid,ids)
inv_obj = self.browse(cr, uid, ids)
for line in inv_obj[0].invoice_line:
if line.account_id:
if line.account_id.company_id.id != company_id:
result_id = self.pool.get('account.account').search(cr,uid,[('name','=',line.account_id.name),('company_id','=',company_id)])
result_id = self.pool.get('account.account').search(cr, uid, [('name', '=', line.account_id.name), ('company_id', '=', company_id)])
if not result_id:
raise osv.except_osv(_('Configration Error !'),
_('Can not find account chart for this company in invoice line account, Please Create account.'))
r_id = self.pool.get('account.invoice.line').write(cr,uid,[line.id],{'account_id': result_id[0]})
r_id = self.pool.get('account.invoice.line').write(cr, uid, [line.id], {'account_id': result_id[0]})
else:
if invoice_line:
for inv_line in invoice_line:
obj_l = self.pool.get('account.account').browse(cr,uid,inv_line[2]['account_id'])
obj_l = self.pool.get('account.account').browse(cr, uid, inv_line[2]['account_id'])
if obj_l.company_id.id != company_id:
raise osv.except_osv(_('Configration Error !'),
_('invoice line account company is not match with invoice company.'))
else:
continue
if company_id:
val['journal_id']=False
journal_ids=self.pool.get('account.journal').search(cr,uid,[('company_id','=',company_id)])
dom={'journal_id': [('id','in',journal_ids)]}
val['journal_id'] = False
journal_ids = self.pool.get('account.journal').search(cr, uid, [('company_id', '=', company_id)])
dom = {'journal_id': [('id', 'in', journal_ids)]}
else:
journal_ids=self.pool.get('account.journal').search(cr,uid,[])
dom={'journal_id': [('id','in',journal_ids)]}
journal_ids = self.pool.get('account.journal').search(cr, uid, [])
dom = {'journal_id': [('id', 'in', journal_ids)]}
if currency_id and company_id:
currency = self.pool.get('res.currency').browse(cr, uid, currency_id)
if currency.company_id.id != company_id:
val['currency_id'] = False
else:
val['currency_id'] = currency.id
if company_id:
company = self.pool.get('res.company').browse(cr, uid, company_id)
if company.currency_id.company_id.id != company_id:
val['currency_id'] = False
val['currency_id'] = False
else:
val['currency_id'] = company.currency_id.id
return {'value' : val, 'domain': dom }
# go from canceled state to draft state
@ -542,7 +542,7 @@ class account_invoice(osv.osv):
l.id \
from account_move_line l \
left join account_invoice i on (i.move_id=l.move_id) \
where i.id in ('+','.join(map(str,map(int, ids)))+') and l.account_id=i.account_id')
where i.id in (' + ','.join(map(str, map(int, ids))) + ') and l.account_id=i.account_id')
res = map(lambda x: x[0], cr.fetchall())
return res
@ -550,7 +550,7 @@ class account_invoice(osv.osv):
if default is None:
default = {}
default = default.copy()
default.update({'state':'draft', 'number':False, 'move_id':False, 'move_name':False,})
default.update({'state':'draft', 'number':False, 'move_id':False, 'move_name':False, })
if 'date_invoice' not in default:
default['date_invoice'] = False
if 'date_due' not in default:
@ -573,7 +573,7 @@ class account_invoice(osv.osv):
ait_obj = self.pool.get('account.invoice.tax')
for id in ids:
cr.execute("DELETE FROM account_invoice_tax WHERE invoice_id=%s", (id,))
partner = self.browse(cr, uid, id,context=context).partner_id
partner = self.browse(cr, uid, id, context=context).partner_id
if partner.lang:
context.update({'lang': partner.lang})
for taxe in ait_obj.compute(cr, uid, id, context=context).values():
@ -591,7 +591,7 @@ class account_invoice(osv.osv):
return True
def _convert_ref(self, cr, uid, ref):
return (ref or '').replace('/','')
return (ref or '').replace('/', '')
def _get_analytic_lines(self, cr, uid, id):
inv = self.browse(cr, uid, [id])[0]
@ -610,7 +610,7 @@ class account_invoice(osv.osv):
ref = inv.reference
else:
ref = self._convert_ref(cr, uid, inv.number)
il['analytic_lines'] = [(0,0, {
il['analytic_lines'] = [(0, 0, {
'name': il['name'],
'date': inv['date_invoice'],
'account_id': il['account_analytic_id'],
@ -669,7 +669,7 @@ class account_invoice(osv.osv):
if not key in tax_key:
raise osv.except_osv(_('Warning !'), _('Taxes missing !'))
if inv.type in ('in_invoice', 'in_refund') and abs(inv.check_total - inv.amount_total) >= (inv.currency_id.rounding/2.0):
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.'))
# one move line per tax line
@ -695,10 +695,10 @@ class account_invoice(osv.osv):
i['amount_currency'] = False
i['currency_id'] = False
i['ref'] = ref
if inv.type in ('out_invoice','in_refund'):
if inv.type in ('out_invoice', 'in_refund'):
total += i['price']
total_currency += i['amount_currency'] or i['price']
i['price'] = - i['price']
i['price'] = -i['price']
else:
total -= i['price']
total_currency -= i['amount_currency'] or i['price']
@ -754,28 +754,28 @@ class account_invoice(osv.osv):
date = inv.date_invoice or time.strftime('%Y-%m-%d')
part = inv.partner_id.id
line = map(lambda x:(0,0,self.line_get_convert(cr, uid, x, part, date, context={})) ,iml)
line = map(lambda x:(0, 0, self.line_get_convert(cr, uid, x, part, date, context={})) , iml)
if inv.journal_id.group_invoice_lines:
line2 = {}
for x, y, l in line:
tmp = str(l['account_id'])
tmp += '-'+str(l.get('tax_code_id',"False"))
tmp += '-'+str(l.get('product_id',"False"))
tmp += '-'+str(l.get('analytic_account_id',"False"))
tmp += '-'+str(l.get('date_maturity',"False"))
tmp += '-' + str(l.get('tax_code_id', "False"))
tmp += '-' + str(l.get('product_id', "False"))
tmp += '-' + str(l.get('analytic_account_id', "False"))
tmp += '-' + str(l.get('date_maturity', "False"))
if tmp in line2:
am = line2[tmp]['debit'] - line2[tmp]['credit'] + (l['debit'] - l['credit'])
line2[tmp]['debit'] = (am > 0) and am or 0.0
line2[tmp]['credit'] = (am < 0) and -am or 0.0
line2[tmp]['credit'] = (am < 0) and - am or 0.0
line2[tmp]['tax_amount'] += l['tax_amount']
line2[tmp]['analytic_lines'] += l['analytic_lines']
else:
line2[tmp] = l
line = []
for key, val in line2.items():
line.append((0,0,val))
line.append((0, 0, val))
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)
@ -783,11 +783,11 @@ class account_invoice(osv.osv):
raise osv.except_osv(_('UserError'),
_('Cannot create invoice move on centralised journal'))
move = {'ref': inv.number, 'line_id': line, 'journal_id': journal_id, 'date': date}
period_id=inv.period_id and inv.period_id.id or False
period_id = inv.period_id and inv.period_id.id or False
if not period_id:
period_ids= self.pool.get('account.period').search(cr,uid,[('date_start','<=',inv.date_invoice or time.strftime('%Y-%m-%d')),('date_stop','>=',inv.date_invoice or time.strftime('%Y-%m-%d'))])
period_ids = self.pool.get('account.period').search(cr, uid, [('date_start', '<=', inv.date_invoice or time.strftime('%Y-%m-%d')), ('date_stop', '>=', inv.date_invoice or time.strftime('%Y-%m-%d'))])
if len(period_ids):
period_id=period_ids[0]
period_id = period_ids[0]
if period_id:
move['period_id'] = period_id
for i in line:
@ -796,7 +796,7 @@ class account_invoice(osv.osv):
move_id = self.pool.get('account.move').create(cr, uid, move, context=context)
new_move_name = self.pool.get('account.move').browse(cr, uid, move_id).name
# make the invoice point to that move
self.write(cr, uid, [inv.id], {'move_id': move_id,'period_id':period_id, 'move_name':new_move_name})
self.write(cr, uid, [inv.id], {'move_id': move_id, 'period_id':period_id, 'move_name':new_move_name})
self.pool.get('account.move').post(cr, uid, [move_id])
self._log_event(cr, uid, ids)
return True
@ -807,25 +807,25 @@ class account_invoice(osv.osv):
'partner_id':part,
'name':x['name'][:64],
'date': date,
'debit':x['price']>0 and x['price'],
'credit':x['price']<0 and -x['price'],
'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)),
'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),
'quantity':x.get('quantity',1.00),
'ref':x.get('ref', False),
'quantity':x.get('quantity', 1.00),
'product_id':x.get('product_id', False),
'product_uom_id':x.get('uos_id',False),
'analytic_account_id':x.get('account_analytic_id',False),
'product_uom_id':x.get('uos_id', False),
'analytic_account_id':x.get('account_analytic_id', 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))+')')
'WHERE id IN (' + ','.join(map(str, ids)) + ')')
obj_inv = self.browse(cr, uid, ids)[0]
for (id, invtype, number, move_id, reference) in cr.fetchall():
if not number:
@ -867,7 +867,7 @@ class account_invoice(osv.osv):
if i['payment_ids']:
self.pool.get('account.move.line').write(cr, uid, i['payment_ids'], {'reconcile_partial_id': False})
self.write(cr, uid, ids, {'state':'cancel', 'move_id':False})
self._log_event(cr, uid, ids,-1.0, 'Cancel Invoice')
self._log_event(cr, uid, ids, -1.0, 'Cancel Invoice')
return True
###################
@ -882,22 +882,22 @@ class account_invoice(osv.osv):
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'])
invs = self.read(cr, uid, ids, ['type', 'partner_id', 'amount_untaxed'])
for inv in invs:
part=inv['partner_id'] and inv['partner_id'][0]
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=%s', (inv['id'],))
total = inv['amount_untaxed']
if inv['type'] in ('in_invoice','in_refund'):
partnertype='supplier'
if inv['type'] in ('in_invoice', 'in_refund'):
partnertype = 'supplier'
eventtype = 'purchase'
pc = total*factor
pc = total * factor
else:
partnertype = 'customer'
eventtype = 'sale'
pr = total*factor
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})
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=None):
@ -909,18 +909,18 @@ class account_invoice(osv.osv):
'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')]
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=100):
if not args:
args=[]
args = []
if context is None:
context={}
context = {}
ids = []
if name:
ids = self.search(cr, user, [('number','=',name)]+ args, limit=limit, context=context)
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)
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, cr, uid, lines):
@ -934,16 +934,16 @@ class account_invoice(osv.osv):
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', [])) ]
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]
if 'tax_code_id' in line :
if isinstance(line['tax_code_id'],tuple) and len(line['tax_code_id']) >0 :
if isinstance(line['tax_code_id'], tuple) and len(line['tax_code_id']) > 0 :
line['tax_code_id'] = line['tax_code_id'][0]
if 'base_code_id' in line :
if isinstance(line['base_code_id'],tuple) and len(line['base_code_id']) >0 :
if isinstance(line['base_code_id'], tuple) and len(line['base_code_id']) > 0 :
line['base_code_id'] = line['base_code_id'][0]
return map(lambda x: (0,0,x), lines)
return map(lambda x: (0, 0, x), lines)
def refund(self, cr, uid, ids, date=None, period_id=None, description=None):
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'])
@ -954,9 +954,9 @@ class account_invoice(osv.osv):
type_dict = {
'out_invoice': 'out_refund', # Customer Invoice
'in_invoice': 'in_refund', # Supplier Invoice
'in_invoice': 'in_refund', # Supplier Invoice
'out_refund': 'out_invoice', # Customer Refund
'in_refund': 'in_invoice', # Supplier Refund
'in_refund': 'in_invoice', # Supplier Refund
}
@ -996,17 +996,17 @@ class account_invoice(osv.osv):
if context is None:
context = {}
#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"
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
# Take the seq as name for move
types = {'out_invoice': -1, 'in_invoice': 1, 'out_refund': 1, 'in_refund': -1}
types = {'out_invoice':-1, 'in_invoice': 1, 'out_refund': 1, 'in_refund':-1}
direction = types[invoice.type]
#take the choosen date
if 'date_p' in context and context['date_p']:
date=context['date_p']
date = context['date_p']
else:
date=time.strftime('%Y-%m-%d')
date = time.strftime('%Y-%m-%d')
# Take the amount in currency and the currency of the payment
if 'amount_currency' in context and context['amount_currency'] and 'currency_id' in context and context['currency_id']:
@ -1021,8 +1021,8 @@ class account_invoice(osv.osv):
ref = self._convert_ref(cr, uid, invoice.number)
# Pay attention to the sign for both debit/credit AND amount_currency
l1 = {
'debit': direction * pay_amount>0 and direction * pay_amount,
'credit': direction * pay_amount<0 and - direction * pay_amount,
'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,
'ref':ref,
@ -1032,8 +1032,8 @@ class account_invoice(osv.osv):
'company_id': invoice.company_id.id,
}
l2 = {
'debit': direction * pay_amount<0 and - direction * pay_amount,
'credit': direction * pay_amount>0 and direction * pay_amount,
'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,
'ref':ref,
@ -1055,16 +1055,16 @@ class account_invoice(osv.osv):
line_ids = []
total = 0.0
line = self.pool.get('account.move.line')
move_ids = [move_id,]
move_ids = [move_id, ]
if invoice.move_id:
move_ids.append(invoice.move_id.id)
cr.execute('SELECT id FROM account_move_line WHERE move_id = ANY(%s)',(move_ids,))
lines = line.browse(cr, uid, map(lambda x: x[0], cr.fetchall()) )
for l in lines+invoice.payment_ids:
if l.account_id.id==src_account_id:
cr.execute('SELECT id FROM account_move_line WHERE move_id = ANY(%s)', (move_ids,))
lines = line.browse(cr, uid, map(lambda x: x[0], cr.fetchall()))
for l in lines + invoice.payment_ids:
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 round(total,int(config['price_accuracy']))) or writeoff_acc_id:
if (not round(total, int(config['price_accuracy']))) 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)
@ -1075,16 +1075,16 @@ class account_invoice(osv.osv):
account_invoice()
class account_invoice_line(osv.osv):
def _amount_line(self, cr, uid, ids, prop, unknow_none,unknow_dict):
def _amount_line(self, cr, uid, ids, prop, unknow_none, unknow_dict):
res = {}
cur_obj=self.pool.get('res.currency')
cur_obj = self.pool.get('res.currency')
for line in self.browse(cr, uid, ids):
if line.invoice_id:
res[line.id] = line.price_unit * line.quantity * (1-(line.discount or 0.0)/100.0)
res[line.id] = line.price_unit * line.quantity * (1 - (line.discount or 0.0) / 100.0)
cur = line.invoice_id.currency_id
res[line.id] = cur_obj.round(cr, uid, cur, res[line.id])
else:
res[line.id] = round(line.price_unit * line.quantity * (1-(line.discount or 0.0)/100.0),int(config['price_accuracy']))
res[line.id] = round(line.price_unit * line.quantity * (1 - (line.discount or 0.0) / 100.0), int(config['price_accuracy']))
return res
@ -1096,12 +1096,12 @@ class account_invoice_line(osv.osv):
for l in context.get('invoice_line', {}):
if isinstance(l, (list, tuple)) and 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)
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)):
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
@ -1114,19 +1114,19 @@ class account_invoice_line(osv.osv):
'invoice_id': fields.many2one('account.invoice', 'Invoice Reference', ondelete='cascade', select=True),
'uos_id': fields.many2one('product.uom', 'Unit of Measure', 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')], help="The income or expense account related to the selected product."),
'account_id': fields.many2one('account.account', 'Account', required=True, domain=[('type', '<>', 'view'), ('type', '<>', 'closed')], help="The income or expense account related to the selected product."),
'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, type="float", digits=(16, int(config['price_accuracy']))),
'price_subtotal': fields.function(_amount_line, method=True, string='Subtotal', store=True, type="float", digits=(16, int(config['price_accuracy']))),
'quantity': fields.float('Quantity', required=True),
'discount': fields.float('Discount (%)', digits=(16, int(config['price_accuracy']))),
'invoice_line_tax_id': fields.many2many('account.tax', 'account_invoice_line_tax', 'invoice_line_id', 'tax_id', 'Taxes', domain=[('parent_id','=',False)]),
'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', translate=True),
'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
'company_id': fields.related('invoice_id','company_id',type='many2one',relation='res.company',string='Company',store=True)
'company_id': fields.related('invoice_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True)
}
_defaults = {
'quantity': lambda *a: 1,
'discount': lambda *a: 0.0,
'quantity': lambda * a: 1,
'discount': lambda * a: 0.0,
'price_unit': _price_unit_default,
}
@ -1136,14 +1136,14 @@ class account_invoice_line(osv.osv):
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}
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, fposition_id=False, price_unit=False, address_invoice_id=False, currency_id=False, context=None):
if context is None:
context = {}
company_id = context.get('company_id',False)
company_id = context.get('company_id', False)
if not partner_id:
raise osv.except_osv(_('No Partner Defined !'),_("You must first select a partner !") )
raise osv.except_osv(_('No Partner Defined !'), _("You must first select a partner !"))
if not product:
if type in ('in_invoice', 'in_refund'):
return {'value': {'categ_id': False}, 'domain':{'product_uom':[]}}
@ -1152,18 +1152,18 @@ class account_invoice_line(osv.osv):
part = self.pool.get('res.partner').browse(cr, uid, partner_id)
fpos = fposition_id and self.pool.get('account.fiscal.position').browse(cr, uid, fposition_id) or False
lang=part.lang
lang = part.lang
context.update({'lang': lang})
result = {}
res = self.pool.get('product.product').browse(cr, uid, product, context=context)
if company_id:
in_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_income'),('res_id','=','product.template,'+str(res.product_tmpl_id.id)+''),('company_id','=',company_id)])
in_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_income'), ('res_id', '=', 'product.template,' + str(res.product_tmpl_id.id) + ''), ('company_id', '=', company_id)])
if not in_pro_id:
in_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_income_categ'),('res_id','=','product.template,'+str(res.categ_id.id)+''),('company_id','=',company_id)])
exp_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_expense'),('res_id','=','product.template,'+str(res.product_tmpl_id.id)+''),('company_id','=',company_id)])
in_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_income_categ'), ('res_id', '=', 'product.template,' + str(res.categ_id.id) + ''), ('company_id', '=', company_id)])
exp_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_expense'), ('res_id', '=', 'product.template,' + str(res.product_tmpl_id.id) + ''), ('company_id', '=', company_id)])
if not exp_pro_id:
exp_pro_id = self.pool.get('ir.property').search(cr,uid,[('name','=','property_account_expense_categ'),('res_id','=','product.template,'+str(res.categ_id.id)+''),('company_id','=',company_id)])
exp_pro_id = self.pool.get('ir.property').search(cr, uid, [('name', '=', 'property_account_expense_categ'), ('res_id', '=', 'product.template,' + str(res.categ_id.id) + ''), ('company_id', '=', company_id)])
if not in_pro_id:
in_acc = res.product_tmpl_id.property_account_income
@ -1173,7 +1173,7 @@ class account_invoice_line(osv.osv):
else:
app_acc_in = in_acc_cate
else:
app_acc_in = self.pool.get('account.account').browse(cr,uid,in_pro_id)[0]
app_acc_in = self.pool.get('account.account').browse(cr, uid, in_pro_id)[0]
if not exp_pro_id:
ex_acc = res.product_tmpl_id.property_account_expense
ex_acc_cate = res.categ_id.property_account_expense_categ
@ -1182,7 +1182,7 @@ class account_invoice_line(osv.osv):
else:
app_acc_exp = ex_acc_cate
else:
app_acc_exp = self.pool.get('account.account').browse(cr,uid,exp_pro_id)[0]
app_acc_exp = self.pool.get('account.account').browse(cr, uid, exp_pro_id)[0]
if not in_pro_id and not exp_pro_id:
in_acc = res.product_tmpl_id.property_account_income
in_acc_cate = res.categ_id.property_account_income_categ
@ -1198,13 +1198,13 @@ class account_invoice_line(osv.osv):
# app_acc_in = self.pool.get('account.account').browse(cr,uid,in_pro_id)[0]
# app_acc_exp = self.pool.get('account.account').browse(cr,uid,exp_pro_id)[0]
if app_acc_in.company_id.id != company_id and app_acc_exp.company_id.id != company_id:
in_res_id=self.pool.get('account.account').search(cr,uid,[('name','=',app_acc_in.name),('company_id','=',company_id)])
exp_res_id=self.pool.get('account.account').search(cr,uid,[('name','=',app_acc_exp.name),('company_id','=',company_id)])
in_res_id = self.pool.get('account.account').search(cr, uid, [('name', '=', app_acc_in.name), ('company_id', '=', company_id)])
exp_res_id = self.pool.get('account.account').search(cr, uid, [('name', '=', app_acc_exp.name), ('company_id', '=', company_id)])
if not in_res_id and not exp_res_id:
raise osv.except_osv(_('Configration Error !'),
_('Can not find account chart for this company, Please Create account.'))
in_obj_acc=self.pool.get('account.account').browse(cr,uid,in_res_id)
exp_obj_acc=self.pool.get('account.account').browse(cr,uid,exp_res_id)
in_obj_acc = self.pool.get('account.account').browse(cr, uid, in_res_id)
exp_obj_acc = self.pool.get('account.account').browse(cr, uid, exp_res_id)
if in_acc or ex_acc:
res.product_tmpl_id.property_account_income = in_obj_acc[0]
res.product_tmpl_id.property_account_expense = exp_obj_acc[0]
@ -1212,12 +1212,12 @@ class account_invoice_line(osv.osv):
res.categ_id.property_account_income_categ = in_obj_acc[0]
res.categ_id.property_account_expense_categ = exp_obj_acc[0]
if type in ('out_invoice','out_refund'):
a = res.product_tmpl_id.property_account_income.id
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
a = res.product_tmpl_id.property_account_expense.id
if not a:
a = res.categ_id.property_account_expense_categ.id
@ -1225,13 +1225,13 @@ class account_invoice_line(osv.osv):
if a:
result['account_id'] = a
taxep=None
taxep = None
tax_obj = self.pool.get('account.tax')
if type in ('out_invoice', 'out_refund'):
taxes = res.taxes_id and res.taxes_id or (a and self.pool.get('account.account').browse(cr, uid,a).tax_ids or False)
taxes = res.taxes_id and res.taxes_id or (a and self.pool.get('account.account').browse(cr, uid, a).tax_ids or False)
tax_id = self.pool.get('account.fiscal.position').map_tax(cr, uid, fpos, taxes)
else:
taxes = res.supplier_taxes_id and res.supplier_taxes_id or (a and self.pool.get('account.account').browse(cr, uid,a).tax_ids or False)
taxes = res.supplier_taxes_id and res.supplier_taxes_id or (a and self.pool.get('account.account').browse(cr, uid, a).tax_ids or False)
tax_id = self.pool.get('account.fiscal.position').map_tax(cr, uid, fpos, taxes)
if type in ('in_invoice', 'in_refund'):
to_update = self.product_id_change_unit_price_inv(cr, uid, tax_id, price_unit or res.standard_price, qty, address_invoice_id, product, partner_id, context=context)
@ -1247,9 +1247,9 @@ class account_invoice_line(osv.osv):
if result['uos_id']:
res2 = res.uom_id.category_id.id
if res2 :
domain = {'uos_id':[('category_id','=',res2 )]}
domain = {'uos_id':[('category_id', '=', res2)]}
prod_pool=self.pool.get('product.product')
prod_pool = self.pool.get('product.product')
result['categ_id'] = res.categ_id.id
res_final = {'value':result, 'domain':domain}
@ -1283,7 +1283,7 @@ class account_invoice_line(osv.osv):
if not mres:
continue
res.append(mres)
tax_code_found= False
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,
@ -1342,44 +1342,44 @@ class account_invoice_tax(osv.osv):
_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,int(config['price_accuracy']))),
'amount': fields.float('Amount', digits=(16,int(config['price_accuracy']))),
'account_id': fields.many2one('account.account', 'Tax Account', required=True, domain=[('type', '<>', 'view'), ('type', '<>', 'income'), ('type', '<>', 'closed')]),
'base': fields.float('Base', digits=(16, int(config['price_accuracy']))),
'amount': fields.float('Amount', digits=(16, int(config['price_accuracy']))),
'manual': fields.boolean('Manual'),
'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of invoice tax."),
'base_code_id': fields.many2one('account.tax.code', 'Base Code', help="The account basis of the tax declaration."),
'base_amount': fields.float('Base Code Amount', digits=(16,int(config['price_accuracy']))),
'base_amount': fields.float('Base Code Amount', digits=(16, int(config['price_accuracy']))),
'tax_code_id': fields.many2one('account.tax.code', 'Tax Code', help="The tax basis of the tax declaration."),
'tax_amount': fields.float('Tax Code Amount', digits=(16,int(config['price_accuracy']))),
'company_id': fields.related('account_id','company_id',type='many2one',relation='res.company',string='Company',store=True),
'tax_amount': fields.float('Tax Code Amount', digits=(16, int(config['price_accuracy']))),
'company_id': fields.related('account_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True),
}
def base_change(self, cr, uid, ids, base,currency_id=False,company_id=False,date_invoice=False):
def base_change(self, cr, uid, ids, base, currency_id=False, company_id=False, date_invoice=False):
cur_obj = self.pool.get('res.currency')
company_obj = self.pool.get('res.company')
company_currency=False
company_currency = False
if company_id:
company_currency = company_obj.read(cr,uid,[company_id],['currency_id'])[0]['currency_id'][0]
company_currency = company_obj.read(cr, uid, [company_id], ['currency_id'])[0]['currency_id'][0]
if currency_id and company_currency:
base = cur_obj.compute(cr, uid, currency_id, company_currency, base, context={'date': date_invoice or time.strftime('%Y-%m-%d')}, round=False)
return {'value': {'base_amount':base}}
def amount_change(self, cr, uid, ids, amount,currency_id=False,company_id=False,date_invoice=False):
def amount_change(self, cr, uid, ids, amount, currency_id=False, company_id=False, date_invoice=False):
cur_obj = self.pool.get('res.currency')
company_obj = self.pool.get('res.company')
company_currency=False
company_currency = False
if company_id:
company_currency = company_obj.read(cr,uid,[company_id],['currency_id'])[0]['currency_id'][0]
company_currency = company_obj.read(cr, uid, [company_id], ['currency_id'])[0]['currency_id'][0]
if currency_id and company_currency:
amount = cur_obj.compute(cr, uid, currency_id, company_currency, amount, context={'date': date_invoice or time.strftime('%Y-%m-%d')}, round=False)
return {'value': {'tax_amount':amount}}
_order = 'sequence'
_defaults = {
'manual': lambda *a: 1,
'base_amount': lambda *a: 0.0,
'tax_amount': lambda *a: 0.0,
'manual': lambda * a: 1,
'base_amount': lambda * a: 0.0,
'tax_amount': lambda * a: 0.0,
}
def compute(self, cr, uid, invoice_id, context={}):
tax_grouped = {}
@ -1390,8 +1390,8 @@ class account_invoice_tax(osv.osv):
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={}
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'] = tax['amount']
@ -1399,7 +1399,7 @@ class account_invoice_tax(osv.osv):
val['sequence'] = tax['sequence']
val['base'] = tax['price_unit'] * line['quantity']
if inv.type in ('out_invoice','in_invoice'):
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 or time.strftime('%Y-%m-%d')}, round=False)

View File

@ -45,7 +45,7 @@ class account_fiscal_position(osv.osv):
if tax.tax_src_id.id == t.id:
if tax.tax_dest_id:
result.append(tax.tax_dest_id.id)
ok=True
ok = True
if not ok:
result.append(t.id)
return result
@ -54,7 +54,7 @@ class account_fiscal_position(osv.osv):
if not fposition_id :
return account_id
for pos in fposition_id.account_ids:
if pos.account_src_id.id==account_id:
if pos.account_src_id.id == account_id:
account_id = pos.account_dest_id.id
break
return account_id
@ -79,8 +79,8 @@ class account_fiscal_position_account(osv.osv):
_rec_name = 'position_id'
_columns = {
'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'),
'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type','<>','view')], required=True),
'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type','<>','view')], required=True)
'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type', '<>', 'view')], required=True),
'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type', '<>', 'view')], required=True)
}
account_fiscal_position_account()
@ -100,10 +100,10 @@ class res_partner(osv.osv):
a.type =ANY(%s) and
l.partner_id =ANY(%s) and
l.reconcile_id is null and
"""+query+"""
""" + query + """
group by
l.partner_id, a.type
""",(['receivable','payable'],ids,))
""", (['receivable', 'payable'], ids,))
tinvert = {
'credit': 'receivable',
'debit': 'payable'
@ -112,32 +112,32 @@ class res_partner(osv.osv):
res = {}
for id in ids:
res[id] = {}.fromkeys(field_names, 0)
for pid,type,val in cr.fetchall():
if val is None: val=0
res[pid][maps[type]] = (type=='receivable') and val or -val
for pid, type, val in cr.fetchall():
if val is None: val = 0
res[pid][maps[type]] = (type == 'receivable') and val or - val
return res
def _credit_search(self, cr, uid, obj, name, args, context):
if not len(args):
return []
where = ' and '.join(map(lambda x: '(sum(debit-credit)'+x[1]+str(x[2])+')',args))
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',) )
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))]
return [('id', '=', '0')]
return [('id', 'in', map(lambda x:x[0], res))]
def _debit_search(self, cr, uid, obj, name, args, context):
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',) )
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))]
return [('id', '=', '0')]
return [('id', 'in', map(lambda x:x[0], res))]
_columns = {
'credit': fields.function(_credit_debit_get,
@ -177,7 +177,7 @@ class res_partner(osv.osv):
'account.payment.term',
type='many2one',
relation='account.payment.term',
string ='Payment Term',
string='Payment Term',
method=True,
view_load=True,
help="This payment term will be used instead of the default one for the current partner"),

View File

@ -53,10 +53,10 @@ class product_template(osv.osv):
_columns = {
'taxes_id': fields.many2many('account.tax', 'product_taxes_rel',
'prod_id', 'tax_id', 'Customer Taxes',
domain=[('parent_id','=',False),('type_tax_use','in',['sale','all'])]),
domain=[('parent_id', '=', False), ('type_tax_use', 'in', ['sale', 'all'])]),
'supplier_taxes_id': fields.many2many('account.tax',
'product_supplier_taxes_rel', 'prod_id', 'tax_id',
'Supplier Taxes', domain=[('parent_id', '=', False),('type_tax_use','in',['purchase','all'])]),
'Supplier Taxes', domain=[('parent_id', '=', False), ('type_tax_use', 'in', ['purchase', 'all'])]),
'property_account_income': fields.property(
'account.account',
type='many2one',

View File

@ -31,22 +31,22 @@ class account_analytic_journal(osv.osv):
'name' : fields.char('Journal name', size=64, required=True),
'code' : fields.char('Journal code', size=8),
'active' : fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the analytic journal without removing it."),
'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 it needs for a document (eg: an invoice) to create analytic entries, Open ERP will look for a matching journal of the same type."),
'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 it needs for a document (eg: an invoice) to create analytic entries, Open ERP will look for a matching journal of the same type."),
'line_ids' : fields.one2many('account.analytic.line', 'journal_id', 'Lines'),
'company_id': fields.many2one('res.company', 'Company', required=True),
}
_defaults = {
'active': lambda *a: True,
'type': lambda *a: 'general',
'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
'active': lambda * a: True,
'type': lambda * a: 'general',
'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
}
account_analytic_journal()
class account_journal(osv.osv):
_inherit="account.journal"
_inherit = "account.journal"
_columns = {
'analytic_journal_id':fields.many2one('account.analytic.journal','Analytic Journal'),
'analytic_journal_id':fields.many2one('account.analytic.journal', 'Analytic Journal'),
}
account_journal()

View File

@ -42,7 +42,7 @@ class journal_print(report_sxw.rml_parse):
'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)
report_sxw.report_sxw('report.account.analytic.journal.print', 'account.analytic.journal', 'addons/account/project/report/analytic_journal.rml', parser=journal_print)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -27,7 +27,7 @@ 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=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'get_objects': self._get_objects,
'lines_g': self._lines_g,
@ -50,10 +50,10 @@ class account_analytic_balance(report_sxw.rml_parse):
def get_children(self, ids):
ids2 = []
read_data = self.pool.get('account.analytic.account').read(self.cr, self.uid, ids,['child_ids','code','complete_name','balance'])
read_data = self.pool.get('account.analytic.account').read(self.cr, self.uid, ids, ['child_ids', 'code', 'complete_name', 'balance'])
for data in read_data:
if (data['id'] not in self.acc_ids):
inculde_empty = True
inculde_empty = True
if (not self.empty_acc) and data['balance'] == 0.00:
inculde_empty = False
if inculde_empty:
@ -103,7 +103,7 @@ class account_analytic_balance(report_sxw.rml_parse):
def _move_sum(self, account_id, date1, date2, option):
if account_id not in self.acc_data_dict:
account_analytic_obj = self.pool.get('account.analytic.account')
ids = account_analytic_obj.search(self.cr, self.uid,[('parent_id', 'child_of', [account_id])])
ids = account_analytic_obj.search(self.cr, self.uid, [('parent_id', 'child_of', [account_id])])
self.acc_data_dict[account_id] = ids
else:
ids = self.acc_data_dict[account_id]
@ -111,17 +111,17 @@ class account_analytic_balance(report_sxw.rml_parse):
if option == "credit" :
self.cr.execute("SELECT -sum(amount) FROM account_analytic_line \
WHERE account_id =ANY(%s) AND date>=%s AND date<=%s AND amount<0",
(ids,date1, date2))
(ids, date1, date2))
elif option == "debit" :
self.cr.execute("SELECT sum(amount) FROM account_analytic_line \
WHERE account_id =ANY(%s)\
AND date>=%s AND date<=%s AND amount>0",
(ids,date1, date2))
(ids, date1, date2))
elif option == "quantity" :
self.cr.execute("SELECT sum(unit_amount) FROM account_analytic_line \
WHERE account_id =ANY(%s)\
AND date>=%s AND date<=%s",
(ids,date1, date2))
(ids, date1, date2))
return self.cr.fetchone()[0] or 0.0
@ -150,7 +150,7 @@ class account_analytic_balance(report_sxw.rml_parse):
def _move_sum_balance(self, account_id, date1, date2):
debit = self._move_sum(account_id, date1, date2, 'debit')
credit = self._move_sum(account_id, date1, date2, 'credit')
return (debit-credit)
return (debit - credit)
# def _move_sum_quantity(self, account_id, date1, date2):
# account_analytic_obj = self.pool.get('account.analytic.account')
@ -170,22 +170,22 @@ class account_analytic_balance(report_sxw.rml_parse):
if not self.acc_sum_list:
account_analytic_obj = self.pool.get('account.analytic.account')
ids2 = account_analytic_obj.search(self.cr, self.uid,[('parent_id', 'child_of', ids)])
ids2 = account_analytic_obj.search(self.cr, self.uid, [('parent_id', 'child_of', ids)])
self.acc_sum_list = ids2
else:
ids2 = self.acc_sum_list
if option == "debit" :
self.cr.execute("SELECT sum(amount) FROM account_analytic_line \
WHERE account_id =ANY(%s) AND date>=%s AND date<=%s AND amount>0",
(ids,date1, date2,))
(ids, date1, date2,))
elif option == "credit" :
self.cr.execute("SELECT -sum(amount) FROM account_analytic_line \
WHERE account_id =ANY(%s) AND date>=%s AND date<=%s AND amount<0",
(ids,date1, date2,))
(ids, date1, date2,))
elif option == "quantity" :
self.cr.execute("SELECT sum(unit_amount) FROM account_analytic_line \
WHERE account_id =ANY(%s)AND date>=%s AND date<=%s",
(ids,date1, date2,))
(ids, date1, date2,))
return self.cr.fetchone()[0] or 0.0
@ -221,7 +221,7 @@ class account_analytic_balance(report_sxw.rml_parse):
def _sum_balance(self, accounts, date1, date2):
debit = self._sum_all(accounts, date1, date2, 'debit') or 0.0
credit = self._sum_all(accounts, date1, date2, 'credit') or 0.0
return (debit-credit)
return (debit - credit)
# def _sum_quantity(self, accounts, date1, date2):
# ids = map(lambda x: x['id'], accounts)

View File

@ -30,7 +30,7 @@ class account_analytic_analytic_check(report_sxw.rml_parse):
self.sum_gen_cred = 0.0
self.sum_ana_deb = 0.0
self.sum_ana_cred = 0.0
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines_p': self._lines_p,
'general_debit': self._gen_deb,
@ -69,7 +69,7 @@ class account_analytic_analytic_check(report_sxw.rml_parse):
'ana_debit': ad,
'ana_credit': ac,
'delta_debit': gd - ad,
'delta_credit': gc - ac,})
'delta_credit': gc - ac, })
self.sum_gen_deb += gd
self.sum_gen_cred += gc
self.sum_ana_deb += ad
@ -125,12 +125,12 @@ class account_analytic_analytic_check(report_sxw.rml_parse):
return self.sum_ana_cred
def _delta_deb(self, date1, date2):
return (self._gen_deb(date1,date2)-self._ana_deb(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))
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)
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)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -29,7 +29,7 @@ from report import report_sxw
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=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines': self._lines,
'lines_a': self._lines_a,
@ -43,11 +43,11 @@ class account_analytic_journal(report_sxw.rml_parse):
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)])
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=%s) AND (move_id is not null))', (date1, date2, journal_id,))
return self.cr.fetchall()[0][0] or 0
@ -57,7 +57,7 @@ class account_analytic_journal(report_sxw.rml_parse):
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,header=False)
report_sxw.report_sxw('report.account.analytic.journal', 'account.analytic.journal', 'addons/account/project/report/analytic_journal.rml', parser=account_analytic_journal, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -26,7 +26,7 @@ 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=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines_g': self._lines_g,
'lines_a': self._lines_a,
@ -87,7 +87,7 @@ class account_analytic_cost_ledger(report_sxw.rml_parse):
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)
return (debit - credit)
def _sum_debit(self, accounts, date1, date2):
ids = map(lambda x: x.id, accounts)
@ -101,15 +101,15 @@ class account_analytic_cost_ledger(report_sxw.rml_parse):
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 =ANY(%s) AND date>=%s AND date<=%s AND amount<0", (ids,date1, date2,))
self.cr.execute("SELECT -sum(amount) FROM account_analytic_line WHERE account_id =ANY(%s) AND date>=%s AND date<=%s AND amount<0", (ids, 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)
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)
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)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -26,7 +26,7 @@ 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=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines_g': self._lines_g,
'lines_a': self._lines_a,
@ -41,7 +41,7 @@ class account_inverted_analytic_balance(report_sxw.rml_parse):
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 =ANY(%s)) 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", (ids,date1,date2,))
GROUP BY aal.general_account_id, aa.name, aa.code, aal.code, aa.id ORDER BY aal.code", (ids, date1, date2,))
res = self.cr.dictfetchall()
for r in res:
@ -49,7 +49,7 @@ class account_inverted_analytic_balance(report_sxw.rml_parse):
r['debit'] = r['balance']
r['credit'] = 0.0
elif r['balance'] < 0:
r['debit'] = 0.0
r['debit'] = 0.0
r['credit'] = -r['balance']
else:
r['debit'] = 0.0
@ -61,7 +61,7 @@ class account_inverted_analytic_balance(report_sxw.rml_parse):
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 =ANY(%s) AND aal.general_account_id=%s 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", (ids,general_account_id, date1, date2,))
GROUP BY aal.account_id, general_account_id, aaa.code, aaa.name ORDER BY aal.account_id", (ids, general_account_id, date1, date2,))
res = self.cr.dictfetchall()
aaa_obj = self.pool.get('account.analytic.account')
@ -86,29 +86,29 @@ class account_inverted_analytic_balance(report_sxw.rml_parse):
ids = map(lambda x: x.id, accounts)
self.cr.execute("SELECT sum(amount) \
FROM account_analytic_line \
WHERE account_id =ANY(%s) AND date>=%s AND date<=%s AND amount>0", (ids,date1, date2,))
WHERE account_id =ANY(%s) AND date>=%s AND date<=%s AND amount>0", (ids, 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 =ANY(%s) AND date>=%s AND date<=%s AND amount<0", (ids,date1, date2,))
WHERE account_id =ANY(%s) AND date>=%s AND date<=%s AND amount<0", (ids, 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)
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 =ANY(%s) AND date>=%s AND date<=%s", (ids,date1, date2,))
WHERE account_id =ANY(%s) AND date>=%s AND date<=%s", (ids, 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)
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)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -26,7 +26,7 @@ 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=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines_g': self._lines_g,
'lines_a': self._lines_a,
@ -54,7 +54,7 @@ class account_analytic_quantity_cost_ledger(report_sxw.rml_parse):
AND aa.active \
AND (aal.journal_id =ANY(%s) ) \
GROUP BY aa.code, aa.name, aa.id ORDER BY aa.code",
(account_id, date1, date2,journal_ids))
(account_id, date1, date2, journal_ids))
res = self.cr.dictfetchall()
return res
@ -81,7 +81,7 @@ class account_analytic_quantity_cost_ledger(report_sxw.rml_parse):
AND (aal.date>=%s) AND (aal.date<=%s) \
AND (aal.journal_id=aaj.id) AND (aaj.id =ANY(%s)) \
ORDER BY aal.date, aaj.code, aal.code",
(general_account_id, account_id, date1, date2,journal_ids,))
(general_account_id, account_id, date1, date2, journal_ids,))
res = self.cr.dictfetchall()
return res
@ -97,7 +97,7 @@ class account_analytic_quantity_cost_ledger(report_sxw.rml_parse):
FROM account_analytic_line \
WHERE account_id = %s AND date >= %s AND date <= %s \
AND journal_id =ANY(%s)",
(account_id, date1, date2,journal_ids,))
(account_id, date1, date2, journal_ids,))
return self.cr.fetchone()[0] or 0.0
def _sum_quantity(self, accounts, date1, date2, journals):
@ -108,13 +108,13 @@ class account_analytic_quantity_cost_ledger(report_sxw.rml_parse):
self.cr.execute("SELECT sum(unit_amount) \
FROM account_analytic_line \
WHERE account_id =ANY(%s) AND date>=%s AND date<=%s",
(date1, date2,ids,))
(date1, date2, ids,))
else:
journal_ids = journals[0][2]
self.cr.execute("SELECT sum(unit_amount) \
FROM account_analytic_line \
WHERE account_id =ANY(%s) AND date >= %s AND date <= %s \
AND journal_id =ANY(%s)",(ids,date1, date2,journal_ids))
AND journal_id =ANY(%s)", (ids, date1, date2, journal_ids))
return self.cr.fetchone()[0] or 0.0
report_sxw.report_sxw('report.account.analytic.account.quantity_cost_ledger',

View File

@ -29,15 +29,15 @@ dates_form = '''<?xml version="1.0"?>
</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')]}
'actions': [],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -30,8 +30,8 @@ dates_form = '''<?xml version="1.0"?>
</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')},
'empty_acc': {'string':'Empty Accounts ? ', 'type':'boolean', 'help':'Check if you want to display Accounts with 0 balance too.'},
}
@ -39,8 +39,8 @@ dates_fields = {
class wizard_report(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'), ('report','Print')]}
'actions': [],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -32,9 +32,9 @@ _form = '''<?xml version="1.0"?>
</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'},
}
@ -47,8 +47,8 @@ class wizard_report(wizard.interface):
'arch': _form,
'fields': _fields,
'state': [
('end','Cancel'),
('report','Print')
('end', 'Cancel'),
('report', 'Print')
]
}
},

View File

@ -29,15 +29,15 @@ dates_form = '''<?xml version="1.0"?>
</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')]}
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -29,15 +29,15 @@ dates_form = '''<?xml version="1.0"?>
</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')]}
'actions': [],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -29,15 +29,15 @@ dates_form = '''<?xml version="1.0"?>
</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')]}
'actions': [],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -24,19 +24,19 @@ import pooler
import time
from tools.translate import _
def _action_open_window(self, cr, uid, data, context):
def _action_open_window(self, cr, uid, data, context):
domain = []
from_date = data['form']['from_date']
to_date = data['form']['to_date']
if from_date and to_date:
domain = [('date','>=',from_date),('date','<=',to_date)]
domain = [('date', '>=', from_date), ('date', '<=', to_date)]
elif from_date:
domain = [('date','>=',from_date)]
domain = [('date', '>=', from_date)]
elif to_date:
domain = [('date','<=',to_date)]
domain = [('date', '<=', to_date)]
mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data')
result = mod_obj._get_id(cr, uid, 'account', 'view_account_analytic_line_filter')
id = mod_obj.read(cr, uid, result, ['res_id'])
id = mod_obj.read(cr, uid, result, ['res_id'])
return {
'name': _('Analytic Entries'),
@ -45,7 +45,7 @@ def _action_open_window(self, cr, uid, data, context):
'res_model': 'account.analytic.line',
'type': 'ir.actions.act_window',
'domain': domain,
'search_view_id': id['res_id'],}
'search_view_id': id['res_id'], }
class account_analytic_line(wizard.interface):
@ -73,7 +73,7 @@ class account_analytic_line(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type': 'form', 'arch':form1, 'fields':form1_fields, 'state': [('end', 'Cancel','gtk-cancel'),('open', 'Open Entries','gtk-ok')]}
'result': {'type': 'form', 'arch':form1, 'fields':form1_fields, 'state': [('end', 'Cancel', 'gtk-cancel'), ('open', 'Open Entries', 'gtk-ok')]}
},
'open': {
'actions': [],

View File

@ -57,8 +57,8 @@ class wizard_analytic_account_chart(wizard.interface):
if data['form']['from_date']:
result_context.update({'from_date' : data['form']['from_date']})
if data['form']['to_date']:
result_context.update({'to_date' : data['form']['to_date']})
result_context.update({'to_date' : data['form']['to_date']})
result['context'] = str(result_context)
return result

View File

@ -45,36 +45,36 @@ class account_balance(report_sxw.rml_parse):
self.context = context
def get_fiscalyear(self, form):
res=[]
res = []
if form.has_key('fiscalyear'):
fisc_id = form['fiscalyear']
if not (fisc_id):
return ''
self.cr.execute("select name from account_fiscalyear where id = %s" , (int(fisc_id),))
res=self.cr.fetchone()
res = self.cr.fetchone()
return res and res[0] or ''
def get_periods(self, form):
result=''
result = ''
if form.has_key('periods') and form['periods'][0][2]:
period_ids = form['periods'][0][2]
self.cr.execute("select name from account_period where id =ANY(%s)" ,(period_ids))
self.cr.execute("select name from account_period where id =ANY(%s)" , (period_ids))
res = self.cr.fetchall()
len_res = len(res)
for r in res:
if (r == res[len_res-1]):
result+=r[0]+". "
if (r == res[len_res - 1]):
result += r[0] + ". "
else:
result+=r[0]+", "
result += r[0] + ", "
else:
fy_obj = self.pool.get('account.fiscalyear').browse(self.cr,self.uid,form['fiscalyear'])
fy_obj = self.pool.get('account.fiscalyear').browse(self.cr, self.uid, form['fiscalyear'])
res = fy_obj.period_ids
len_res = len(res)
for r in res:
if r == res[len_res-1]:
result+=r.name+". "
if r == res[len_res - 1]:
result += r.name + ". "
else:
result+=r.name+", "
result += r.name + ", "
return str(result and result[:-1]) or ''
@ -85,24 +85,24 @@ class account_balance(report_sxw.rml_parse):
if not ids:
return []
if not done:
done={}
done = {}
if form.has_key('Account_list') and form['Account_list']:
ids = [form['Account_list']]
del form['Account_list']
res={}
result_acc=[]
res = {}
result_acc = []
ctx = self.context.copy()
ctx['state'] = form['context'].get('state','all')
ctx['state'] = form['context'].get('state', 'all')
ctx['fiscalyear'] = form['fiscalyear']
if form['state']=='byperiod' :
if form['state'] == 'byperiod' :
ctx['periods'] = form['periods'][0][2]
elif form['state']== 'bydate':
elif form['state'] == 'bydate':
ctx['date_from'] = form['date_from']
ctx['date_to'] = form['date_to']
ctx['date_to'] = form['date_to']
elif form['state'] == 'all' :
ctx['periods'] = form['periods'][0][2]
ctx['date_from'] = form['date_from']
ctx['date_to'] = form['date_to']
ctx['date_to'] = form['date_to']
# accounts = self.pool.get('account.account').browse(self.cr, self.uid, ids, ctx)
# def cmp_code(x, y):
# return cmp(x.code, y.code)
@ -110,7 +110,7 @@ class account_balance(report_sxw.rml_parse):
child_ids = self.pool.get('account.account')._get_children_and_consol(self.cr, self.uid, ids, ctx)
if child_ids:
ids = child_ids
accounts = self.pool.get('account.account').read(self.cr, self.uid, ids,['type','code','name','debit','credit','balance','parent_id'], ctx)
accounts = self.pool.get('account.account').read(self.cr, self.uid, ids, ['type', 'code', 'name', 'debit', 'credit', 'balance', 'parent_id'], ctx)
for account in accounts:
if account['id'] in done:
continue

View File

@ -29,7 +29,7 @@ from report import report_sxw
class journal_print(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(journal_print, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines': self.lines,
'sum_debit': self._sum_debit,
@ -37,27 +37,27 @@ class journal_print(report_sxw.rml_parse):
})
def lines(self, period_id, journal_id, sort_selection='date', *args):
if type(period_id)==type([]):
if type(period_id) == type([]):
ids_final = []
for journal in journal_id:
for period in period_id:
ids_journal_period = self.pool.get('account.journal.period').search(self.cr,self.uid, [('journal_id','=',journal),('period_id','=',period)])
ids_journal_period = self.pool.get('account.journal.period').search(self.cr, self.uid, [('journal_id', '=', journal), ('period_id', '=', period)])
if ids_journal_period:
self.cr.execute('update account_journal_period set state=%s where journal_id=%s and period_id=%s and state=%s', ('printed',journal,period,'draft'))
self.cr.execute('update account_journal_period set state=%s where journal_id=%s and period_id=%s and state=%s', ('printed', journal, period, 'draft'))
self.cr.commit()
self.cr.execute('select id from account_move_line where period_id=%s and journal_id=%s and state<>\'draft\' order by ('+ sort_selection +'),id', (period, journal))
self.cr.execute('select id from account_move_line where period_id=%s and journal_id=%s and state<>\'draft\' order by (' + sort_selection + '),id', (period, journal))
ids = map(lambda x: x[0], self.cr.fetchall())
ids_final.append(ids)
line_ids = []
for line_id in ids_final:
a = self.pool.get('account.move.line').browse(self.cr, self.uid, line_id )
a = self.pool.get('account.move.line').browse(self.cr, self.uid, line_id)
line_ids.append(a)
return line_ids
self.cr.execute('update account_journal_period set state=%s where journal_id=%s and period_id=%s and state=%s', ('printed',journal_id,period_id,'draft'))
self.cr.execute('update account_journal_period set state=%s where journal_id=%s and period_id=%s and state=%s', ('printed', journal_id, period_id, 'draft'))
self.cr.commit()
self.cr.execute('select id from account_move_line where period_id=%s and journal_id=%s 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 )
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=%s and journal_id=%s and state<>\'draft\'', (period_id, journal_id))
@ -66,8 +66,8 @@ class journal_print(report_sxw.rml_parse):
def _sum_credit(self, period_id, journal_id):
self.cr.execute('select sum(credit) from account_move_line where period_id=%s and journal_id=%s 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,header=False)
report_sxw.report_sxw('report.account.journal.period.print.wiz', 'account.journal.period', 'addons/account/report/wizard_account_journal.rml', parser=journal_print,header=False)
report_sxw.report_sxw('report.account.journal.period.print', 'account.journal.period', 'addons/account/report/account_journal.rml', parser=journal_print, header=False)
report_sxw.report_sxw('report.account.journal.period.print.wiz', 'account.journal.period', 'addons/account/report/wizard_account_journal.rml', parser=journal_print, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -57,7 +57,7 @@ class account_tax_code_report(rml_parse.rml_parse):
})
def get_line(self, obj):
line_ids = self.pool.get('account.move.line').search(self.cr, self.uid, [('tax_code_id','=',obj.id)])
line_ids = self.pool.get('account.move.line').search(self.cr, self.uid, [('tax_code_id', '=', obj.id)])
if not line_ids: return []
return map(_record_to_report_line,

View File

@ -46,12 +46,12 @@ class aged_trial_report(rml_parse.rml_parse):
def _get_lines(self, form):
if (form['result_selection'] == 'customer' ):
if (form['result_selection'] == 'customer'):
self.ACCOUNT_TYPE = ['receivable']
elif (form['result_selection'] == 'supplier'):
self.ACCOUNT_TYPE = ['payable']
else:
self.ACCOUNT_TYPE = ['payable','receivable']
self.ACCOUNT_TYPE = ['payable', 'receivable']
res = []
@ -66,7 +66,7 @@ class aged_trial_report(rml_parse.rml_parse):
OR (reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))
AND (line.partner_id=res_partner.id)
AND (account_account.company_id = %s)
ORDER BY res_partner.name""" , (form['date1'],form['company_id']))
ORDER BY res_partner.name""" , (form['date1'], form['company_id']))
partners = self.cr.dictfetchall()
## mise a 0 du total
for i in range(7):
@ -87,7 +87,7 @@ class aged_trial_report(rml_parse.rml_parse):
OR (reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))
AND (account_account.company_id = %s)
AND account_account.active
GROUP BY partner_id""" , (self.ACCOUNT_TYPE, partner_ids,form['date1'],form['company_id'],))
GROUP BY partner_id""" , (self.ACCOUNT_TYPE, partner_ids, form['date1'], form['company_id'],))
t = self.cr.fetchall()
for i in t:
totals[i[0]] = i[1]
@ -105,7 +105,7 @@ class aged_trial_report(rml_parse.rml_parse):
OR (reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))
AND (account_account.company_id = %s)
AND account_account.active
GROUP BY partner_id""", (self.ACCOUNT_TYPE, form['date1'], partner_ids,form['date1'], form['company_id'],))
GROUP BY partner_id""", (self.ACCOUNT_TYPE, form['date1'], partner_ids, form['date1'], form['company_id'],))
t = self.cr.fetchall()
for i in t:
future_past[i[0]] = i[1]
@ -139,7 +139,7 @@ class aged_trial_report(rml_parse.rml_parse):
OR (reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))
AND (account_account.company_id = %s)
AND account_account.active
GROUP BY partner_id""" , (self.ACCOUNT_TYPE, form[str(i)]['start'], form[str(i)]['stop'],partner_ids ,form['date1'] ,form['company_id'],))
GROUP BY partner_id""" , (self.ACCOUNT_TYPE, form[str(i)]['start'], form[str(i)]['stop'], partner_ids , form['date1'] , form['company_id'],))
t = self.cr.fetchall()
d = {}
@ -177,11 +177,11 @@ class aged_trial_report(rml_parse.rml_parse):
values[str(i)] = during and during[0] or ""
total = False
if totals.has_key( partner['id'] ):
if totals.has_key(partner['id']):
total = [ totals[partner['id']] ]
values['total'] = total and total[0] or 0.0
## Add for total
self.total_account[(i+1)] = self.total_account[(i+1)] + (total and total[0] or 0.0)
self.total_account[(i + 1)] = self.total_account[(i + 1)] + (total and total[0] or 0.0)
values['name'] = partner['name']
#t = 0.0
#for i in range(5)+['direction']:
@ -195,20 +195,20 @@ class aged_trial_report(rml_parse.rml_parse):
totals = {}
for r in res:
total += float(r['total'] or 0.0)
for i in range(5)+['direction']:
for i in range(5) + ['direction']:
totals.setdefault(str(i), 0.0)
totals[str(i)] += float(r[str(i)] or 0.0)
return res
def _get_total(self,pos):
def _get_total(self, pos):
period = self.total_account[int(pos)]
return period
def _get_direction(self,pos):
def _get_direction(self, pos):
period = self.total_account[int(pos)]
return period
def _get_for_period(self,pos):
def _get_for_period(self, pos):
period = self.total_account[int(pos)]
return period
@ -220,7 +220,7 @@ class aged_trial_report(rml_parse.rml_parse):
report_sxw.report_sxw('report.account.aged_trial_balance', 'res.partner',
'addons/account/report/aged_trial_balance.rml',parser=aged_trial_report,header=False)
'addons/account/report/aged_trial_balance.rml', parser=aged_trial_report, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -36,15 +36,15 @@ class journal_print(report_sxw.rml_parse):
})
def lines(self, period_id, journal_id, *args):
if type(period_id)==type([]):
if type(period_id) == type([]):
ids_final = []
for journal in journal_id:
for period in period_id:
ids_journal_period = self.pool.get('account.journal.period').search(self.cr,self.uid, [('journal_id','=',journal),('period_id','=',period)])
ids_journal_period = self.pool.get('account.journal.period').search(self.cr, self.uid, [('journal_id', '=', journal), ('period_id', '=', period)])
if ids_journal_period:
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=%s and l.journal_id=%s and l.state<>\'draft\' group by a.id, a.code, a.name, l.journal_id, l.period_id', (period, journal))
res = self.cr.dictfetchall()
a = {'journal':self.pool.get('account.journal').browse(self.cr, self.uid, journal),'period':self.pool.get('account.period').browse(self.cr, self.uid, period)}
a = {'journal':self.pool.get('account.journal').browse(self.cr, self.uid, journal), 'period':self.pool.get('account.period').browse(self.cr, self.uid, period)}
res[0].update(a)
ids_final.append(res)
return ids_final
@ -59,8 +59,8 @@ class journal_print(report_sxw.rml_parse):
def _sum_credit(self, period_id, journal_id):
self.cr.execute('select sum(credit) from account_move_line where period_id=%s and journal_id=%s 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, header=False)
report_sxw.report_sxw('report.account.central.journal.wiz', 'account.journal.period', 'addons/account/report/wizard_central_journal.rml',parser=journal_print, header=False)
report_sxw.report_sxw('report.account.central.journal', 'account.journal.period', 'addons/account/report/central_journal.rml', parser=journal_print, header=False)
report_sxw.report_sxw('report.account.central.journal.wiz', 'account.journal.period', 'addons/account/report/wizard_central_journal.rml', parser=journal_print, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -29,7 +29,7 @@ from report import report_sxw
class journal_print(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(journal_print, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines': self.lines,
'periods': self.periods,
@ -39,12 +39,12 @@ class journal_print(report_sxw.rml_parse):
'sum_credit': self._sum_credit
})
def set_context(self, objects, data, ids, report_type = None):
def set_context(self, objects, data, ids, report_type=None):
super(journal_print, self).set_context(objects, data, ids, report_type)
self.cr.execute('select period_id, journal_id from account_journal_period where id =ANY(%s)',(ids,))
self.cr.execute('select period_id, journal_id from account_journal_period where id =ANY(%s)', (ids,))
res = self.cr.fetchall()
self.period_ids = map(lambda x:x[0],res)
self.journal_ids = map(lambda x:x[1],res)
self.period_ids = map(lambda x:x[0], res)
self.journal_ids = map(lambda x:x[1], res)
# returns a list of period objs
def periods(self, journal_period_objs):
@ -59,11 +59,11 @@ class journal_print(report_sxw.rml_parse):
return map(lambda x: x.period_id, filtered_objs)
def lines(self, period_id, journal_id=[]):
if type(period_id)==type([]):
if type(period_id) == type([]):
ids_final = []
for journal in journal_id:
for period in period_id:
ids_journal_period = self.pool.get('account.journal.period').search(self.cr,self.uid, [('journal_id','=',journal),('period_id','=',period)])
ids_journal_period = self.pool.get('account.journal.period').search(self.cr, self.uid, [('journal_id', '=', journal), ('period_id', '=', period)])
if ids_journal_period:
ids_final.append(ids_journal_period[0])
data_jour_period = self.pool.get('account.journal.period').browse(self.cr, self.uid, ids_final)
@ -74,7 +74,7 @@ class journal_print(report_sxw.rml_parse):
periods.append(data.period_id.id)
for period in periods:
period_data = self.pool.get('account.period').browse(self.cr, self.uid, period)
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=%s and journal_id =ANY(%s) and l.state<>\'draft\' group by j.id, j.code, j.name', (period,journal_id,))
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=%s and journal_id =ANY(%s) and l.state<>\'draft\' group by j.id, j.code, j.name', (period, journal_id,))
res = self.cr.dictfetchall()
res[0].update({'period_name':period_data.name})
res[0].update({'pid':period})
@ -82,48 +82,48 @@ class journal_print(report_sxw.rml_parse):
return lines_data
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=%s and journal_id =ANY(%s) and l.state<>\'draft\' group by j.id, j.code, j.name', (period_id,self.journal_ids,))
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=%s and journal_id =ANY(%s) and l.state<>\'draft\' group by j.id, j.code, j.name', (period_id, self.journal_ids,))
res = self.cr.dictfetchall()
return res
def _sum_debit_period(self, period_id,journal_id=None):
if type(journal_id)==type([]):
self.cr.execute('select sum(debit) from account_move_line where period_id=%s and journal_id =ANY(%s) and state<>\'draft\'', (period_id,journal_id,))
def _sum_debit_period(self, period_id, journal_id=None):
if type(journal_id) == type([]):
self.cr.execute('select sum(debit) from account_move_line where period_id=%s and journal_id =ANY(%s) and state<>\'draft\'', (period_id, journal_id,))
return self.cr.fetchone()[0] or 0.0
if not self.journal_ids:
return 0.0
self.cr.execute('select sum(debit) from account_move_line where period_id=%s and journal_id =ANY(%s) and state<>\'draft\'', (period_id,self.journal_ids,))
self.cr.execute('select sum(debit) from account_move_line where period_id=%s and journal_id =ANY(%s) and state<>\'draft\'', (period_id, self.journal_ids,))
return self.cr.fetchone()[0] or 0.0
def _sum_credit_period(self, period_id,journal_id=None):
if type(journal_id)==type([]):
self.cr.execute('select sum(credit) from account_move_line where period_id=%s and journal_id =ANY(%s) and state<>\'draft\'', (period_id,journal_id,))
def _sum_credit_period(self, period_id, journal_id=None):
if type(journal_id) == type([]):
self.cr.execute('select sum(credit) from account_move_line where period_id=%s and journal_id =ANY(%s) and state<>\'draft\'', (period_id, journal_id,))
return self.cr.fetchone()[0] or 0.0
if not self.journal_ids:
return 0.0
self.cr.execute('select sum(credit) from account_move_line where period_id=%s and journal_id =ANY(%s) and state<>\'draft\'', (period_id,self.journal_ids,))
self.cr.execute('select sum(credit) from account_move_line where period_id=%s and journal_id =ANY(%s) and state<>\'draft\'', (period_id, self.journal_ids,))
return self.cr.fetchone()[0] or 0.0
def _sum_debit(self,period_id=None,journal_id=None):
if type(period_id)==type([]):
self.cr.execute('select sum(debit) from account_move_line where period_id =ANY(%s) and journal_id =ANY(%s) and state<>\'draft\'',(period_id,journal_id,))
def _sum_debit(self, period_id=None, journal_id=None):
if type(period_id) == type([]):
self.cr.execute('select sum(debit) from account_move_line where period_id =ANY(%s) and journal_id =ANY(%s) and state<>\'draft\'', (period_id, journal_id,))
return self.cr.fetchone()[0] or 0.0
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 =ANY(%s) and journal_id =ANY(%s) and state<>\'draft\'',(self.period_ids,self.journal_ids,))
self.cr.execute('select sum(debit) from account_move_line where period_id =ANY(%s) and journal_id =ANY(%s) and state<>\'draft\'', (self.period_ids, self.journal_ids,))
return self.cr.fetchone()[0] or 0.0
def _sum_credit(self,period_id=None,journal_id=None):
if type(period_id)==type([]):
self.cr.execute('select sum(credit) from account_move_line where period_id =ANY(%s) and journal_id =ANY(%s) and state<>\'draft\'',(period_id,journal_id,))
def _sum_credit(self, period_id=None, journal_id=None):
if type(period_id) == type([]):
self.cr.execute('select sum(credit) from account_move_line where period_id =ANY(%s) and journal_id =ANY(%s) and state<>\'draft\'', (period_id, journal_id,))
return self.cr.fetchone()[0] or 0.0
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 =ANY(%s) and journal_id =ANY(%s) and state<>\'draft\'',(self.period_ids,self.journal_ids,))
self.cr.execute('select sum(credit) from account_move_line where period_id =ANY(%s) and journal_id =ANY(%s) and state<>\'draft\'', (self.period_ids, self.journal_ids,))
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)
report_sxw.report_sxw('report.account.general.journal.wiz', 'account.journal.period', 'addons/account/report/wizard_general_journal.rml',parser=journal_print, header=False)
report_sxw.report_sxw('report.account.general.journal', 'account.journal.period', 'addons/account/report/general_journal.rml', parser=journal_print)
report_sxw.report_sxw('report.account.general.journal.wiz', 'account.journal.period', 'addons/account/report/wizard_general_journal.rml', parser=journal_print, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -36,7 +36,7 @@ class general_ledger(rml_parse.rml_parse):
def set_context(self, objects, data, ids, report_type = None):
def set_context(self, objects, data, ids, report_type=None):
##
self.borne_date = self.get_min_date(data['form'])
##
@ -58,7 +58,7 @@ class general_ledger(rml_parse.rml_parse):
self.tot_currency = 0.0
self.period_sql = ""
self.sold_accounts = {}
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines': self.lines,
'sum_debit_account': self._sum_debit_account,
@ -71,7 +71,7 @@ class general_ledger(rml_parse.rml_parse):
'sum_currency_amount_account': self._sum_currency_amount_account
})
self.context = context
def _calc_contrepartie(self,cr,uid,ids, context={}):
def _calc_contrepartie(self, cr, uid, ids, context={}):
result = {}
#for id in ids:
# result.setdefault(id, False)
@ -89,23 +89,23 @@ class general_ledger(rml_parse.rml_parse):
# We have the account ID we will search all account move line from now until this time
# We are in the case of we are on the top of the account move Line
cr.execute('SELECT distinct(ac.code) as code_rest,ac.name as name_rest from account_account AS ac, account_move_line mv\
where ac.id = mv.account_id and mv.move_id = %s and mv.account_id <> %s' ,(num_id_move,account_id,))
where ac.id = mv.account_id and mv.move_id = %s and mv.account_id <> %s' , (num_id_move, account_id,))
res_mv = cr.dictfetchall()
# we need a result more than 2 line to make the test so we will made the the on 1 because we have exclude the current line
if (len(res_mv) >=1):
if (len(res_mv) >= 1):
concat = ''
rup_id = 0
for move_rest in res_mv:
concat = concat + move_rest['code_rest'] + '|'
result[account_line.id] = concat
if rup_id >5:
if rup_id > 5:
# we need to stop the computing and to escape but before we will add "..."
result[account_line.id] = concat + '...'
break
rup_id+=1
rup_id += 1
return result
def get_min_date(self,form):
def get_min_date(self, form):
## Get max born from account_fiscal year
#
@ -121,10 +121,10 @@ class general_ledger(rml_parse.rml_parse):
periods = form['periods'][0][2]
if not periods:
self.cr.execute("""
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.fiscalyear_id = %s""",(form['fiscalyear'],))
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.fiscalyear_id = %s""", (form['fiscalyear'],))
else:
self.cr.execute("""
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.id =ANY(%s)""",(periods,))
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.id =ANY(%s)""", (periods,))
res = self.cr.dictfetchall()
borne_min = res[0]['start_date']
borne_max = res[0]['stop_date']
@ -135,20 +135,20 @@ class general_ledger(rml_parse.rml_parse):
periods = form['periods'][0][2]
if not periods:
self.cr.execute("""
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.fiscalyear_id = %s""",(form['fiscalyear'],))
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.fiscalyear_id = %s""", (form['fiscalyear'],))
else:
self.cr.execute("""
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.id =ANY(%s)""",(periods,))
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.id =ANY(%s)""", (periods,))
res = self.cr.dictfetchall()
period_min = res[0]['start_date']
period_max = res[0]['stop_date']
date_min = form['date_from']
date_max = form['date_to']
if period_min<date_min:
if period_min < date_min:
borne_min = period_min
else :
borne_min = date_min
if date_max<period_max:
if date_max < period_max:
borne_max = period_max
else :
borne_max = date_max
@ -178,7 +178,7 @@ class general_ledger(rml_parse.rml_parse):
## We will make the test for period or date
## We will now make the test
#
ctx['state'] = form['context'].get('state','all')
ctx['state'] = form['context'].get('state', 'all')
if form.has_key('fiscalyear'):
ctx['fiscalyear'] = form['fiscalyear']
ctx['periods'] = form['periods'][0][2]
@ -191,28 +191,28 @@ class general_ledger(rml_parse.rml_parse):
if account and account.child_consol_ids: # add ids of consolidated childs also of selected account
ctx['consolidate_childs'] = True
ctx['account_id'] = account.id
ids_acc = self.pool.get('account.account').search(self.cr, self.uid,[('parent_id', 'child_of', [account.id])], context=ctx)
ids_acc = self.pool.get('account.account').search(self.cr, self.uid, [('parent_id', 'child_of', [account.id])], context=ctx)
for child_id in ids_acc:
child_account = self.pool.get('account.account').browse(self.cr, self.uid, child_id)
sold_account = self._sum_solde_account(child_account,form)
sold_account = self._sum_solde_account(child_account, form)
self.sold_accounts[child_account.id] = sold_account
if form['display_account'] == 'bal_mouvement':
if child_account.type != 'view' \
and len(self.pool.get('account.move.line').search(self.cr, self.uid,
[('account_id','=',child_account.id)],
[('account_id', '=', child_account.id)],
context=ctx)) <> 0 :
res.append(child_account)
elif form['display_account'] == 'bal_solde':
if child_account.type != 'view' \
and len(self.pool.get('account.move.line').search(self.cr, self.uid,
[('account_id','=',child_account.id)],
[('account_id', '=', child_account.id)],
context=ctx)) <> 0 :
if ( sold_account <> 0.0):
if (sold_account <> 0.0):
res.append(child_account)
else:
if child_account.type != 'view' \
and len(self.pool.get('account.move.line').search(self.cr, self.uid,
[('account_id','>=',child_account.id)],
[('account_id', '>=', child_account.id)],
context=ctx)) <> 0 :
res.append(child_account)
##
@ -223,7 +223,7 @@ class general_ledger(rml_parse.rml_parse):
## We will now compute solde initiaux
for move in res:
self.cr.execute("""SELECT sum(l.debit) AS sum_debit, sum(l.credit) AS sum_credit FROM account_move_line l \
WHERE l.account_id = %s AND l.date < %s AND l.date > %s""",(move.id,self.borne_date['max_date'],self.borne_date['min_date']))
WHERE l.account_id = %s AND l.date < %s AND l.date > %s""", (move.id, self.borne_date['max_date'], self.borne_date['min_date']))
resultat = self.cr.dictfetchall()
if resultat[0] :
if resultat[0]['sum_debit'] == None:
@ -276,11 +276,11 @@ class general_ledger(rml_parse.rml_parse):
for l in res:
line = self.pool.get('account.move.line').browse(self.cr, self.uid, l['id'])
l['move'] = line.move_id.name
self.cr.execute('Select id from account_invoice where move_id =%s',(line.move_id.id,))
self.cr.execute('Select id from account_invoice where move_id =%s', (line.move_id.id,))
tmpres = self.cr.dictfetchall()
if len(tmpres) > 0 :
inv = self.pool.get('account.invoice').browse(self.cr, self.uid, tmpres[0]['id'])
l['ref'] = inv_types[inv.type] + ': '+str(inv.number)
l['ref'] = inv_types[inv.type] + ': ' + str(inv.number)
if line.partner_id :
l['partner'] = line.partner_id.name
else :
@ -289,7 +289,7 @@ class general_ledger(rml_parse.rml_parse):
# c = time.strptime(l['date'],"%Y-%m-%d")
# l['date'] = time.strftime("%d-%m-%Y",c)
l['progress'] = sum
l['line_corresp'] = self._calc_contrepartie(self.cr,self.uid,[l['id']])[l['id']]
l['line_corresp'] = self._calc_contrepartie(self.cr, self.uid, [l['id']])[l['id']]
# Modification du amount Currency
if (l['credit'] > 0):
if l['amount_currency'] != None:
@ -304,7 +304,7 @@ class general_ledger(rml_parse.rml_parse):
self.cr.execute("SELECT sum(debit) "\
"FROM account_move_line l "\
"WHERE l.account_id = %s AND "+self.query,(account.id,))
"WHERE l.account_id = %s AND " + self.query, (account.id,))
## Add solde init to the result
#
sum_debit = self.cr.fetchone()[0] or 0.0
@ -318,7 +318,7 @@ class general_ledger(rml_parse.rml_parse):
self.cr.execute("SELECT sum(credit) "\
"FROM account_move_line l "\
"WHERE l.account_id = %s AND "+ self.query,(account.id,))
"WHERE l.account_id = %s AND " + self.query, (account.id,))
## Add solde init to the result
#
sum_credit = self.cr.fetchone()[0] or 0.0
@ -332,7 +332,7 @@ class general_ledger(rml_parse.rml_parse):
def _sum_solde_account(self, account, form):
self.cr.execute("SELECT (sum(debit) - sum(credit)) as tot_solde "\
"FROM account_move_line l "\
"WHERE l.account_id = %s AND "+ self.query,(account.id,))
"WHERE l.account_id = %s AND " + self.query, (account.id,))
sum_solde = self.cr.fetchone()[0] or 0.0
if form.get('soldeinit', False):
sum_solde += account.init_debit - account.init_credit
@ -344,7 +344,7 @@ class general_ledger(rml_parse.rml_parse):
return 0.0
self.cr.execute("SELECT sum(debit) "\
"FROM account_move_line l "\
"WHERE l.account_id =ANY(%s) AND "+ self.query,(self.child_ids,))
"WHERE l.account_id =ANY(%s) AND " + self.query, (self.child_ids,))
sum_debit = self.cr.fetchone()[0] or 0.0
return sum_debit
@ -353,7 +353,7 @@ class general_ledger(rml_parse.rml_parse):
return 0.0
self.cr.execute("SELECT sum(credit) "\
"FROM account_move_line l "\
"WHERE l.account_id =ANY(%s) AND "+ self.query,(self.child_ids,))
"WHERE l.account_id =ANY(%s) AND " + self.query, (self.child_ids,))
## Add solde init to the result
#
sum_credit = self.cr.fetchone()[0] or 0.0
@ -364,14 +364,14 @@ class general_ledger(rml_parse.rml_parse):
return 0.0
self.cr.execute("SELECT (sum(debit) - sum(credit)) as tot_solde "\
"FROM account_move_line l "\
"WHERE l.account_id =ANY(%s) AND "+ self.query,(self.child_ids,))
"WHERE l.account_id =ANY(%s) AND " + self.query, (self.child_ids,))
sum_solde = self.cr.fetchone()[0] or 0.0
return sum_solde
def _set_get_account_currency_code(self, account_id):
self.cr.execute("SELECT c.code as code "\
"FROM res_currency c,account_account as ac "\
"WHERE ac.id = %s AND ac.currency_id = c.id",(account_id,))
"WHERE ac.id = %s AND ac.currency_id = c.id", (account_id,))
result = self.cr.fetchone()
if result:
self.account_currency = result[0]

View File

@ -37,7 +37,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
_name = 'report.account.general.ledger_landscape'
def set_context(self, objects, data, ids, report_type = None):
def set_context(self, objects, data, ids, report_type=None):
##
self.borne_date = self.get_min_date(data['form'])
##
@ -49,7 +49,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
objects = self.pool.get('account.account').browse(self.cr, self.uid, new_ids)
super(general_ledger_landscape, self).set_context(objects, data, new_ids,report_type)
super(general_ledger_landscape, self).set_context(objects, data, new_ids, report_type)
def __init__(self, cr, uid, name, context):
super(general_ledger_landscape, self).__init__(cr, uid, name, context=context)
@ -59,7 +59,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
self.tot_currency = 0.0
self.period_sql = ""
self.sold_accounts = {}
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines': self.lines,
'sum_debit_account': self._sum_debit_account,
@ -72,7 +72,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
'sum_currency_amount_account': self._sum_currency_amount_account
})
self.context = context
def _calc_contrepartie(self,cr,uid,ids, context={}):
def _calc_contrepartie(self, cr, uid, ids, context={}):
result = {}
#for id in ids:
# result.setdefault(id, False)
@ -90,23 +90,23 @@ class general_ledger_landscape(rml_parse.rml_parse):
# We have the account ID we will search all account move line from now until this time
# We are in the case of we are on the top of the account move Line
cr.execute('SELECT distinct(ac.code) as code_rest,ac.name as name_rest from account_account AS ac, account_move_line mv\
where ac.id = mv.account_id and mv.move_id = %s and mv.account_id <> %s' , (num_id_move,account_id,))
where ac.id = mv.account_id and mv.move_id = %s and mv.account_id <> %s' , (num_id_move, account_id,))
res_mv = cr.dictfetchall()
# we need a result more than 2 line to make the test so we will made the the on 1 because we have exclude the current line
if (len(res_mv) >=1):
if (len(res_mv) >= 1):
concat = ''
rup_id = 0
for move_rest in res_mv:
concat = concat + move_rest['code_rest'] + '|'
result[account_line.id] = concat
if rup_id >5:
if rup_id > 5:
# we need to stop the computing and to escape but before we will add "..."
result[account_line.id] = concat + '...'
break
rup_id+=1
rup_id += 1
return result
def get_min_date(self,form):
def get_min_date(self, form):
## Get max born from account_fiscal year
#
@ -122,10 +122,10 @@ class general_ledger_landscape(rml_parse.rml_parse):
periods = form['periods'][0][2]
if not periods:
self.cr.execute("""
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.fiscalyear_id = %s""" ,(form['fiscalyear'],))
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.fiscalyear_id = %s""" , (form['fiscalyear'],))
else:
self.cr.execute("""
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.id =ANY(%s)""",(periods,))
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.id =ANY(%s)""", (periods,))
res = self.cr.dictfetchall()
borne_min = res[0]['start_date']
@ -137,21 +137,21 @@ class general_ledger_landscape(rml_parse.rml_parse):
periods = form['periods'][0][2]
if not periods:
self.cr.execute("""
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.fiscalyear_id = = %s""" ,(form['fiscalyear'],))
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.fiscalyear_id = = %s""" , (form['fiscalyear'],))
else:
self.cr.execute("""
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.id =ANY(%s)""",(periods,))
Select min(p.date_start) as start_date,max(p.date_stop) as stop_date from account_period as p where p.id =ANY(%s)""", (periods,))
res = self.cr.dictfetchall()
period_min = res[0]['start_date']
period_max = res[0]['stop_date']
date_min = form['date_from']
date_max = form['date_to']
if period_min<date_min:
if period_min < date_min:
borne_min = period_min
else :
borne_min = date_min
if date_max<period_max:
if date_max < period_max:
borne_max = period_max
else :
borne_max = date_max
@ -180,7 +180,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
## We will make the test for period or date
## We will now make the test
#
ctx['state'] = form['context'].get('state','all')
ctx['state'] = form['context'].get('state', 'all')
if form.has_key('fiscalyear'):
ctx['fiscalyear'] = form['fiscalyear']
ctx['periods'] = form['periods'][0][2]
@ -194,28 +194,28 @@ class general_ledger_landscape(rml_parse.rml_parse):
if account and account.child_consol_ids: # add ids of consolidated childs also of selected account
ctx['consolidate_childs'] = True
ctx['account_id'] = account.id
ids_acc = self.pool.get('account.account').search(self.cr, self.uid,[('parent_id', 'child_of', [account.id])], context=ctx)
ids_acc = self.pool.get('account.account').search(self.cr, self.uid, [('parent_id', 'child_of', [account.id])], context=ctx)
for child_id in ids_acc:
child_account = self.pool.get('account.account').browse(self.cr, self.uid, child_id)
sold_account = self._sum_solde_account(child_account,form)
sold_account = self._sum_solde_account(child_account, form)
self.sold_accounts[child_account.id] = sold_account
if form['display_account'] == 'bal_mouvement':
if child_account.type != 'view' \
and len(self.pool.get('account.move.line').search(self.cr, self.uid,
[('account_id','=',child_account.id)],
[('account_id', '=', child_account.id)],
context=ctx)) <> 0 :
res.append(child_account)
elif form['display_account'] == 'bal_solde':
if child_account.type != 'view' \
and len(self.pool.get('account.move.line').search(self.cr, self.uid,
[('account_id','=',child_account.id)],
[('account_id', '=', child_account.id)],
context=ctx)) <> 0 :
if ( sold_account <> 0.0):
if (sold_account <> 0.0):
res.append(child_account)
else:
if child_account.type != 'view' \
and len(self.pool.get('account.move.line').search(self.cr, self.uid,
[('account_id','>=',child_account.id)],
[('account_id', '>=', child_account.id)],
context=ctx)) <> 0 :
res.append(child_account)
##
@ -226,7 +226,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
## We will now compute solde initiaux
for move in res:
self.cr.execute("""SELECT sum(l.debit) AS sum_debit, sum(l.credit) AS sum_credit FROM account_move_line l \
WHERE l.account_id = %s AND l.date < %s AND l.date > %s""",(move.id,self.borne_date['max_date'],self.borne_date['min_date']))
WHERE l.account_id = %s AND l.date < %s AND l.date > %s""", (move.id, self.borne_date['max_date'], self.borne_date['min_date']))
resultat = self.cr.dictfetchall()
if resultat[0] :
if resultat[0]['sum_debit'] == None:
@ -279,11 +279,11 @@ class general_ledger_landscape(rml_parse.rml_parse):
for l in res:
line = self.pool.get('account.move.line').browse(self.cr, self.uid, l['id'])
l['move'] = line.move_id.name
self.cr.execute('Select id from account_invoice where move_id =%s',(line.move_id.id,))
self.cr.execute('Select id from account_invoice where move_id =%s', (line.move_id.id,))
tmpres = self.cr.dictfetchall()
if len(tmpres) > 0 :
inv = self.pool.get('account.invoice').browse(self.cr, self.uid, tmpres[0]['id'])
l['ref'] = inv_types[inv.type] + ': '+str(inv.number)
l['ref'] = inv_types[inv.type] + ': ' + str(inv.number)
if line.partner_id :
l['partner'] = line.partner_id.name
else :
@ -292,7 +292,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
# c = time.strptime(l['date'],"%Y-%m-%d")
# l['date'] = time.strftime("%d-%m-%Y",c)
l['progress'] = sum
l['line_corresp'] = self._calc_contrepartie(self.cr,self.uid,[l['id']])[l['id']]
l['line_corresp'] = self._calc_contrepartie(self.cr, self.uid, [l['id']])[l['id']]
# Modification du amount Currency
if (l['credit'] > 0):
if l['amount_currency'] != None:
@ -307,7 +307,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
self.cr.execute("SELECT sum(debit) "\
"FROM account_move_line l "\
"WHERE l.account_id = %s AND "+self.query,(account.id,))
"WHERE l.account_id = %s AND " + self.query, (account.id,))
## Add solde init to the result
#
sum_debit = self.cr.fetchone()[0] or 0.0
@ -321,7 +321,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
self.cr.execute("SELECT sum(credit) "\
"FROM account_move_line l "\
"WHERE l.account_id = %s AND "+self.query,(account.id,))
"WHERE l.account_id = %s AND " + self.query, (account.id,))
## Add solde init to the result
#
sum_credit = self.cr.fetchone()[0] or 0.0
@ -335,9 +335,9 @@ class general_ledger_landscape(rml_parse.rml_parse):
def _sum_solde_account(self, account, form):
self.cr.execute("SELECT (sum(debit) - sum(credit)) as tot_solde "\
"FROM account_move_line l "\
"WHERE l.account_id = %s AND "+self.query,(account.id,))
"WHERE l.account_id = %s AND " + self.query, (account.id,))
sum_solde = self.cr.fetchone()[0] or 0.0
if form.get('soldeinit',False):
if form.get('soldeinit', False):
sum_solde += account.init_debit - account.init_credit
return sum_solde
@ -347,7 +347,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
return 0.0
self.cr.execute("SELECT sum(debit) "\
"FROM account_move_line l "\
"WHERE l.account_id =ANY(%s) AND "+self.query,(self.child_ids,))
"WHERE l.account_id =ANY(%s) AND " + self.query, (self.child_ids,))
sum_debit = self.cr.fetchone()[0] or 0.0
return sum_debit
@ -356,7 +356,7 @@ class general_ledger_landscape(rml_parse.rml_parse):
return 0.0
self.cr.execute("SELECT sum(credit) "\
"FROM account_move_line l "\
"WHERE l.account_id =ANY(%s) AND "+self.query,(self.child_ids,))
"WHERE l.account_id =ANY(%s) AND " + self.query, (self.child_ids,))
## Add solde init to the result
#
sum_credit = self.cr.fetchone()[0] or 0.0
@ -367,14 +367,14 @@ class general_ledger_landscape(rml_parse.rml_parse):
return 0.0
self.cr.execute("SELECT (sum(debit) - sum(credit)) as tot_solde "\
"FROM account_move_line l "\
"WHERE l.account_id =ANY(%s) AND "+self.query,(self.child_ids,))
"WHERE l.account_id =ANY(%s) AND " + self.query, (self.child_ids,))
sum_solde = self.cr.fetchone()[0] or 0.0
return sum_solde
def _set_get_account_currency_code(self, account_id):
self.cr.execute("SELECT c.code as code "\
"FROM res_currency c,account_account as ac "\
"WHERE ac.id = %s AND ac.currency_id = c.id",(account_id,))
"WHERE ac.id = %s AND ac.currency_id = c.id", (account_id,))
result = self.cr.fetchone()
if result:
self.account_currency = result[0]

View File

@ -29,7 +29,7 @@ import pooler
class Overdue(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(Overdue, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
self.localcontext.update({
'time' : time,
'adr_get' : self._adr_get,
'getLines' : self._lines_get,
@ -51,14 +51,14 @@ class Overdue(report_sxw.rml_parse):
'country_id' : False,
}
if adr_id:
result = res_partner_address.read(self.cr, self.uid, [adr_id],context=self.context.copy())
result = res_partner_address.read(self.cr, self.uid, [adr_id], context=self.context.copy())
result[0]['country_id'] = result[0]['country_id'] and result[0]['country_id'][1] or False
return result
return result
res.append(result)
return res
def _tel_get(self,partner):
def _tel_get(self, partner):
if not partner:
return False
res_partner_address = pooler.get_pool(self.cr.dbname).get('res.partner.address')
@ -66,7 +66,7 @@ class Overdue(report_sxw.rml_parse):
addresses = res_partner.address_get(self.cr, self.uid, [partner.id], ['invoice'])
adr_id = addresses and addresses['invoice'] or False
if adr_id:
adr=res_partner_address.read(self.cr, self.uid, [adr_id])[0]
adr = res_partner_address.read(self.cr, self.uid, [adr_id])[0]
return adr['phone']
else:
return partner.address and partner.address[0].phone or False
@ -80,12 +80,12 @@ class Overdue(report_sxw.rml_parse):
('state', '<>', 'draft'), ('reconcile_id', '=', False)])
movelines = moveline_obj.browse(self.cr, self.uid, movelines)
return movelines
def _message(self, obj, company):
company_pool = pooler.get_pool(self.cr.dbname).get('res.company')
message = company_pool.browse(self.cr, self.uid, company.id, {'lang':obj.lang}).overdue_msg
message = company_pool.browse(self.cr, self.uid, company.id, {'lang':obj.lang}).overdue_msg
return message
report_sxw.report_sxw('report.account.overdue', 'res.partner',
'addons/account/report/overdue.rml', parser=Overdue)

View File

@ -31,7 +31,7 @@ class partner_balance(report_sxw.rml_parse):
self.date_lst = []
self.date_lst_string = ''
self.account_ids = ''
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines': self.lines,
'sum_debit': self._sum_debit,
@ -49,73 +49,73 @@ class partner_balance(report_sxw.rml_parse):
#
# Date Management
#
def date_range(self,start,end):
def date_range(self, start, end):
if not start or not end:
return []
start = datetime.date.fromtimestamp(time.mktime(time.strptime(start,"%Y-%m-%d")))
end = datetime.date.fromtimestamp(time.mktime(time.strptime(end,"%Y-%m-%d")))
start = datetime.date.fromtimestamp(time.mktime(time.strptime(start, "%Y-%m-%d")))
end = datetime.date.fromtimestamp(time.mktime(time.strptime(end, "%Y-%m-%d")))
full_str_date = []
#
r = (end+datetime.timedelta(days=1)-start).days
r = (end + datetime.timedelta(days=1) - start).days
#
date_array = [start+datetime.timedelta(days=i) for i in range(r)]
date_array = [start + datetime.timedelta(days=i) for i in range(r)]
for date in date_array:
full_str_date.append(str(date))
return full_str_date
def transform_period_into_date_array(self,data):
def transform_period_into_date_array(self, data):
## Get All Period Date
#
# If we have no period we will take all perdio in the FiscalYear.
if not data['form']['periods'][0][2] :
periods_id = self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id','=',data['form']['fiscalyear'])])
periods_id = self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id', '=', data['form']['fiscalyear'])])
else:
periods_id = data['form']['periods'][0][2]
date_array = []
for period_id in periods_id:
period_obj = self.pool.get('account.period').browse(self.cr, self.uid, period_id)
date_array = date_array + self.date_range(period_obj.date_start,period_obj.date_stop)
date_array = date_array + self.date_range(period_obj.date_start, period_obj.date_stop)
self.date_lst = date_array
self.date_lst.sort()
def transform_date_into_date_array(self,data):
return_array = self.date_range(data['form']['date1'],data['form']['date2'])
def transform_date_into_date_array(self, data):
return_array = self.date_range(data['form']['date1'], data['form']['date2'])
self.date_lst = return_array
self.date_lst.sort()
def transform_both_into_date_array(self,data):
def transform_both_into_date_array(self, data):
if not data['form']['periods'][0][2] :
periods_id = self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id','=',data['form']['fiscalyear'])])
periods_id = self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id', '=', data['form']['fiscalyear'])])
else:
periods_id = data['form']['periods'][0][2]
date_array = []
for period_id in periods_id:
period_obj = self.pool.get('account.period').browse(self.cr, self.uid, period_id)
date_array = date_array + self.date_range(period_obj.date_start,period_obj.date_stop)
date_array = date_array + self.date_range(period_obj.date_start, period_obj.date_stop)
period_start_date = date_array[0]
date_start_date = data['form']['date1']
period_stop_date = date_array[-1]
date_stop_date = data['form']['date2']
if period_start_date<date_start_date:
if period_start_date < date_start_date:
start_date = period_start_date
else :
start_date = date_start_date
if date_stop_date<period_stop_date:
if date_stop_date < period_stop_date:
stop_date = period_stop_date
else :
stop_date = date_stop_date
final_date_array = []
final_date_array = final_date_array + self.date_range(start_date,stop_date)
final_date_array = final_date_array + self.date_range(start_date, stop_date)
self.date_lst = final_date_array
self.date_lst.sort()
def transform_none_into_date_array(self,data):
def transform_none_into_date_array(self, data):
sql = "SELECT min(date) as start_date from account_move_line"
self.cr.execute(sql)
@ -127,14 +127,14 @@ class partner_balance(report_sxw.rml_parse):
array = []
array = array + self.date_range(start_date,stop_date)
array = array + self.date_range(start_date, stop_date)
self.date_lst = array
self.date_lst.sort()
def comma_me(self,amount):
def comma_me(self, amount):
if type(amount) is float :
amount = str('%.2f'%amount)
amount = str('%.2f' % amount)
else :
amount = str(amount)
if (amount == '0'):
@ -146,7 +146,7 @@ class partner_balance(report_sxw.rml_parse):
else:
return self.comma_me(new)
def set_context(self, objects, data, ids, report_type = None):
def set_context(self, objects, data, ids, report_type=None):
# Transformation des date
#
#
@ -164,19 +164,19 @@ class partner_balance(report_sxw.rml_parse):
self.transform_both_into_date_array(data)
##
self.date_lst_string =''
self.date_lst_string = ''
if self.date_lst:
self.date_lst_string = '\'' + '\',\''.join(map(str, self.date_lst)) + '\''
## Compute Code
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
#
if (data['form']['result_selection'] == 'customer' ):
if (data['form']['result_selection'] == 'customer'):
self.ACCOUNT_TYPE = ['receivable']
elif (data['form']['result_selection'] == 'supplier'):
self.ACCOUNT_TYPE = ['payable']
else:
self.ACCOUNT_TYPE = ['payable','receivable']
self.ACCOUNT_TYPE = ['payable', 'receivable']
#
self.cr.execute("SELECT a.id " \
"FROM account_account a " \
@ -184,12 +184,12 @@ class partner_balance(report_sxw.rml_parse):
"ON (a.type = t.code) " \
"WHERE a.company_id = %s " \
"AND a.type =ANY(%s) "\
"AND a.active", (data['form']['company_id'],self.ACCOUNT_TYPE,))
"AND a.active", (data['form']['company_id'], self.ACCOUNT_TYPE,))
self.account_ids = [a for (a,) in self.cr.fetchall()]
super(partner_balance, self).set_context(objects, data, ids, report_type)
def lines(self,data):
def lines(self, data):
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
full_account = []
@ -217,7 +217,7 @@ class partner_balance(report_sxw.rml_parse):
"AND l.date IN (" + self.date_lst_string + ") " \
"AND ac.company_id = %s" \
"GROUP BY p.id, p.ref, p.name,l.account_id,ac.name,ac.code " \
"ORDER BY l.account_id,p.name",(self.ACCOUNT_TYPE,data['form']['company_id'],))
"ORDER BY l.account_id,p.name", (self.ACCOUNT_TYPE, data['form']['company_id'],))
res = self.cr.dictfetchall()
for r in res:
full_account.append(r)
@ -225,8 +225,8 @@ class partner_balance(report_sxw.rml_parse):
## We will now compute Total
return self._add_subtotal(full_account)
def _add_subtotal(self,cleanarray):
i=0
def _add_subtotal(self, cleanarray):
i = 0
completearray = []
tot_debit = 0.0
tot_credit = 0.0
@ -237,7 +237,7 @@ class partner_balance(report_sxw.rml_parse):
# For the first element we always add the line
# type = 1 is the line is the first of the account
# type = 2 is an other line of the account
if i==0:
if i == 0:
# We add the first as the header
#
##
@ -267,7 +267,7 @@ class partner_balance(report_sxw.rml_parse):
tot_enlitige = (r['enlitige'] or 0.0)
#
else:
if cleanarray[i]['account_id'] <> cleanarray[i-1]['account_id']:
if cleanarray[i]['account_id'] <> cleanarray[i - 1]['account_id']:
new_header['debit'] = tot_debit
new_header['credit'] = tot_credit
@ -307,7 +307,7 @@ class partner_balance(report_sxw.rml_parse):
completearray.append(r)
if cleanarray[i]['account_id'] == cleanarray[i-1]['account_id']:
if cleanarray[i]['account_id'] == cleanarray[i - 1]['account_id']:
# we reset the counter
new_header['debit'] = tot_debit
@ -344,7 +344,7 @@ class partner_balance(report_sxw.rml_parse):
return completearray
def _sum_debit(self,data):
def _sum_debit(self, data):
if not self.ids:
return 0.0
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
@ -355,13 +355,13 @@ class partner_balance(report_sxw.rml_parse):
"SELECT sum(debit) " \
"FROM account_move_line AS l " \
"WHERE l.account_id =ANY(%s)" \
"AND l.date IN (" + self.date_lst_string + ")" ,(self.account_ids,))
"AND l.date IN (" + self.date_lst_string + ")" , (self.account_ids,))
temp_res = float(self.cr.fetchone()[0] or 0.0)
result_tmp = result_tmp + temp_res
return result_tmp
def _sum_credit(self,data):
def _sum_credit(self, data):
if not self.ids:
return 0.0
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
@ -373,13 +373,13 @@ class partner_balance(report_sxw.rml_parse):
"SELECT sum(credit) " \
"FROM account_move_line AS l " \
"WHERE l.account_id =ANY(%s)" \
"AND l.date IN (" + self.date_lst_string + ")" ,(self.account_ids,))
"AND l.date IN (" + self.date_lst_string + ")" , (self.account_ids,))
temp_res = float(self.cr.fetchone()[0] or 0.0)
result_tmp = result_tmp + temp_res
return result_tmp
def _sum_litige(self,data):
def _sum_litige(self, data):
if not self.ids:
return 0.0
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
@ -391,13 +391,13 @@ class partner_balance(report_sxw.rml_parse):
"FROM account_move_line AS l " \
"WHERE l.account_id =ANY(%s)" \
"AND l.date IN (" + self.date_lst_string + ")"\
"AND l.blocked=TRUE " ,(self.account_ids,))
"AND l.blocked=TRUE " , (self.account_ids,))
temp_res = float(self.cr.fetchone()[0] or 0.0)
result_tmp = result_tmp + temp_res
return result_tmp
def _sum_sdebit(self,data):
def _sum_sdebit(self, data):
if not self.ids:
return 0.0
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
@ -412,7 +412,7 @@ class partner_balance(report_sxw.rml_parse):
"FROM account_move_line AS l " \
"WHERE l.account_id =ANY(%s)" \
"AND l.date IN (" + self.date_lst_string + ")" \
"GROUP BY l.partner_id",(self.account_ids,))
"GROUP BY l.partner_id", (self.account_ids,))
a = self.cr.fetchone()[0]
if self.cr.fetchone() != None:
@ -422,7 +422,7 @@ class partner_balance(report_sxw.rml_parse):
return result_tmp
def _sum_scredit(self,data):
def _sum_scredit(self, data):
if not self.ids:
return 0.0
@ -439,7 +439,7 @@ class partner_balance(report_sxw.rml_parse):
"FROM account_move_line AS l " \
"WHERE l.account_id =ANY(%s)" \
"AND l.date IN (" + self.date_lst_string + ")" \
"GROUP BY l.partner_id",(self.account_ids,))
"GROUP BY l.partner_id", (self.account_ids,))
a = self.cr.fetchone()[0] or 0.0
if self.cr.fetchone() != None:
@ -450,11 +450,11 @@ class partner_balance(report_sxw.rml_parse):
return result_tmp
def _solde_balance_debit(self,data):
def _solde_balance_debit(self, data):
debit, credit = self._sum_debit(data), self._sum_credit(data)
return debit > credit and debit - credit
def _solde_balance_credit(self,data):
def _solde_balance_credit(self, data):
debit, credit = self._sum_debit(data), self._sum_credit(data)
return credit > debit and credit - debit
@ -465,7 +465,7 @@ class partner_balance(report_sxw.rml_parse):
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',
'account/report/partner_balance.rml',parser=partner_balance,
'account/report/partner_balance.rml', parser=partner_balance,
header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -40,12 +40,12 @@ class rml_parse(report_sxw.rml_parse):
'explode_name' : self._explode_name,
})
def comma_me(self,amount):
def comma_me(self, amount):
#print "#" + str(amount) + "#"
if not amount:
amount = 0.0
if type(amount) is float :
amount = str('%.2f'%amount)
amount = str('%.2f' % amount)
else :
amount = str(amount)
if (amount == '0'):
@ -56,7 +56,7 @@ class rml_parse(report_sxw.rml_parse):
return new
else:
return self.comma_me(new)
def _ellipsis(self, string, maxlen=100, ellipsis = '...'):
def _ellipsis(self, string, maxlen=100, ellipsis='...'):
ellipsis = ellipsis or ''
try:
return string[:maxlen - len(ellipsis) ] + (ellipsis, '')[len(string) < maxlen]
@ -65,20 +65,20 @@ class rml_parse(report_sxw.rml_parse):
def _strip_name(self, name, maxlen=50):
return self._ellipsis(name, maxlen, '...')
def _get_and_change_date_format_for_swiss (self,date_to_format):
date_formatted=''
def _get_and_change_date_format_for_swiss (self, date_to_format):
date_formatted = ''
if date_to_format:
date_formatted = strptime (date_to_format,'%Y-%m-%d').strftime('%d.%m.%Y')
date_formatted = strptime (date_to_format, '%Y-%m-%d').strftime('%d.%m.%Y')
return date_formatted
def _explode_name(self,chaine,length):
def _explode_name(self, chaine, length):
# We will test if the size is less then account
full_string = ''
if (len(str(chaine)) <= length):
return chaine
#
else:
chaine = unicode(chaine,'utf8').encode('iso-8859-1')
chaine = unicode(chaine, 'utf8').encode('iso-8859-1')
rup = 0
for carac in chaine:
rup = rup + 1
@ -91,7 +91,7 @@ class rml_parse(report_sxw.rml_parse):
return full_string
def makeAscii(self,str):
def makeAscii(self, str):
try:
Stringer = str.encode("utf-8")
except UnicodeDecodeError:
@ -105,17 +105,17 @@ class rml_parse(report_sxw.rml_parse):
else:
return Stringer
return Stringer
def explode_this(self,chaine,length):
def explode_this(self, chaine, length):
#chaine = self.repair_string(chaine)
chaine = rstrip(chaine)
ast = list(chaine)
i = length
while i <= len(ast):
ast.insert(i,'\n')
ast.insert(i, '\n')
i = i + length
chaine = str("".join(ast))
return chaine
def repair_string(self,chaine):
def repair_string(self, chaine):
ast = list(chaine)
UnicodeAst = []
_previouslyfound = False
@ -126,11 +126,11 @@ class rml_parse(report_sxw.rml_parse):
try:
Stringer = elem.encode("utf-8")
except UnicodeDecodeError:
to_reencode = elem + ast[i+1]
to_reencode = elem + ast[i + 1]
print str(to_reencode)
Good_char = to_reencode.decode('utf-8')
UnicodeAst.append(Good_char)
i += i +2
i += i + 2
else:
UnicodeAst.append(elem)
i += i + 1
@ -138,7 +138,7 @@ class rml_parse(report_sxw.rml_parse):
return "".join(UnicodeAst)
def ReencodeAscii(self,str):
def ReencodeAscii(self, str):
print sys.stdin.encoding
try:
Stringer = str.decode("ascii")

View File

@ -42,19 +42,19 @@ class tax_report(rml_parse.rml_parse):
})
def _get_lines(self, based_on,period_list,company_id=False, parent=False, level=0):
res = self._get_codes(based_on,company_id,parent,level,period_list)
def _get_lines(self, based_on, period_list, company_id=False, parent=False, level=0):
res = self._get_codes(based_on, company_id, parent, level, period_list)
if period_list[0][2] :
res = self._add_codes(based_on,res,period_list)
res = self._add_codes(based_on, res, period_list)
else :
self.cr.execute ("select id from account_fiscalyear")
fy = self.cr.fetchall()
self.cr.execute ("select id from account_period where fiscalyear_id = %s",(fy[0][0],))
self.cr.execute ("select id from account_period where fiscalyear_id = %s", (fy[0][0],))
periods = self.cr.fetchall()
for p in periods :
period_list[0][2].append(p[0])
res = self._add_codes(based_on,res,period_list)
res = self._add_codes(based_on, res, period_list)
i = 0
top_result = []
@ -71,15 +71,15 @@ class tax_report(rml_parse.rml_parse):
}
top_result.append(res_dict)
res_general = self._get_general(res[i][1].id,period_list,company_id,based_on)
res_general = self._get_general(res[i][1].id, period_list, company_id, based_on)
ind_general = 0
while ind_general < len(res_general) :
res_general[ind_general]['type'] = 2
res_general[ind_general]['pos'] = 0
res_general[ind_general]['level'] = res_dict['level']
top_result.append(res_general[ind_general])
ind_general+=1
i+=1
ind_general += 1
i += 1
#array_result = self.sort_result(top_result)
return top_result
#return array_result
@ -87,8 +87,8 @@ class tax_report(rml_parse.rml_parse):
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_list ,company_id, based_on):
res=[]
def _get_general(self, tax_code_id, period_list , 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, \
@ -110,8 +110,8 @@ class tax_report(rml_parse.rml_parse):
AND line.period_id =ANY(%s) \
AND ((invoice.state = %s) \
OR (invoice.id IS NULL)) \
GROUP BY account.id,account.name,account.code', ('draft',tax_code_id,
company_id, period_list[0][2],'paid',))
GROUP BY account.id,account.name,account.code', ('draft', tax_code_id,
company_id, period_list[0][2], 'paid',))
else :
self.cr.execute('SELECT SUM(line.tax_amount) AS tax_amount, \
@ -129,42 +129,42 @@ class tax_report(rml_parse.rml_parse):
AND account.company_id = %s \
AND line.period_id =ANY(%s)\
AND account.active \
GROUP BY account.id,account.name,account.code', ('draft',tax_code_id,
company_id,period_list[0][2],))
GROUP BY account.id,account.name,account.code', ('draft', tax_code_id,
company_id, period_list[0][2],))
res = self.cr.dictfetchall()
#AND line.period_id IN ('+ period_sql_list +') \
i = 0
while i<len(res):
while i < len(res):
res[i]['account'] = self.pool.get('account.account').browse(self.cr, self.uid, res[i]['account_id'])
i+=1
i += 1
return res
def _get_codes(self,based_on, company_id, parent=False, level=0,period_list=[]):
def _get_codes(self, based_on, company_id, parent=False, level=0, period_list=[]):
tc = self.pool.get('account.tax.code')
ids = tc.search(self.cr, self.uid, [('parent_id','=',parent),('company_id','=',company_id)])
ids = tc.search(self.cr, self.uid, [('parent_id', '=', parent), ('company_id', '=', company_id)])
res = []
for code in tc.browse(self.cr, self.uid, ids, {'based_on': based_on}):
res.append(('.'*2*level,code))
res.append(('.'*2 * level, code))
res += self._get_codes(based_on, company_id, code.id, level+1)
res += self._get_codes(based_on, company_id, code.id, level + 1)
return res
def _add_codes(self,based_on, account_list=[],period_list=[]):
def _add_codes(self, based_on, account_list=[], period_list=[]):
res = []
for account in account_list:
tc = self.pool.get('account.tax.code')
ids = tc.search(self.cr, self.uid, [('id','=',account[1].id)])
ids = tc.search(self.cr, self.uid, [('id', '=', account[1].id)])
sum_tax_add = 0
for period_ind in period_list[0][2]:
for code in tc.browse(self.cr, self.uid, ids, {'period_id':period_ind,'based_on': based_on}):
for code in tc.browse(self.cr, self.uid, ids, {'period_id':period_ind, 'based_on': based_on}):
sum_tax_add = sum_tax_add + code.sum_period
code.sum_period = sum_tax_add
res.append((account[0],code))
res.append((account[0], code))
return res
@ -174,12 +174,12 @@ class tax_report(rml_parse.rml_parse):
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 sort_result(self,accounts):
def sort_result(self, accounts):
# On boucle sur notre rapport
result_accounts = []
ind=0
old_level=0
while ind<len(accounts):
ind = 0
old_level = 0
while ind < len(accounts):
#
account_elem = accounts[ind]
#
@ -190,7 +190,7 @@ class tax_report(rml_parse.rml_parse):
bcl_current_level = old_level
bcl_rup_ind = ind - 1
while (bcl_current_level >= int(accounts[bcl_rup_ind]['level']) and bcl_rup_ind >= 0 ):
while (bcl_current_level >= int(accounts[bcl_rup_ind]['level']) and bcl_rup_ind >= 0):
tot_elem = copy.copy(accounts[bcl_rup_ind])
res_tot = { 'code' : accounts[bcl_rup_ind]['code'],
'name' : '',
@ -206,12 +206,12 @@ class tax_report(rml_parse.rml_parse):
# on change le type pour afficher le total
res_tot['type'] = 2
result_accounts.append(res_tot)
bcl_current_level = accounts[bcl_rup_ind]['level']
bcl_current_level = accounts[bcl_rup_ind]['level']
bcl_rup_ind -= 1
old_level = account_elem['level']
result_accounts.append(account_elem)
ind+=1
ind += 1
return result_accounts

View File

@ -31,7 +31,7 @@ class third_party_ledger(rml_parse.rml_parse):
self.date_lst = []
self.date_lst_string = ''
super(third_party_ledger, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines': self.lines,
'sum_debit_partner': self._sum_debit_partner,
@ -42,61 +42,61 @@ class third_party_ledger(rml_parse.rml_parse):
'get_currency': self._get_currency,
'comma_me' : self.comma_me,
})
def date_range(self,start,end):
def date_range(self, start, end):
if not start or not end:
return []
start = datetime.date.fromtimestamp(time.mktime(time.strptime(start,"%Y-%m-%d")))
end = datetime.date.fromtimestamp(time.mktime(time.strptime(end,"%Y-%m-%d")))
start = datetime.date.fromtimestamp(time.mktime(time.strptime(start, "%Y-%m-%d")))
end = datetime.date.fromtimestamp(time.mktime(time.strptime(end, "%Y-%m-%d")))
full_str_date = []
#
r = (end+datetime.timedelta(days=1)-start).days
r = (end + datetime.timedelta(days=1) - start).days
#
date_array = [start+datetime.timedelta(days=i) for i in range(r)]
date_array = [start + datetime.timedelta(days=i) for i in range(r)]
for date in date_array:
full_str_date.append(str(date))
return full_str_date
#
def transform_period_into_date_array(self,data):
def transform_period_into_date_array(self, data):
## Get All Period Date
if not data['form']['periods'][0][2] :
periods_id = self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id','=',data['form']['fiscalyear'])])
periods_id = self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id', '=', data['form']['fiscalyear'])])
else:
periods_id = data['form']['periods'][0][2]
date_array = []
for period_id in periods_id:
period_obj = self.pool.get('account.period').browse(self.cr, self.uid, period_id)
date_array = date_array + self.date_range(period_obj.date_start,period_obj.date_stop)
date_array = date_array + self.date_range(period_obj.date_start, period_obj.date_stop)
self.date_lst = date_array
self.date_lst.sort()
def transform_date_into_date_array(self,data):
return_array = self.date_range(data['form']['date1'],data['form']['date2'])
def transform_date_into_date_array(self, data):
return_array = self.date_range(data['form']['date1'], data['form']['date2'])
self.date_lst = return_array
self.date_lst.sort()
def transform_both_into_date_array(self,data):
def transform_both_into_date_array(self, data):
if not data['form']['periods'][0][2] :
periods_id = self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id','=',data['form']['fiscalyear'])])
periods_id = self.pool.get('account.period').search(self.cr, self.uid, [('fiscalyear_id', '=', data['form']['fiscalyear'])])
else:
periods_id = data['form']['periods'][0][2]
date_array = []
for period_id in periods_id:
period_obj = self.pool.get('account.period').browse(self.cr, self.uid, period_id)
date_array = date_array + self.date_range(period_obj.date_start,period_obj.date_stop)
date_array = date_array + self.date_range(period_obj.date_start, period_obj.date_stop)
period_start_date = date_array[0]
date_start_date = data['form']['date1']
period_stop_date = date_array[-1]
date_stop_date = data['form']['date2']
if period_start_date<date_start_date:
if period_start_date < date_start_date:
start_date = period_start_date
else :
start_date = date_start_date
if date_stop_date<period_stop_date:
if date_stop_date < period_stop_date:
stop_date = period_stop_date
else :
stop_date = date_stop_date
@ -105,22 +105,22 @@ class third_party_ledger(rml_parse.rml_parse):
self.date_lst = final_date_array
self.date_lst.sort()
def transform_none_into_date_array(self,data):
def transform_none_into_date_array(self, data):
sql = "SELECT min(date) as start_date from account_move_line"
self.cr.execute(sql)
start_date = self.cr.fetchone()[0]
sql = "SELECT max(date) as start_date from account_move_line"
self.cr.execute(sql)
stop_date = self.cr.fetchone()[0]
array= []
array = []
array = array + self.date_range(start_date, stop_date)
self.date_lst = array
self.date_lst.sort()
def comma_me(self,amount):
def comma_me(self, amount):
if type(amount) is float :
amount = str('%.2f'%amount)
amount = str('%.2f' % amount)
else :
amount = str(amount)
if (amount == '0'):
@ -137,13 +137,13 @@ class third_party_ledger(rml_parse.rml_parse):
string_map = date_string + ','
return string_map
def set_context(self, objects, data, ids, report_type = None):
def set_context(self, objects, data, ids, report_type=None):
PARTNER_REQUEST = ''
if (data['model'] == 'res.partner'):
## Si on imprime depuis les partenaires
if ids:
#PARTNER_REQUEST = "AND line.partner_id IN (" + ','.join(map(str, ids)) + ")"
PARTNER_REQUEST = "AND line.partner_id =ANY(%s)" %ids
PARTNER_REQUEST = "AND line.partner_id =ANY(%s)" % ids
# Transformation des date
#
#
@ -171,7 +171,7 @@ class third_party_ledger(rml_parse.rml_parse):
elif data['form']['result_selection'] == 'customer':
self.ACCOUNT_TYPE = ['payable']
elif data['form']['result_selection'] == 'all':
self.ACCOUNT_TYPE = ['payable','receivable']
self.ACCOUNT_TYPE = ['payable', 'receivable']
self.cr.execute(
"SELECT a.id " \
@ -180,7 +180,7 @@ class third_party_ledger(rml_parse.rml_parse):
"ON (a.type=t.code) " \
"WHERE a.company_id = %s " \
'AND a.type =ANY(%s)' \
"AND a.active", (data['form']['company_id'],self.ACCOUNT_TYPE,))
"AND a.active", (data['form']['company_id'], self.ACCOUNT_TYPE,))
self.account_ids = [a for (a,) in self.cr.fetchall()]
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
@ -200,7 +200,7 @@ class third_party_ledger(rml_parse.rml_parse):
" " + PARTNER_REQUEST + " " \
"AND account.company_id = %s " \
"AND account.active " ,
(self.date_lst[0],self.date_lst[len(self.date_lst)-1],self.account_ids,data['form']['company_id'],))
(self.date_lst[0], self.date_lst[len(self.date_lst) - 1], self.account_ids, data['form']['company_id'],))
# else:
#
# self.cr.execute(
@ -226,7 +226,7 @@ class third_party_ledger(rml_parse.rml_parse):
objects = self.pool.get('res.partner').browse(self.cr, self.uid, new_ids)
super(third_party_ledger, self).set_context(objects, data, new_ids, report_type)
def lines(self, partner,data):
def lines(self, partner, data):
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
full_account = []
if data['form']['reconcil'] :
@ -265,7 +265,7 @@ class third_party_ledger(rml_parse.rml_parse):
"AND l.date IN (" + self.date_lst_string + ")"
" " + RECONCILE_TAG + " "\
"ORDER BY l.id",
(partner.id,self.account_ids,))
(partner.id, self.account_ids,))
res = self.cr.dictfetchall()
sum = 0.0
for r in res:
@ -275,7 +275,7 @@ class third_party_ledger(rml_parse.rml_parse):
return full_account
def _sum_debit_partner(self, partner,data):
def _sum_debit_partner(self, partner, data):
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
result_tmp = 0.0
@ -291,7 +291,7 @@ class third_party_ledger(rml_parse.rml_parse):
"AND account_id =ANY(%s)" \
"AND reconcile_id IS NULL " \
"AND date < %s " ,
(partner.id, self.account_ids,self.date_lst[0],))
(partner.id, self.account_ids, self.date_lst[0],))
contemp = self.cr.fetchone()
if contemp != None:
result_tmp = contemp[0] or 0.0
@ -306,7 +306,7 @@ class third_party_ledger(rml_parse.rml_parse):
"AND account_id =ANY(%s)" \
" " + RECONCILE_TAG + " " \
"AND date IN (" + self.date_lst_string + ")" ,
(partner.id,self.account_ids,))
(partner.id, self.account_ids,))
contemp = self.cr.fetchone()
if contemp != None:
@ -315,7 +315,7 @@ class third_party_ledger(rml_parse.rml_parse):
result_tmp = result_tmp + 0.0
return result_tmp
def _sum_credit_partner(self, partner,data):
def _sum_credit_partner(self, partner, data):
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
result_tmp = 0.0
if data['form']['reconcil'] :
@ -330,7 +330,7 @@ class third_party_ledger(rml_parse.rml_parse):
"AND account_id =ANY(%s)" \
"AND reconcile_id IS NULL " \
"AND date < %s " ,
(partner.id,self.account_ids,self.date_lst[0],))
(partner.id, self.account_ids, self.date_lst[0],))
contemp = self.cr.fetchone()
if contemp != None:
result_tmp = contemp[0] or 0.0
@ -345,7 +345,7 @@ class third_party_ledger(rml_parse.rml_parse):
"AND account_id =ANY(%s)" \
" " + RECONCILE_TAG + " " \
"AND date IN (" + self.date_lst_string + ")",
(partner.id,self.account_ids,))
(partner.id, self.account_ids,))
contemp = self.cr.fetchone()
if contemp != None:
@ -354,7 +354,7 @@ class third_party_ledger(rml_parse.rml_parse):
result_tmp = result_tmp + 0.0
return result_tmp
def _sum_debit(self,data):
def _sum_debit(self, data):
if not self.ids:
return 0.0
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
@ -371,7 +371,7 @@ class third_party_ledger(rml_parse.rml_parse):
"AND account_id =ANY(%s)" \
"AND reconcile_id IS NULL " \
"AND date < %s " ,
(self.partner_ids,self.account_ids,self.date_lst[0],))
(self.partner_ids, self.account_ids, self.date_lst[0],))
contemp = self.cr.fetchone()
if contemp != None:
result_tmp = contemp[0] or 0.0
@ -385,7 +385,7 @@ class third_party_ledger(rml_parse.rml_parse):
"WHERE partner_id =ANY(%s)" \
"AND account_id =ANY(%s)" \
" " + RECONCILE_TAG + " " \
"AND date IN (" + self.date_lst_string + ")",(self.partner_ids,self.account_ids,))
"AND date IN (" + self.date_lst_string + ")", (self.partner_ids, self.account_ids,))
contemp = self.cr.fetchone()
if contemp != None:
result_tmp = contemp[0] or 0.0
@ -395,7 +395,7 @@ class third_party_ledger(rml_parse.rml_parse):
return result_tmp
def _sum_credit(self,data):
def _sum_credit(self, data):
if not self.ids:
return 0.0
account_move_line_obj = pooler.get_pool(self.cr.dbname).get('account.move.line')
@ -412,7 +412,7 @@ class third_party_ledger(rml_parse.rml_parse):
"AND account_id =ANY(%s)" \
"AND reconcile_id IS NULL " \
"AND date < %s " ,
(self.partner_ids,self.account_ids,self.date_lst[0],))
(self.partner_ids, self.account_ids, self.date_lst[0],))
contemp = self.cr.fetchone()
if contemp != None:
result_tmp = contemp[0] or 0.0
@ -426,7 +426,7 @@ class third_party_ledger(rml_parse.rml_parse):
"WHERE partner_id =ANY(%s)" \
"AND account_id =ANY(%s)" \
" " + RECONCILE_TAG + " " \
"AND date IN (" + self.date_lst_string + ")",(self.partner_ids,self.account_ids,))
"AND date IN (" + self.date_lst_string + ")", (self.partner_ids, self.account_ids,))
contemp = self.cr.fetchone()
if contemp != None:
result_tmp = contemp[0] or 0.0
@ -442,11 +442,11 @@ class third_party_ledger(rml_parse.rml_parse):
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,
'addons/account/report/third_party_ledger.rml', parser=third_party_ledger,
header=False)
report_sxw.report_sxw('report.account.third_party_ledger_other', 'res.partner',
'addons/account/report/third_party_ledger_other.rml',parser=third_party_ledger,
'addons/account/report/third_party_ledger_other.rml', parser=third_party_ledger,
header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -20,7 +20,7 @@
##############################################################################
from osv import fields,osv
from osv import fields, osv
class ir_sequence_fiscalyear(osv.osv):
_name = 'account.sequence.fiscalyear'
@ -32,7 +32,7 @@ class ir_sequence_fiscalyear(osv.osv):
}
_sql_constraints = [
('main_id', 'CHECK (sequence_main_id != sequence_id)', 'Main Sequence must be different from current !'),
('main_id', 'CHECK (sequence_main_id != sequence_id)', 'Main Sequence must be different from current !'),
]
ir_sequence_fiscalyear()
@ -42,12 +42,12 @@ class ir_sequence(osv.osv):
_columns = {
'fiscal_ids' : fields.one2many('account.sequence.fiscalyear', 'sequence_main_id', 'Sequences')
}
def get_id(self, cr, uid, sequence_id, test='id', context={}):
cr.execute('select id from ir_sequence where '+test+'=%s and active=%s', (sequence_id, True,))
def get_id(self, cr, uid, sequence_id, test='id', context={}):
cr.execute('select id from ir_sequence where ' + test + '=%s and active=%s', (sequence_id, True,))
res = cr.dictfetchone()
if res:
for line in self.browse(cr, uid, res['id'], context=context).fiscal_ids:
if line.fiscalyear_id.id==context.get('fiscalyear_id', False):
if line.fiscalyear_id.id == context.get('fiscalyear_id', False):
return super(ir_sequence, self).get_id(cr, uid, line.sequence_id.id, test="id", context=context)
return super(ir_sequence, self).get_id(cr, uid, sequence_id, test, context)
ir_sequence()

View File

@ -26,23 +26,23 @@ USERID = 1
USERPASS = 'admin'
sock = xmlrpclib.ServerProxy('http://%s:%s/xmlrpc/object' % ('localhost',8069))
sock = xmlrpclib.ServerProxy('http://%s:%s/xmlrpc/object' % ('localhost', 8069))
ids = sock.execute(DB, USERID, USERPASS, 'account.account', 'search', [], {})
account_lists = sock.execute(DB, USERID, USERPASS, 'account.account', 'read', ids, ['parent_id','parent_left','parent_right'])
account_lists = sock.execute(DB, USERID, USERPASS, 'account.account', 'read', ids, ['parent_id', 'parent_left', 'parent_right'])
accounts = dict(map(lambda x: (x['id'],x), account_lists))
accounts = dict(map(lambda x: (x['id'], x), account_lists))
for a in account_lists:
if a['parent_id']:
assert a['parent_left'] > accounts[a['parent_id'][0]]['parent_left']
assert a['parent_right'] < accounts[a['parent_id'][0]]['parent_right']
assert a['parent_left'] < a['parent_right']
for a2 in account_lists:
assert not ((a2['parent_right']>a['parent_left']) and
(a2['parent_left']<a['parent_left']) and
(a2['parent_right']<a['parent_right']))
if a2['parent_id']==a['id']:
assert (a2['parent_left']>a['parent_left']) and (a2['parent_right']<a['parent_right'])
assert not ((a2['parent_right'] > a['parent_left']) and
(a2['parent_left'] < a['parent_left']) and
(a2['parent_right'] < a['parent_right']))
if a2['parent_id'] == a['id']:
assert (a2['parent_left'] > a['parent_left']) and (a2['parent_right'] < a['parent_right'])
print 'Tests Ok'

View File

@ -53,8 +53,8 @@ period_fields = {
'state':{
'string':"Date/Period Filter",
'type':'selection',
'selection':[('bydate','By Date'),('byperiod','By Period'),('all','By Date and Period'),('none','No Filter')],
'default': lambda *a:'none'
'selection':[('bydate', 'By Date'), ('byperiod', 'By Period'), ('all', 'By Date and Period'), ('none', 'No Filter')],
'default': lambda * a:'none'
},
'fiscalyear': {
'string':'Fiscal year',
@ -63,9 +63,9 @@ period_fields = {
'help':'Keep empty for all open fiscal year'
},
'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty'},
'display_account':{'string':"Display accounts ",'type':'selection','selection':[('bal_mouvement','With movements'),('bal_all','All'),('bal_solde','With balance is not equal to 0')]},
'date_from': {'string':"Start date",'type':'date','required':True ,'default': lambda *a: time.strftime('%Y-01-01')},
'date_to': {'string':"End date",'type':'date','required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')},
'display_account':{'string':"Display accounts ", 'type':'selection', 'selection':[('bal_mouvement', 'With movements'), ('bal_all', 'All'), ('bal_solde', 'With balance is not equal to 0')]},
'date_from': {'string':"Start date", 'type':'date', 'required':True , 'default': lambda * a: time.strftime('%Y-01-01')},
'date_to': {'string':"End date", 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')},
}
account_form = '''<?xml version="1.0"?>
@ -74,7 +74,7 @@ account_form = '''<?xml version="1.0"?>
</form>'''
account_fields = {
'Account_list': {'string':'Account', 'type':'many2one', 'relation':'account.account', 'required':True ,'domain':[('parent_id','=',False)]},
'Account_list': {'string':'Account', 'type':'many2one', 'relation':'account.account', 'required':True , 'domain':[('parent_id', '=', False)]},
}
class wizard_report(wizard.interface):
@ -112,29 +112,29 @@ class wizard_report(wizard.interface):
def _check_date(self, cr, uid, data, context):
sql = """
SELECT f.id, f.date_start, f.date_stop FROM account_fiscalyear f Where %s between f.date_start and f.date_stop """
cr.execute(sql,(data['form']['date_from'],))
cr.execute(sql, (data['form']['date_from'],))
res = cr.dictfetchall()
if res:
if (data['form']['date_to'] > res[0]['date_stop'] or data['form']['date_to'] < res[0]['date_start']):
raise wizard.except_wizard(_('UserError'),_('Date to must be set between %s and %s') % (res[0]['date_start'], res[0]['date_stop']))
raise wizard.except_wizard(_('UserError'), _('Date to must be set between %s and %s') % (res[0]['date_start'], res[0]['date_stop']))
else:
return 'report'
else:
raise wizard.except_wizard(_('UserError'),_('Date not in a defined fiscal year'))
raise wizard.except_wizard(_('UserError'), _('Date not in a defined fiscal year'))
states = {
'init': {
'actions': [],
'result': {'type':'choice','next_state':_check_path}
'result': {'type':'choice', 'next_state':_check_path}
},
'account_selection': {
'actions': [],
'result': {'type':'form', 'arch':account_form,'fields':account_fields, 'state':[('end','Cancel','gtk-cancel'),('checktype','Next','gtk-go-forward')]}
'result': {'type':'form', 'arch':account_form, 'fields':account_fields, 'state':[('end', 'Cancel', 'gtk-cancel'), ('checktype', 'Next', 'gtk-go-forward')]}
},
'checktype': {
'actions': [_get_defaults],
'result': {'type':'form', 'arch':period_form, 'fields':period_fields, 'state':[('end','Cancel','gtk-cancel'),('report','Print','gtk-print')]}
'result': {'type':'form', 'arch':period_form, 'fields':period_fields, 'state':[('end', 'Cancel', 'gtk-cancel'), ('report', 'Print', 'gtk-print')]}
},
'report': {
'actions': [_check_state],

View File

@ -40,9 +40,9 @@ class wizard_account_chart(wizard.interface):
'target_move': {
'string': 'Target Moves',
'type': 'selection',
'selection': [('all','All Entries'),('posted','All Posted Entries')],
'selection': [('all', 'All Entries'), ('posted', 'All Posted Entries')],
'required': True,
'default': lambda *a:"all",
'default': lambda * a:"all",
},
}
@ -59,9 +59,9 @@ class wizard_account_chart(wizard.interface):
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], context=context)[0]
result['context'] = str({'fiscalyear': data['form']['fiscalyear'],'state':data['form']['target_move']})
result['context'] = str({'fiscalyear': data['form']['fiscalyear'], 'state':data['form']['target_move']})
if data['form']['fiscalyear']:
result['name']+=':'+pooler.get_pool(cr.dbname).get('account.fiscalyear').read(cr,uid,[data['form']['fiscalyear']])[0]['code']
result['name'] += ':' + pooler.get_pool(cr.dbname).get('account.fiscalyear').read(cr, uid, [data['form']['fiscalyear']])[0]['code']
return result
states = {

View File

@ -41,37 +41,37 @@ _aged_trial_form = """<?xml version="1.0"?>
_aged_trial_fields = {
'company_id': {'string': 'Company', 'type': 'many2one', 'relation': 'res.company', 'required': True},
'period_length': {'string': 'Period length (days)', 'type': 'integer', 'required': True, 'default': lambda *a:30},
'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')},
'period_length': {'string': 'Period length (days)', 'type': 'integer', 'required': True, 'default': lambda * a:30},
'date1': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')},
'result_selection':{
'string':"Filter on Partners",
'type':'selection',
'selection':[('customer','Receivable'),('supplier','Payable'),('all','Receivable and Payable')],
'selection':[('customer', 'Receivable'), ('supplier', 'Payable'), ('all', 'Receivable and Payable')],
'required':True,
'default': lambda *a: 'all',
'default': lambda * a: 'all',
},
'direction_selection':{
'string':"Analysis Direction",
'type':'selection',
'selection':[('past','Past'),('future','Future')],
'selection':[('past', 'Past'), ('future', 'Future')],
'required':True,
'default': lambda *a: 'past',
'default': lambda * a: 'past',
},
}
def _calc_dates(self, cr, uid, data, context):
res = {}
period_length = data['form']['period_length']
if period_length<=0:
if period_length <= 0:
raise wizard.except_wizard(_('UserError'), _('You must enter a period length that cannot be 0 or below !'))
start = datetime.date.fromtimestamp(time.mktime(time.strptime(data['form']['date1'],"%Y-%m-%d")))
start = DateTime(int(start.year),int(start.month),int(start.day))
start = datetime.date.fromtimestamp(time.mktime(time.strptime(data['form']['date1'], "%Y-%m-%d")))
start = DateTime(int(start.year), int(start.month), int(start.day))
if data['form']['direction_selection'] == 'past':
for i in range(5)[::-1]:
stop = start - RelativeDateTime(days=period_length)
res[str(i)] = {
'name' : str((5-(i+1))*period_length) + '-' + str((5-i)*period_length),
'name' : str((5 - (i + 1)) * period_length) + '-' + str((5 - i) * period_length),
'stop': start.strftime('%Y-%m-%d'),
'start' : stop.strftime('%Y-%m-%d'),
}
@ -79,8 +79,8 @@ def _calc_dates(self, cr, uid, data, context):
else:
for i in range(5):
stop = start + RelativeDateTime(days=period_length)
res[str(5-(i+1))] = {
'name' : str((i)*period_length)+'-'+str((i+1)*period_length),
res[str(5 - (i + 1))] = {
'name' : str((i) * period_length) + '-' + str((i + 1) * period_length),
'start': start.strftime('%Y-%m-%d'),
'stop' : stop.strftime('%Y-%m-%d'),
}
@ -101,7 +101,7 @@ class wizard_report(wizard.interface):
states = {
'init': {
'actions': [_get_defaults],
'result': {'type':'form', 'arch':_aged_trial_form, 'fields':_aged_trial_fields, 'state':[('end','Cancel'),('print','Print Aged Trial Balance')]},
'result': {'type':'form', 'arch':_aged_trial_form, 'fields':_aged_trial_fields, 'state':[('end', 'Cancel'), ('print', 'Print Aged Trial Balance')]},
},
'print': {
'actions': [_calc_dates],

View File

@ -64,7 +64,7 @@ _reconcile_fields = {
'string': 'Account to reconcile',
'type': 'many2many',
'relation': 'account.account',
'domain': [('reconcile','=',1)],
'domain': [('reconcile', '=', 1)],
'help': 'If no account is specified, the reconciliation will be made using every accounts that can be reconcilied',
},
'writeoff_acc_id': {
@ -98,20 +98,20 @@ _reconcile_fields = {
'power': {
'string': 'Power',
'type': 'selection',
'selection': [(p,str(p)) for p in range(2, 10)],
'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')
'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')
'default': lambda * a: time.strftime('%Y-%m-%d')
},
}
@ -150,14 +150,14 @@ def do_reconcile(cr, uid, credits, debits, max_amount, power, writeoff_acc_id, p
return [move[0]]
else:
del move_list[i]
res = check(value - move[1], move_list, power-1)
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):
for p in range(1, power + 1):
res = check(value, move_list, p)
if res:
return res
@ -177,7 +177,7 @@ def do_reconcile(cr, uid, credits, debits, max_amount, power, writeoff_acc_id, p
return ([move[0]], res)
else:
del list1[i]
res = check3(value + move[1], list1, list2, list1power-1, power-1)
res = check3(value + move[1], list1, list2, list1power - 1, power - 1)
list1[i:i] = [move]
if res:
x, y = res
@ -190,9 +190,9 @@ def do_reconcile(cr, uid, credits, debits, max_amount, power, writeoff_acc_id, p
if res:
return res
return False
def check5(list1, list2, max_power):
for p in range(2, max_power+1):
for p in range(2, max_power + 1):
res = check4(list1, list2, p)
if res:
return res
@ -209,8 +209,8 @@ def do_reconcile(cr, uid, credits, debits, max_amount, power, writeoff_acc_id, p
debits = [(id, debit) for (id, debit) in debits if id not in res[1]]
else:
ok = False
return (reconciled, len(credits)+len(debits))
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')
@ -221,7 +221,7 @@ def _reconcile(self, cr, uid, data, context):
if not form['account_ids'][0][2]:
raise wizard.except_wizard(_('UserError'), _('You must select accounts to reconcile'))
for account_id in form['account_ids'][0][2]:
# reconcile automatically all transactions from partners whose balance is 0
cr.execute(
"SELECT partner_id " \
@ -244,11 +244,11 @@ def _reconcile(self, cr, uid, data, context):
"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 " \
@ -274,7 +274,7 @@ def _reconcile(self, cr, uid, data, context):
"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 " \
@ -286,7 +286,7 @@ def _reconcile(self, cr, uid, data, context):
"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
@ -302,17 +302,17 @@ def _reconcile(self, cr, uid, data, context):
"AND state <> 'draft' " + partner_filter,
(account_id,))
additional_unrec = cr.fetchone()[0]
return {'reconciled':reconciled, 'unreconciled':unreconciled+additional_unrec}
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')]}
'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')]}
'result': {'type':'form', 'arch':_result_form, 'fields':_result_fields, 'state':[('end', 'OK')]}
}
}
wiz_reconcile('account.automatic.reconcile')

View File

@ -38,7 +38,7 @@ def _action_open_window(self, cr, uid, data, context):
if not account_id:
raise wizard.except_wizard(_('Error'), _('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),
'domain': "[('journal_id','=',%d), ('account_id','=',%d), ('state','<>','draft')]" % (form['journal_id'], account_id),
'name': _('Standard Encoding'),
'view_type': 'form',
@ -53,7 +53,7 @@ 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')]}
'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end', 'Cancel'), ('open', 'Open for bank reconciliation')]}
},
'open': {
'actions': [],

View File

@ -37,15 +37,15 @@ fields = {
def _check_data(self, cr, uid, data, *args):
period_id = data['form']['period_id'][0][2]
journal_id=data['form']['journal_id'][0][2]
journal_id = data['form']['journal_id'][0][2]
if type(period_id) == type([]):
if type(period_id)==type([]):
ids_final = []
for journal in journal_id:
for period in period_id:
ids_journal_period = pooler.get_pool(cr.dbname).get('account.journal.period').search(cr,uid, [('journal_id','=',journal),('period_id','=',period)])
ids_journal_period = pooler.get_pool(cr.dbname).get('account.journal.period').search(cr, uid, [('journal_id', '=', journal), ('period_id', '=', period)])
if ids_journal_period:
ids_final.append(ids_journal_period)

View File

@ -30,49 +30,49 @@ class wizard_change_currency(wizard.interface):
<form string="Invoice Currency">
<field name="currency_id"/>
</form>'''
message = '''<?xml version="1.0"?>
<form string="Invoice Currency">
<label string="You can not change currency for Open Invoice !"/>
</form>'''
fields = {
'currency_id': {'string': 'New Currency', 'type': 'many2one', 'relation': 'res.currency', 'required':True},
}
def _get_defaults(self, cr, user, data, context):
#TODO : initlize required data
return data['form']
return data['form']
def _change_currency(self, cr, uid, data, context):
pool = pooler.get_pool(cr.dbname)
inv_obj = pool.get('account.invoice')
inv_line_obj = pool.get('account.invoice.line')
curr_obj = pool.get('res.currency')
invoice_ids = data['ids']
new_currency = data['form']['currency_id']
for invoice in inv_obj.browse(cr, uid, invoice_ids, context=context):
if invoice.currency_id.id == new_currency:
continue
for line in invoice.invoice_line:
rate = curr_obj.browse(cr, uid, new_currency).rate
new_price = 0
if invoice.company_id.currency_id.id == invoice.currency_id.id:
new_price = line.price_unit * rate
if invoice.company_id.currency_id.id != invoice.currency_id.id and invoice.company_id.currency_id.id == new_currency:
old_rate = invoice.currency_id.rate
new_price = line.price_unit / old_rate
if invoice.company_id.currency_id.id != invoice.currency_id.id and invoice.company_id.currency_id.id != new_currency:
old_rate = invoice.currency_id.rate
new_price = (line.price_unit / old_rate ) * rate
new_price = (line.price_unit / old_rate) * rate
inv_line_obj.write(cr, uid, [line.id], {'price_unit':new_price})
inv_obj.write(cr, uid, [invoice.id], {'currency_id':new_currency})
return {}
@ -82,9 +82,9 @@ class wizard_change_currency(wizard.interface):
inv_obj = pool.get('account.invoice')
if inv_obj.browse(cr, uid, data['id']).state != 'draft':
return 'message'
return 'change'
states = {
'init': {
'actions': [],

View File

@ -37,10 +37,10 @@ _transaction_form = '''<?xml version="1.0"?>
</form>'''
_transaction_fields = {
'fy_id': {'string':'Fiscal Year to close', 'type':'many2one', 'relation': 'account.fiscalyear','required':True, 'domain':[('state','=','draft')]},
'journal_id': {'string':'Opening Entries Journal', 'type':'many2one', 'relation': 'account.journal','required':True},
'period_id': {'string':'Opening Entries Period', 'type':'many2one', 'relation': 'account.period','required':True, 'domain':"[('fiscalyear_id','=',fy2_id)]"},
'fy2_id': {'string':'New Fiscal Year', 'type':'many2one', 'relation': 'account.fiscalyear', 'domain':[('state','=','draft')], 'required':True},
'fy_id': {'string':'Fiscal Year to close', 'type':'many2one', 'relation': 'account.fiscalyear', 'required':True, 'domain':[('state', '=', 'draft')]},
'journal_id': {'string':'Opening Entries Journal', 'type':'many2one', 'relation': 'account.journal', 'required':True},
'period_id': {'string':'Opening Entries Period', 'type':'many2one', 'relation': 'account.period', 'required':True, 'domain':"[('fiscalyear_id','=',fy2_id)]"},
'fy2_id': {'string':'New Fiscal Year', 'type':'many2one', 'relation': 'account.fiscalyear', 'domain':[('state', '=', 'draft')], 'required':True},
'report_name': {'string':'Name of new entries', 'type':'char', 'size': 64, 'required':True},
'sure': {'string':'Check this box', 'type':'boolean'},
}
@ -73,7 +73,7 @@ def _data_save(self, cr, uid, data, context):
_('The journal must have centralised counterpart'))
move_ids = pool.get('account.move.line').search(cr, uid, [
('journal_id','=',new_journal.id),('period_id.fiscalyear_id','=',new_fyear.id)])
('journal_id', '=', new_journal.id), ('period_id.fiscalyear_id', '=', new_fyear.id)])
if move_ids:
raise wizard.except_wizard(_('UserError'),
_('The opening journal must not have any entry in the new fiscal year !'))
@ -91,13 +91,13 @@ def _data_save(self, cr, uid, data, context):
accnt_type_data = account.user_type
if not accnt_type_data:
continue
if accnt_type_data.close_method=='none' or account.type == 'view':
if accnt_type_data.close_method == 'none' or account.type == 'view':
continue
if accnt_type_data.close_method=='balance':
if abs(account.balance)>0.0001:
if accnt_type_data.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,
'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,
@ -150,7 +150,7 @@ def _data_save(self, cr, uid, data, context):
'AND b.period_id =ANY(%s)'\
'AND a.period_id =ANY(%s)' \
'ORDER BY id ' \
'LIMIT %s OFFSET %s', (account.id,period_ids,periods_fy2,limit, offset))
'LIMIT %s OFFSET %s', (account.id, period_ids, periods_fy2, limit, offset))
result = cr.dictfetchall()
if not result:
break
@ -166,7 +166,7 @@ def _data_save(self, cr, uid, data, context):
'period_id': period.id,
})
offset += limit
if accnt_type_data.close_method=='detail':
if accnt_type_data.close_method == 'detail':
offset = 0
limit = 100
while True:
@ -191,17 +191,17 @@ def _data_save(self, cr, uid, data, context):
})
pool.get('account.move.line').create(cr, uid, move)
offset += limit
ids = pool.get('account.move.line').search(cr, uid, [('journal_id','=',new_journal.id),
('period_id.fiscalyear_id','=',new_fyear.id)])
ids = pool.get('account.move.line').search(cr, uid, [('journal_id', '=', new_journal.id),
('period_id.fiscalyear_id', '=', new_fyear.id)])
context['fy_closing'] = True
if ids:
pool.get('account.move.line').reconcile(cr, uid, ids, context=context)
new_period = data['form']['period_id']
ids = pool.get('account.journal.period').search(cr, uid, [('journal_id','=',new_journal.id),('period_id','=',new_period)])
ids = pool.get('account.journal.period').search(cr, uid, [('journal_id', '=', new_journal.id), ('period_id', '=', new_period)])
if not ids:
ids = [pool.get('account.journal.period').create(cr, uid, {
'name': (new_journal.name or '')+':'+(period.code or ''),
'name': (new_journal.name or '') + ':' + (period.code or ''),
'journal_id': new_journal.id,
'period_id': period.id
})]
@ -214,7 +214,7 @@ class wiz_journal_close(wizard.interface):
states = {
'init': {
'actions': [_data_load],
'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Create entries')]}
'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end', 'Cancel'), ('close', 'Create entries')]}
},
'close': {
'actions': [_data_save],

View File

@ -32,7 +32,7 @@ _transaction_form = '''<?xml version="1.0"?>
</form>'''
_transaction_fields = {
'fy_id': {'string':'Fiscal Year to close', 'type':'many2one', 'relation': 'account.fiscalyear','required':True, 'domain':[('state','=','draft')]},
'fy_id': {'string':'Fiscal Year to close', 'type':'many2one', 'relation': 'account.fiscalyear', 'required':True, 'domain':[('state', '=', 'draft')]},
'sure': {'string':'Check this box', 'type':'boolean'},
}
@ -46,9 +46,9 @@ def _data_save(self, cr, uid, data, context):
cr.execute('UPDATE account_journal_period ' \
'SET state = %s ' \
'WHERE period_id IN (SELECT id FROM account_period WHERE fiscalyear_id = %s)',
('done',fy_id))
('done', fy_id))
cr.execute('UPDATE account_period SET state = %s ' \
'WHERE fiscalyear_id = %s', ('done',fy_id))
'WHERE fiscalyear_id = %s', ('done', fy_id))
cr.execute('UPDATE account_fiscalyear ' \
'SET state = %s WHERE id = %s', ('done', fy_id))
return {}
@ -57,7 +57,7 @@ class wiz_journal_close_state(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Close states')]}
'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end', 'Cancel'), ('close', 'Close states')]}
},
'close': {
'actions': [_data_save],

View File

@ -36,15 +36,15 @@ fields = {
def _check_data(self, cr, uid, data, *args):
period_id = data['form']['period_id'][0][2]
journal_id=data['form']['journal_id'][0][2]
journal_id = data['form']['journal_id'][0][2]
if type(period_id) == type([]):
if type(period_id)==type([]):
ids_final = []
for journal in journal_id:
for period in period_id:
ids_journal_period = pooler.get_pool(cr.dbname).get('account.journal.period').search(cr,uid, [('journal_id','=',journal),('period_id','=',period)])
ids_journal_period = pooler.get_pool(cr.dbname).get('account.journal.period').search(cr, uid, [('journal_id', '=', journal), ('period_id', '=', period)])
if ids_journal_period:
ids_final.append(ids_journal_period)

View File

@ -31,7 +31,7 @@ account_form = '''<?xml version="1.0"?>
</form>'''
account_fields = {
'Account_list': {'string':'Chart of Accounts', 'type':'many2one', 'relation':'account.account', 'required':True ,'domain':[('parent_id','=',False)]},
'Account_list': {'string':'Chart of Accounts', 'type':'many2one', 'relation':'account.account', 'required':True , 'domain':[('parent_id', '=', False)]},
}
period_form = '''<?xml version="1.0"?>
@ -76,19 +76,19 @@ period_fields = {
'state':{
'string':"Date/Period Filter",
'type':'selection',
'selection':[('bydate','By Date'),('byperiod','By Period'),('all','By Date and Period'),('none','No Filter')],
'default': lambda *a:'none'
'selection':[('bydate', 'By Date'), ('byperiod', 'By Period'), ('all', 'By Date and Period'), ('none', 'No Filter')],
'default': lambda * a:'none'
},
'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'},
'sortbydate':{'string':"Sort by:",'type':'selection','selection':[('sort_date','Date'),('sort_mvt','Movement')]},
'display_account':{'string':"Display accounts ",'type':'selection','selection':[('bal_mouvement','With movements'),('bal_all','All'),('bal_solde','With balance is not equal to 0')]},
'landscape':{'string':"Landscape Mode",'type':'boolean'},
'soldeinit':{'string':"Include initial balances",'type':'boolean'},
'amount_currency':{'string':"With Currency",'type':'boolean'},
'date_from': {'string':" Start date",'type':'date','required':True ,'default': lambda *a: time.strftime('%Y-01-01')},
'date_to': {'string':"End date",'type':'date','required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')},
'sortbydate':{'string':"Sort by:", 'type':'selection', 'selection':[('sort_date', 'Date'), ('sort_mvt', 'Movement')]},
'display_account':{'string':"Display accounts ", 'type':'selection', 'selection':[('bal_mouvement', 'With movements'), ('bal_all', 'All'), ('bal_solde', 'With balance is not equal to 0')]},
'landscape':{'string':"Landscape Mode", 'type':'boolean'},
'soldeinit':{'string':"Include initial balances", 'type':'boolean'},
'amount_currency':{'string':"With Currency", 'type':'boolean'},
'date_from': {'string':" Start date", 'type':'date', 'required':True , 'default': lambda * a: time.strftime('%Y-01-01')},
'date_to': {'string':"End date", 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')},
}
def _check_path(self, cr, uid, data, context):
if data['model'] == 'account.account':
@ -97,7 +97,7 @@ def _check_path(self, cr, uid, data, context):
return 'account_selection'
def _check(self, cr, uid, data, context):
if data['form']['landscape']==True:
if data['form']['landscape'] == True:
return 'report_landscape'
else:
return 'report'
@ -106,16 +106,16 @@ def _check_date(self, cr, uid, data, context):
sql = """
SELECT f.id, f.date_start, f.date_stop FROM account_fiscalyear f Where %s between f.date_start and f.date_stop """
cr.execute(sql,(data['form']['date_from'],))
cr.execute(sql, (data['form']['date_from'],))
res = cr.dictfetchall()
if res:
if (data['form']['date_to'] > res[0]['date_stop'] or data['form']['date_to'] < res[0]['date_start']):
raise wizard.except_wizard(_('UserError'),_('Date to must be set between %s and %s') % (str(res[0]['date_start']), str(res[0]['date_stop'])))
raise wizard.except_wizard(_('UserError'), _('Date to must be set between %s and %s') % (str(res[0]['date_start']), str(res[0]['date_stop'])))
else:
return 'checkreport'
else:
raise wizard.except_wizard(_('UserError'),_('Date not in a defined fiscal year'))
raise wizard.except_wizard(_('UserError'), _('Date not in a defined fiscal year'))
def _check_state(self, cr, uid, data, context):
@ -142,8 +142,8 @@ class wizard_report(wizard.interface):
#periods_obj=pooler.get_pool(cr.dbname).get('account.period')
#data['form']['periods'] =periods_obj.search(cr, uid, [('fiscalyear_id','=',data['form']['fiscalyear'])])
data['form']['sortbydate'] = 'sort_date'
data['form']['display_account']='bal_all'
data['form']['landscape']=True
data['form']['display_account'] = 'bal_all'
data['form']['landscape'] = True
data['form']['fiscalyear'] = False
data['form']['amount_currency'] = True
data['form']['context'] = context
@ -152,19 +152,19 @@ class wizard_report(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type':'choice','next_state':_check_path}
'result': {'type':'choice', 'next_state':_check_path}
},
'account_selection': {
'actions': [],
'result': {'type':'form', 'arch':account_form,'fields':account_fields, 'state':[('end','Cancel','gtk-cancel'),('checktype','Next','gtk-go-forward')]}
'result': {'type':'form', 'arch':account_form, 'fields':account_fields, 'state':[('end', 'Cancel', 'gtk-cancel'), ('checktype', 'Next', 'gtk-go-forward')]}
},
'checktype': {
'actions': [_get_defaults],
'result': {'type':'form', 'arch':period_form, 'fields':period_fields, 'state':[('end','Cancel','gtk-cancel'),('checkreport','Print','gtk-print')]}
'result': {'type':'form', 'arch':period_form, 'fields':period_fields, 'state':[('end', 'Cancel', 'gtk-cancel'), ('checkreport', 'Print', 'gtk-print')]}
},
'checkreport': {
'actions': [],
'result': {'type':'choice','next_state':_check}
'result': {'type':'choice', 'next_state':_check}
},
'report_landscape': {
'actions': [_check_state],

View File

@ -31,7 +31,7 @@ def _invoice_confirm(self, cr, uid, data, context):
class wizard_invoice_confirm(wizard.interface):
states = {
'init': {
'actions': [_invoice_confirm],
'actions': [_invoice_confirm],
'result': {'type':'state', 'state':'end'}
}
}
@ -47,7 +47,7 @@ def _invoice_cancel(self, cr, uid, data, context):
class wizard_invoice_cancel(wizard.interface):
states = {
'init': {
'actions': [_invoice_cancel],
'actions': [_invoice_cancel],
'result': {'type':'state', 'state':'end'}
}
}

View File

@ -42,9 +42,9 @@ def _period_get(self, cr, uid, datas, ctx={}):
_journal_fields = {
'journal_id': {'string':'Journal', 'type':'many2one', 'relation':'account.journal', 'required':True},
'period_id': {
'string':'Period',
'type':'many2one',
'relation':'account.period',
'string':'Period',
'type':'many2one',
'relation':'account.period',
'required':True,
}
}
@ -54,7 +54,7 @@ def _action_open_window(self, cr, uid, data, context):
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'])])
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']
@ -62,30 +62,30 @@ def _action_open_window(self, cr, uid, data, context):
raise wizard.except_wizard(_('UserError'), _('This period is already closed !'))
company = pooler.get_pool(cr.dbname).get('account.period').read(cr, uid, [form['period_id']])[0]['company_id'][0]
jp.create(cr, uid, {'name':name, 'period_id': form['period_id'], 'journal_id':form['journal_id'], 'company_id':company})
ids = jp.search(cr, uid, [('journal_id','=',form['journal_id']), ('period_id','=',form['period_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 '')
mod_obj = pooler.get_pool(cr.dbname).get('ir.model.data')
result = mod_obj._get_id(cr, uid, 'account', 'view_account_move_line_filter')
id = mod_obj.read(cr, uid, result, ['res_id'])
id = mod_obj.read(cr, uid, result, ['res_id'])
return {
'domain': "[('journal_id','=',%d), ('period_id','=',%d)]" % (form['journal_id'],form['period_id']),
'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']),
'context': "{'journal_id':%d, 'period_id':%d}" % (form['journal_id'], form['period_id']),
'type': 'ir.actions.act_window',
'search_view_id': id['res_id']
'search_view_id': id['res_id']
}
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')]}
'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end', 'Cancel'), ('open', 'Open Journal')]}
},
'open': {
'actions': [],

View File

@ -31,7 +31,7 @@ def _action_open_window(self, cr, uid, data, context):
result = act_obj.read(cr, uid, [id])[0]
cr.execute('select journal_id,period_id from account_journal_period where id=%s', (data['id'],))
journal_id,period_id = cr.fetchone()
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})

View File

@ -52,7 +52,7 @@ class wizard_move_line_select(wizard.interface):
acc_data = account_obj.browse(cr, uid, data['id']).child_consol_ids
if acc_data:
result['context'].update({'consolidate_childs': True})
result['domain']=result['domain'][0:-1]+','+domain+result['domain'][-1]
result['domain'] = result['domain'][0:-1] + ',' + domain + result['domain'][-1]
return result
states = {

View File

@ -37,13 +37,13 @@ fields = {
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'])
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 writing has been defined for the fiscal year'))
period_journal = data_fyear.end_journal_period_id
ids_move = pool.get('account.move').search(cr,uid,[('journal_id','=',period_journal.journal_id.id),('period_id','=',period_journal.period_id.id)])
ids_move = pool.get('account.move').search(cr, uid, [('journal_id', '=', period_journal.journal_id.id), ('period_id', '=', period_journal.period_id.id)])
if ids_move:
cr.execute('delete from account_move where id =ANY(%s)',(ids_move,))
cr.execute('delete from account_move where id =ANY(%s)', (ids_move,))
#cr.execute('UPDATE account_journal_period ' \
# 'SET state = %s ' \
# 'WHERE period_id IN (SELECT id FROM account_period WHERE fiscalyear_id = %s)',
@ -63,7 +63,7 @@ class open_closed_fiscal(wizard.interface):
'type': 'form',
'arch': form,
'fields': fields,
'state':[('end','Cancel'),('open','Open')]
'state':[('end', 'Cancel'), ('open', 'Open')]
}
},
'open': {

View File

@ -53,29 +53,29 @@ period_fields = {
'state':{
'string':"Date/Period Filter",
'type':'selection',
'selection':[('bydate','By Date'),('byperiod','By Period'),('all','By Date and Period'),('none','No Filter')],
'default': lambda *a:'none'
'selection':[('bydate', 'By Date'), ('byperiod', 'By Period'), ('all', 'By Date and Period'), ('none', 'No Filter')],
'default': lambda * a:'none'
},
'fiscalyear': {
'string':'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear',
'default': lambda *a:False,
'default': lambda * a:False,
'help': 'Keep empty for all open fiscal year'
},
'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty'},
'result_selection':{
'string':"Partner",
'type':'selection',
'selection':[('customer','Receivable Accounts'),('supplier','Payable Accounts'),('all','Receivable and Payable Accounts')],
'selection':[('customer', 'Receivable Accounts'), ('supplier', 'Payable Accounts'), ('all', 'Receivable and Payable Accounts')],
'required':True
},
'soldeinit':{'string':"Include initial balances",'type':'boolean'},
'date1': {'string':' Start date', 'type':'date', 'required':True,'default': lambda *a: time.strftime('%Y-01-01')},
'date2': {'string':'End date', 'type':'date', 'required':True,'default': lambda *a: time.strftime('%Y-%m-%d')},
'soldeinit':{'string':"Include initial balances", 'type':'boolean'},
'date1': {'string':' Start date', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-01-01')},
'date2': {'string':'End date', '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):
def _get_defaults(self, cr, uid, data, context):
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
@ -83,9 +83,9 @@ class wizard_report(wizard.interface):
company_id = pooler.get_pool(cr.dbname).get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
periods_obj=pooler.get_pool(cr.dbname).get('account.period')
periods_obj = pooler.get_pool(cr.dbname).get('account.period')
data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid)
data['form']['periods'] =periods_obj.search(cr, uid, [('fiscalyear_id','=',data['form']['fiscalyear'])])
data['form']['periods'] = periods_obj.search(cr, uid, [('fiscalyear_id', '=', data['form']['fiscalyear'])])
data['form']['company_id'] = company_id
data['form']['soldeinit'] = True
data['form']['fiscalyear'] = False
@ -101,21 +101,21 @@ class wizard_report(wizard.interface):
def _check_date(self, cr, uid, data, context):
sql = """
SELECT f.id, f.date_start, f.date_stop FROM account_fiscalyear f Where %s between f.date_start and f.date_stop """
cr.execute(sql,(data['form']['date1'],))
cr.execute(sql, (data['form']['date1'],))
res = cr.dictfetchall()
if res:
if (data['form']['date2'] > res[0]['date_stop'] or data['form']['date2'] < res[0]['date_start']):
raise wizard.except_wizard(_('UserError'),_('Date to must be set between %s and %s') % (str(res[0]['date_start']), str(res[0]['date_stop'])))
raise wizard.except_wizard(_('UserError'), _('Date to must be set between %s and %s') % (str(res[0]['date_start']), str(res[0]['date_stop'])))
else:
return 'report'
else:
raise wizard.except_wizard(_('UserError'),_('Date not in a defined fiscal year'))
raise wizard.except_wizard(_('UserError'), _('Date not in a defined fiscal year'))
states = {
'init': {
'actions': [_get_defaults],
'result': {'type':'form', 'arch':period_form, 'fields':period_fields, 'state':[('end','Cancel','gtk-cancel'),('report','Print','gtk-print')]}
'result': {'type':'form', 'arch':period_form, 'fields':period_fields, 'state':[('end', 'Cancel', 'gtk-cancel'), ('report', 'Print', 'gtk-print')]}
},
'report': {

View File

@ -37,10 +37,10 @@ pay_form = '''<?xml version="1.0"?>
</form>'''
pay_fields = {
'amount': {'string': 'Amount paid', 'type':'float', 'required':True, 'digits': (16,int(tools.config['price_accuracy']))},
'amount': {'string': 'Amount paid', 'type':'float', 'required':True, 'digits': (16, int(tools.config['price_accuracy']))},
'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/Payment Mode', 'type': 'many2one', 'relation':'account.journal', 'required':True, 'domain':[('type','=','cash')]},
'date': {'string': 'Payment date', 'type':'date', 'required':True, 'default':lambda * args: time.strftime('%Y-%m-%d')},
'journal_id': {'string': 'Journal/Payment Mode', 'type': 'many2one', 'relation':'account.journal', 'required':True, 'domain':[('type', '=', 'cash')]},
'period_id': {'string': 'Period', 'type': 'many2one', 'relation':'account.period', 'required':True},
}
@ -59,25 +59,25 @@ def _pay_and_reconcile(self, cr, uid, data, context):
journal = pool.get('account.journal').browse(cr, uid, data['form']['journal_id'], context)
# Compute the amount in company's currency, with the journal currency (which is equal to payment currency)
# when it is needed : If payment currency (according to selected journal.currency) is <> from company currency
if journal.currency and invoice.company_id.currency_id.id<>journal.currency.id:
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)
currency_id = journal.currency.id
# Put the paid amount in currency, and the currency, in the context if currency is different from company's currency
context.update({'amount_currency':form['amount'],'currency_id':currency_id})
if invoice.company_id.currency_id.id<>invoice.currency_id.id:
context.update({'amount_currency':form['amount'], 'currency_id':currency_id})
if invoice.company_id.currency_id.id <> invoice.currency_id.id:
ctx = {'date':data['form']['date']}
amount = cur_obj.compute(cr, uid, invoice.currency_id.id, invoice.company_id.currency_id.id, amount, context=ctx)
currency_id = invoice.currency_id.id
# Put the paid amount in currency, and the currency, in the context if currency is different from company's currency
context.update({'amount_currency':form['amount'],'currency_id':currency_id})
context.update({'amount_currency':form['amount'], 'currency_id':currency_id})
# Take the choosen date
if form.has_key('comment'):
context.update({'date_p':form['date'],'comment':form['comment']})
context.update({'date_p':form['date'], 'comment':form['comment']})
else:
context.update({'date_p':form['date'],'comment':False})
context.update({'date_p':form['date'], 'comment':False})
acc_id = journal.default_credit_account_id and journal.default_credit_account_id.id
if not acc_id:
@ -106,19 +106,19 @@ def _wo_check(self, cr, uid, data, context):
inv_amount_company_currency = abs(inv_amount_company_currency)
# Get the current amount paid in company currency
if journal.currency and invoice.company_id.currency_id.id<>journal.currency.id:
if journal.currency and invoice.company_id.currency_id.id <> journal.currency.id:
ctx = {'date':data['form']['date']}
amount_paid = cur_obj.compute(cr, uid, journal.currency.id, invoice.company_id.currency_id.id, data['form']['amount'], round=True, context=ctx)
else:
amount_paid = data['form']['amount']
# Get the old payment if there are some
if invoice.payment_ids:
debit=credit=0.0
debit = credit = 0.0
for payment in invoice.payment_ids:
debit+=payment.debit
credit+=payment.credit
amount_paid+=abs(debit-credit)
debit += payment.debit
credit += payment.credit
amount_paid += abs(debit - credit)
# Test if there is a difference according to currency rouding setting
if pool.get('res.currency').is_zero(cr, uid, invoice.company_id.currency_id,
(amount_paid - inv_amount_company_currency)):
@ -164,7 +164,7 @@ 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')]}
'result': {'type':'form', 'arch':pay_form, 'fields':pay_fields, 'state':[('end', 'Cancel'), ('reconcile', 'Partial Payment'), ('writeoff_check', 'Full Payment')]}
},
'writeoff_check': {
'actions': [],
@ -172,7 +172,7 @@ class wizard_pay_invoice(wizard.interface):
},
'addendum': {
'actions': [_get_value_addendum],
'result': {'type': 'form', 'arch':_transaction_add_form, 'fields':_transaction_add_fields, 'state':[('end','Cancel'),('reconcile','Pay and reconcile')]}
'result': {'type': 'form', 'arch':_transaction_add_form, 'fields':_transaction_add_fields, 'state':[('end', 'Cancel'), ('reconcile', 'Pay and reconcile')]}
},
'reconcile': {
'actions': [_pay_and_reconcile],

View File

@ -43,7 +43,7 @@ class wiz_journal_close(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('close','Close Period')]}
'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end', 'Cancel'), ('close', 'Close Period')]}
},
'close': {
'actions': [_data_save],

View File

@ -36,24 +36,24 @@ fields = {
'sort_selection':{
'string':"Entries Sorted By",
'type':'selection',
'selection':[('date','By date'),('ref','Reference Number')],
'selection':[('date', 'By date'), ('ref', 'Reference Number')],
'required':True,
'default': lambda *a: 'date',
'default': lambda * a: 'date',
},
}
def _check_data(self, cr, uid, data, *args):
period_id = data['form']['period_id'][0][2]
journal_id=data['form']['journal_id'][0][2]
journal_id = data['form']['journal_id'][0][2]
if type(period_id) == type([]):
if type(period_id)==type([]):
ids_final = []
for journal in journal_id:
for period in period_id:
ids_journal_period = pooler.get_pool(cr.dbname).get('account.journal.period').search(cr,uid, [('journal_id','=',journal),('period_id','=',period)])
ids_journal_period = pooler.get_pool(cr.dbname).get('account.journal.period').search(cr, uid, [('journal_id', '=', journal), ('period_id', '=', period)])
if ids_journal_period:
ids_final.append(ids_journal_period)

View File

@ -88,7 +88,7 @@ def _trans_rec_reconcile(self, cr, uid, data, context=None):
return {}
def _partial_check(self, cr, uid, data, context):
if _trans_rec_get(self,cr,uid, data, context)['writeoff'] == 0:
if _trans_rec_get(self, cr, uid, data, context)['writeoff'] == 0:
return 'init_full'
return 'init_partial'
@ -106,8 +106,8 @@ _transaction_add_form = '''<?xml version="1.0"?>
_transaction_add_fields = {
'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},
'date_p': {'string':'Date','type':'date'},
'comment': {'string':'Comment','type':'char', 'size': 64, 'required':True},
'date_p': {'string':'Date', 'type':'date'},
'comment': {'string':'Comment', 'type':'char', 'size': 64, 'required':True},
'analytic_id': {'string':'Analytic Account', 'type': 'many2one', 'relation':'account.analytic.account'},
}
@ -124,15 +124,15 @@ class wiz_reconcile(wizard.interface):
},
'init_full': {
'actions': [_trans_rec_get],
'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('reconcile','Reconcile')]}
'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')]}
'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')]}
'result': {'type': 'form', 'arch':_transaction_add_form, 'fields':_transaction_add_fields, 'state':[('end', 'Cancel'), ('reconcile', 'Reconcile')]}
},
'reconcile': {
'actions': [_trans_rec_reconcile],

View File

@ -29,7 +29,7 @@ _journal_form = '''<?xml version="1.0"?>
</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):
@ -47,7 +47,7 @@ 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')]}
'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end', 'Cancel'), ('open', 'Open for reconciliation')]}
},
'open': {
'actions': [],

View File

@ -36,7 +36,7 @@ sur_form = '''<?xml version="1.0"?>
</form>'''
sur_fields = {
'date': {'string':'Operation date','type':'date', 'required':'False'},
'date': {'string':'Operation date', 'type':'date', 'required':'False'},
'period':{'string': 'Force period', 'type': 'many2one',
'relation': 'account.period', 'required': False},
'description':{'string':'Description', 'type':'char', 'required':'True'},
@ -81,7 +81,7 @@ class wiz_refund(wizard.interface):
cr.execute("""SELECT id
from account_period where date('%s')
between date_start AND date_stop and company_id = %s limit 1 """,
(form['date'],pool.get('res.users').browse(cr,uid,uid).company_id.id,))
(form['date'], pool.get('res.users').browse(cr, uid, uid).company_id.id,))
else:
#in mono company mode
cr.execute("""SELECT id
@ -102,17 +102,17 @@ class wiz_refund(wizard.interface):
if not period:
raise wizard.except_wizard(_('Data Insufficient !'), _('No Period found on Invoice!'))
refund_id = pool.get('account.invoice').refund(cr, uid, [inv.id],date, period, description)
refund_id = pool.get('account.invoice').refund(cr, uid, [inv.id], date, period, description)
refund = pool.get('account.invoice').browse(cr, uid, refund_id[0])
# we compute due date
#!!!due date = date inv date on formdate
pool.get('account.invoice').write(cr, uid, [refund.id],{'date_due':date,'check_total':inv.check_total})
pool.get('account.invoice').write(cr, uid, [refund.id], {'date_due':date, 'check_total':inv.check_total})
# to make the taxes calculated
pool.get('account.invoice').button_compute(cr, uid, refund_id)
created_inv.append(refund_id[0])
#if inv is paid we unreconcile
if mode in ('cancel','modify'):
if mode in ('cancel', 'modify'):
movelines = inv.move_id.line_id
#we unreconcile the lines
to_reconcile_ids = {}
@ -120,9 +120,9 @@ class wiz_refund(wizard.interface):
#if the account of the line is the as the one in the invoice
#we reconcile
if line.account_id.id == inv.account_id.id :
to_reconcile_ids[line.account_id.id] =[line.id]
to_reconcile_ids[line.account_id.id] = [line.id]
if type(line.reconcile_id) != osv.orm.browse_null :
reconcile_obj.unlink(cr,uid, line.reconcile_id.id)
reconcile_obj.unlink(cr, uid, line.reconcile_id.id)
#we advance the workflow of the refund to open
wf_service = netsvc.LocalService('workflow')
wf_service.trg_validate(uid, 'account.invoice', refund.id, 'invoice_open', cr)
@ -143,9 +143,9 @@ class wiz_refund(wizard.interface):
invoice = pool.get('account.invoice').read(cr, uid, [inv.id],
['name', 'type', 'number', 'reference',
'comment', 'date_due', 'partner_id', 'address_contact_id',
'address_invoice_id', 'partner_insite','partner_contact',
'address_invoice_id', 'partner_insite', 'partner_contact',
'partner_ref', 'payment_term', 'account_id', 'currency_id',
'invoice_line', 'tax_line', 'journal_id','period_id'
'invoice_line', 'tax_line', 'journal_id', 'period_id'
]
)
invoice = invoice[0]
@ -173,12 +173,12 @@ class wiz_refund(wizard.interface):
invoice[field] = invoice[field] and invoice[field][0]
# create the new invoice
inv_id = pool.get('account.invoice').create(cr, uid, invoice,{})
inv_id = pool.get('account.invoice').create(cr, uid, invoice, {})
# we compute due date
if inv.payment_term.id:
data = pool.get('account.invoice').onchange_payment_term_date_invoice(cr, uid, [inv_id],inv.payment_term.id,date)
data = pool.get('account.invoice').onchange_payment_term_date_invoice(cr, uid, [inv_id], inv.payment_term.id, date)
if 'value' in data and data['value']:
pool.get('account.invoice').write(cr, uid, [inv_id],data['value'])
pool.get('account.invoice').write(cr, uid, [inv_id], data['value'])
created_inv.append(inv_id)
#we get the view id
@ -204,7 +204,7 @@ class wiz_refund(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type':'form', 'arch':sur_form, 'fields':sur_fields, 'state':[('end','Cancel'),('refund','Refund Invoice'),('cancel_invoice','Cancel Invoice'),('modify_invoice','Modify Invoice')]}
'result': {'type':'form', 'arch':sur_form, 'fields':sur_fields, 'state':[('end', 'Cancel'), ('refund', 'Refund Invoice'), ('cancel_invoice', 'Cancel Invoice'), ('modify_invoice', 'Modify Invoice')]}
},
'refund': {
'actions': [],

View File

@ -47,7 +47,7 @@ class wiz_state_open(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type':'form', 'arch':form, 'fields':fields, 'state':[('end','No','gtk-no'),('yes','Yes','gtk-yes')]}
'result': {'type':'form', 'arch':form, 'fields':fields, 'state':[('end', 'No', 'gtk-no'), ('yes', 'Yes', 'gtk-yes')]}
},
'yes': {
'actions': [_change_inv_state],

View File

@ -36,11 +36,11 @@ FORM = UpdateableStr()
FIELDS = {
'lines': {'string': 'Invoices', 'type': 'many2many',
'relation': 'account.move.line'},
}
START_FIELD = {
'date': {'string': 'Date payment', 'type': 'date','required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')},
'date': {'string': 'Date payment', 'type': 'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')},
'journal_id': {'string': 'Journal', 'type': 'many2many', 'relation': 'account.journal', 'domain': '[("type","in",["sale","purchase","cash"])]', 'help': 'This field allows you to choose the accounting journals you want for filtering the invoices. If you left this field empty, it will search on all sale, purchase and cash journals.'},
}
@ -63,33 +63,33 @@ def _search_invoices(obj, cr, uid, data, context):
# Creating a group that is unique for importing move lines(move lines, once imported into statement lines, should not appear again)
for st_line in statement.line_ids:
args_move_line = []
args_move_line.append(('name','=', st_line.name))
args_move_line.append(('ref','=',st_line.ref))
args_move_line.append(('name', '=', st_line.name))
args_move_line.append(('ref', '=', st_line.ref))
if st_line.partner_id:
args_move_line.append(('partner_id','=',st_line.partner_id.id))
args_move_line.append(('account_id','=',st_line.account_id.id))
move_line_id = line_obj.search(cr, uid, args_move_line,context=context)
args_move_line.append(('partner_id', '=', st_line.partner_id.id))
args_move_line.append(('account_id', '=', st_line.account_id.id))
move_line_id = line_obj.search(cr, uid, args_move_line, context=context)
if move_line_id:
repeated_move_line_ids += move_line_id
journal_ids = data['form']['journal_id'][0][2]
if journal_ids == []:
journal_ids = journal_obj.search(cr, uid, [('type', 'in', ('sale','cash','purchase'))], context=context)
journal_ids = journal_obj.search(cr, uid, [('type', 'in', ('sale', 'cash', 'purchase'))], context=context)
args = [
('reconcile_id', '=', False),
('journal_id', 'in', journal_ids),
('account_id.reconcile', '=', True)]
if repeated_move_line_ids:
args.append(('id','not in',repeated_move_line_ids))
args.append(('id', 'not in', repeated_move_line_ids))
line_ids = line_obj.search(cr, uid, args,
#order='date DESC, id DESC', #doesn't work
context=context)
FORM.string = '''<?xml version="1.0"?>
<form string="Import Entries">
<field name="lines" colspan="4" height="300" width="800" nolabel="1"
@ -99,7 +99,7 @@ def _search_invoices(obj, cr, uid, data, context):
def _populate_statement(obj, cursor, user, data, context):
line_ids = data['form']['lines'][0][2]
line_date=data['form']['date']
line_date = data['form']['date']
if not line_ids:
return {}
@ -125,9 +125,9 @@ def _populate_statement(obj, cursor, user, data, context):
statement.currency.id, line.amount_currency, context=ctx)
else:
if line.debit > 0:
amount=line.debit
amount = line.debit
elif line.credit > 0:
amount=-line.credit
amount = -line.credit
reconcile_id = statement_reconcile_obj.create(cursor, user, {
'line_ids': [(6, 0, [line.id])]
}, context=context)
@ -137,7 +137,7 @@ def _populate_statement(obj, cursor, user, data, context):
type = 'supplier'
else:
type = 'general'
statement_line_obj.create(cursor, user, {
'name': line.name or '?',
'amount': amount,
@ -150,8 +150,8 @@ def _populate_statement(obj, cursor, user, data, context):
'date':line_date, #time.strftime('%Y-%m-%d'), #line.date_maturity or,
}, context=context)
return {}
class PopulateStatementFromInv(wizard.interface):
"""
Populate the current statement with selected invoices
@ -176,8 +176,8 @@ class PopulateStatementFromInv(wizard.interface):
'arch': FORM,
'fields': FIELDS,
'state': [
('end', '_Cancel','', True),
('finish', 'O_k','', True)
('end', '_Cancel', '', True),
('finish', 'O_k', '', True)
]
},
},

View File

@ -34,7 +34,7 @@ _subscription_form = '''<?xml version="1.0"?>
</form>''' % ('Subscription Compute',)
_subscription_fields = {
'date': {'string':'Date', 'type':'date', 'default':lambda *a: time.strftime('%Y-%m-%d'), 'required':True},
'date': {'string':'Date', 'type':'date', 'default':lambda * a: time.strftime('%Y-%m-%d'), 'required':True},
}
class wiz_subscription(wizard.interface):
@ -47,7 +47,7 @@ class wiz_subscription(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type': 'form', 'arch':_subscription_form, 'fields':_subscription_fields, 'state':[('end','Cancel'),('generate','Compute Entry Dates')]}
'result': {'type': 'form', 'arch':_subscription_form, 'fields':_subscription_fields, 'state':[('end', 'Cancel'), ('generate', 'Compute Entry Dates')]}
},
'generate': {
'actions': [_action_generate],

View File

@ -60,26 +60,26 @@ period_fields = {
'state':{
'string':"Date/Period Filter",
'type':'selection',
'selection':[('bydate','By Date'),('byperiod','By Period'),('all','By Date and Period'),('none','No Filter')],
'default': lambda *a:'none'
'selection':[('bydate', 'By Date'), ('byperiod', 'By Period'), ('all', 'By Date and Period'), ('none', 'No Filter')],
'default': lambda * a:'none'
},
'fiscalyear': {
'string':'Fiscal year', 'type': 'many2one', 'relation': 'account.fiscalyear',
'help': 'Keep empty for all open fiscal year',
'default': lambda *a:False,
'default': lambda * a:False,
},
'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty','states':{'none':[('readonly',True)],'bydate':[('readonly',True)]}},
'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty', 'states':{'none':[('readonly', True)], 'bydate':[('readonly', True)]}},
'result_selection':{
'string':"Partner",
'type':'selection',
'selection':[('customer','Receivable Accounts'),('supplier','Payable Accounts'),('all','Receivable and Payable Accounts')],
'selection':[('customer', 'Receivable Accounts'), ('supplier', 'Payable Accounts'), ('all', 'Receivable and Payable Accounts')],
'required':True
},
'soldeinit':{'string':"Include initial balances",'type':'boolean'},
'reconcil':{'string':" Include Reconciled Entries",'type':'boolean'},
'page_split':{'string':"One Partner Per Page",'type':'boolean'},
'date1': {'string':' Start date', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')},
'date2': {'string':'End date', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')},
'soldeinit':{'string':"Include initial balances", 'type':'boolean'},
'reconcil':{'string':" Include Reconciled Entries", 'type':'boolean'},
'page_split':{'string':"One Partner Per Page", 'type':'boolean'},
'date1': {'string':' Start date', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-01-01')},
'date2': {'string':'End date', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')},
}
@ -88,7 +88,7 @@ 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']['display_account']='bal_all'
data['form']['display_account'] = 'bal_all'
data['form']['result_selection'] = 'all'
user = pooler.get_pool(cr.dbname).get('res.users').browse(cr, uid, uid, context=context)
if user.company_id:
@ -96,9 +96,9 @@ class wizard_report(wizard.interface):
else:
company_id = pooler.get_pool(cr.dbname).get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
data['form']['company_id'] = company_id
periods_obj=pooler.get_pool(cr.dbname).get('account.period')
data['form']['periods'] =periods_obj.search(cr, uid, [('fiscalyear_id','=',data['form']['fiscalyear'])])
data['form']['fiscalyear'] =False
periods_obj = pooler.get_pool(cr.dbname).get('account.period')
data['form']['periods'] = periods_obj.search(cr, uid, [('fiscalyear_id', '=', data['form']['fiscalyear'])])
data['form']['fiscalyear'] = False
data['form']['page_split'] = False
data['form']['reconcil'] = False
data['form']['soldeinit'] = True
@ -114,15 +114,15 @@ class wizard_report(wizard.interface):
sql = """
SELECT f.id, f.date_start, f.date_stop FROM account_fiscalyear f Where %s between f.date_start and f.date_stop """
cr.execute(sql,(data['form']['date1']))
cr.execute(sql, (data['form']['date1']))
res = cr.dictfetchall()
if res:
if (data['form']['date2'] > res[0]['date_stop'] or data['form']['date2'] < res[0]['date_start']):
raise wizard.except_wizard(_('UserError'),_('Date to must be set between %s and %s') % (str(res[0]['date_start']) , str(res[0]['date_stop'])))
raise wizard.except_wizard(_('UserError'), _('Date to must be set between %s and %s') % (str(res[0]['date_start']) , str(res[0]['date_stop'])))
else:
return 'report'
else:
raise wizard.except_wizard(_('UserError'),_('Date not in a defined fiscal year'))
raise wizard.except_wizard(_('UserError'), _('Date not in a defined fiscal year'))
def _check_state(self, cr, uid, data, context):
if data['form']['state'] == 'bydate' or data['form']['state'] == 'all':
@ -130,7 +130,7 @@ class wizard_report(wizard.interface):
else :
data['form']['fiscalyear'] = True
self._check_date(cr, uid, data, context)
acc_id = pooler.get_pool(cr.dbname).get('account.invoice').search(cr, uid, [('state','=','open')])
acc_id = pooler.get_pool(cr.dbname).get('account.invoice').search(cr, uid, [('state', '=', 'open')])
if not acc_id:
raise wizard.except_wizard(_('No Data Available'), _('No records found for your selection!'))
return data['form']
@ -139,11 +139,11 @@ class wizard_report(wizard.interface):
states = {
'init': {
'actions': [_get_defaults],
'result': {'type':'form', 'arch':period_form, 'fields':period_fields, 'state':[('end','Cancel','gtk-cancel'),('checkreport','Print','gtk-print')]}
'result': {'type':'form', 'arch':period_form, 'fields':period_fields, 'state':[('end', 'Cancel', 'gtk-cancel'), ('checkreport', 'Print', 'gtk-print')]}
},
'checkreport': {
'actions': [],
'result': {'type':'choice','next_state':_check}
'result': {'type':'choice', 'next_state':_check}
},
'report': {
'actions': [_check_state],

View File

@ -31,7 +31,7 @@ _info_form = '''<?xml version="1.0"?>
def _trans_unrec(self, cr, uid, data, context):
pool = pooler.get_pool(cr.dbname)
recs = pool.get('account.move.line').read(cr, uid, data['ids'], ['reconcile_id',])
recs = pool.get('account.move.line').read(cr, uid, data['ids'], ['reconcile_id', ])
recs = filter(lambda x: x['reconcile_id'], recs)
rec_ids = [rec['reconcile_id'][0] for rec in recs]
if len(rec_ids):

View File

@ -45,7 +45,7 @@ class wiz_unrec_select(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end','Cancel'),('open','Open for unreconciliation')]}
'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end', 'Cancel'), ('open', 'Open for unreconciliation')]}
},
'open': {
'actions': [],

View File

@ -43,15 +43,15 @@ fields = {
}
def _create_entries(self, cr, uid, data, context):
pool_obj = pooler.get_pool(cr.dbname)
if data['model']=='ir.ui.menu' or data['model']=='account.move.line':
if data['model'] == 'ir.ui.menu' or data['model'] == 'account.move.line':
model_ids = data['form']['model'][0][2]
data_model = pool_obj.get('account.model').browse(cr,uid,model_ids)
data_model = pool_obj.get('account.model').browse(cr, uid, model_ids)
else:
data_model = pool_obj.get('account.model').browse(cr,uid,data['ids'])
data_model = pool_obj.get('account.model').browse(cr, uid, data['ids'])
move_ids = []
for model in data_model:
period_id = pool_obj.get('account.period').find(cr,uid, context=context)
period_id = pool_obj.get('account.period').find(cr, uid, context=context)
if not period_id:
raise wizard.except_wizard(_('No period found !'), _('Unable to find a valid period !'))
period_id = period_id[0]
@ -80,44 +80,44 @@ def _create_entries(self, cr, uid, data, context):
'date_maturity': time.strftime('%Y-%m-%d')
})
c = context.copy()
c.update({'journal_id': model.journal_id.id,'period_id': period_id})
c.update({'journal_id': model.journal_id.id, 'period_id': period_id})
id_line = pool_obj.get('account.move.line').create(cr, uid, val, context=c)
data['form']['move_ids']=move_ids
data['form']['move_ids'] = move_ids
return data['form']
class use_model(wizard.interface):
def _open_moves(self, cr, uid, data, context):
pool_obj = pooler.get_pool(cr.dbname)
model_data_ids = pool_obj.get('ir.model.data').search(cr,uid,[('model','=','ir.ui.view'),('name','=','view_move_form')])
resource_id = pool_obj.get('ir.model.data').read(cr,uid,model_data_ids,fields=['res_id'])[0]['res_id']
model_data_ids = pool_obj.get('ir.model.data').search(cr, uid, [('model', '=', 'ir.ui.view'), ('name', '=', 'view_move_form')])
resource_id = pool_obj.get('ir.model.data').read(cr, uid, model_data_ids, fields=['res_id'])[0]['res_id']
return {
'domain': "[('id','in', ["+','.join(map(str,data['form']['move_ids']))+"])]",
'domain': "[('id','in', [" + ','.join(map(str, data['form']['move_ids'])) + "])]",
'name': 'Entries',
'view_type': 'form',
'view_mode': 'tree,form',
'res_model': 'account.move',
'views': [(False,'tree'),(resource_id,'form')],
'views': [(False, 'tree'), (resource_id, 'form')],
'type': 'ir.actions.act_window'
}
def _check(self, cr, uid, data, context):
if data['model']=='ir.ui.menu' or data['model']=='account.move.line':
if data['model'] == 'ir.ui.menu' or data['model'] == 'account.move.line':
return 'init_form'
return 'create'
states = {
'init': {
'actions': [],
'result': {'type':'choice','next_state':_check}
'result': {'type':'choice', 'next_state':_check}
},
'init_form': {
'actions': [],
'result': {'type':'form', 'arch':model_form, 'fields':model_fields, 'state':[('end','Cancel'),('create','Create Entries')]},
'result': {'type':'form', 'arch':model_form, 'fields':model_fields, 'state':[('end', 'Cancel'), ('create', 'Create Entries')]},
},
'create': {
'actions': [_create_entries],
'result': {'type': 'form','arch':form, 'fields':fields, 'state':[('end','Ok'),('open_move','Open')]},
'result': {'type': 'form', 'arch':form, 'fields':fields, 'state':[('end', 'Ok'), ('open_move', 'Open')]},
},
'open_move': {
'actions': [],

View File

@ -42,7 +42,7 @@ _journal_fields = {
def _validate_move(self, cr, uid, data, context={}):
pool = pooler.get_pool(cr.dbname)
move_obj = pool.get('account.move')
ids_move = move_obj.search(cr,uid,[('state','=','draft'),('journal_id','=',data['form']['journal_id']),('period_id','=',data['form']['period_id'])])
ids_move = move_obj.search(cr, uid, [('state', '=', 'draft'), ('journal_id', '=', data['form']['journal_id']), ('period_id', '=', data['form']['period_id'])])
if not ids_move:
raise wizard.except_wizard(_('Warning'), _('Specified Journal does not have any account move entries in draft state for this period'))
res = move_obj.button_validate(cr, uid, ids_move, context)
@ -52,7 +52,7 @@ class validate_account_move(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end','Cancel'),('validate','Validate')]}
'result': {'type': 'form', 'arch':_journal_form, 'fields':_journal_fields, 'state':[('end', 'Cancel'), ('validate', 'Validate')]}
},
'validate': {
'actions': [_validate_move],
@ -66,9 +66,9 @@ def _validate_move_lines(self, cr, uid, data, context={}):
pool = pooler.get_pool(cr.dbname)
move_line_obj = pool.get('account.move.line')
move_obj = pool.get('account.move')
data_line = move_line_obj.browse(cr,uid,data['ids'],context)
data_line = move_line_obj.browse(cr, uid, data['ids'], context)
for line in data_line:
if line.move_id.state=='draft':
if line.move_id.state == 'draft':
move_ids.append(line.move_id.id)
move_ids = list(set(move_ids))
if not move_ids:

View File

@ -37,9 +37,9 @@ dates_fields = {
'company_id': {'string': 'Company', 'type': 'many2one',
'relation': 'res.company', 'required': True},
'based_on':{'string':'Base on', 'type':'selection', 'selection':[
('invoices','Invoices'),
('payments','Payments'),
], 'required':True, 'default': lambda *a: 'invoices'},
('invoices', 'Invoices'),
('payments', 'Payments'),
], 'required':True, 'default': lambda * a: 'invoices'},
'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty'},
}

View File

@ -32,7 +32,7 @@ Add menu to show relevant information for each manager.""",
"category" : "Generic Modules/Accounting",
"module": "",
"website": "http://www.camptocamp.com/",
"depends" : ["account","hr_timesheet","hr_timesheet_invoice","project"],
"depends" : ["account", "hr_timesheet", "hr_timesheet_invoice", "project"],
"init_xml" : [],
"update_xml" : [
"security/ir.model.access.csv",

View File

@ -41,10 +41,10 @@ class account_analytic_account(osv.osv):
on account_analytic_line.journal_id = account_analytic_journal.id \
where account_analytic_line.account_id =ANY(%s) \
and account_analytic_journal.type = 'sale' \
group by account_analytic_line.account_id" ,(ids2,))
group by account_analytic_line.account_id" , (ids2,))
for account_id, sum in cr.fetchall():
res[account_id] = round(sum,2)
res[account_id] = round(sum, 2)
return self._compute_currency_for_level_tree(cr, uid, ids, ids2, res, acc_set, context)
def _ca_to_invoice_calc(self, cr, uid, ids, name, arg, context={}):
@ -77,9 +77,9 @@ class account_analytic_account(osv.osv):
AND account_analytic_line.invoice_id is null \
AND account_analytic_line.to_invoice IS NOT NULL \
and account_analytic_journal.type in ('purchase','general') \
GROUP BY account_analytic_account.id;""",(ids2,))
GROUP BY account_analytic_account.id;""", (ids2,))
for account_id, sum in cr.fetchall():
res[account_id] = round(sum,2)
res[account_id] = round(sum, 2)
for obj_id in ids:
res.setdefault(obj_id, 0.0)
@ -91,7 +91,7 @@ class account_analytic_account(osv.osv):
res2[obj_id] += res2.get(child_id, 0.0)
# sum both result on account_id
for id in ids:
res[id] = round(res.get(id, 0.0),2) + round(res2.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2) + round(res2.get(id, 0.0), 2)
return res
def _hours_qtt_non_invoiced_calc (self, cr, uid, ids, name, arg, context={}):
@ -106,9 +106,9 @@ class account_analytic_account(osv.osv):
and account_analytic_journal.type='general' \
and invoice_id is null \
AND to_invoice IS NOT NULL \
GROUP BY account_analytic_line.account_id;",(ids2,))
GROUP BY account_analytic_line.account_id;", (ids2,))
for account_id, sum in cr.fetchall():
res[account_id] = round(sum,2)
res[account_id] = round(sum, 2)
for obj_id in ids:
res.setdefault(obj_id, 0.0)
for child_id in self.search(cr, uid,
@ -116,7 +116,7 @@ class account_analytic_account(osv.osv):
if child_id != obj_id:
res[obj_id] += res.get(child_id, 0.0)
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _hours_quantity_calc(self, cr, uid, ids, name, arg, context={}):
@ -129,10 +129,10 @@ class account_analytic_account(osv.osv):
on account_analytic_line.journal_id = account_analytic_journal.id \
where account_analytic_line.account_id =ANY(%s) \
and account_analytic_journal.type='general' \
GROUP BY account_analytic_line.account_id",(ids2,))
ff = cr.fetchall()
GROUP BY account_analytic_line.account_id", (ids2,))
ff = cr.fetchall()
for account_id, sum in ff:
res[account_id] = round(sum,2)
res[account_id] = round(sum, 2)
for obj_id in ids:
res.setdefault(obj_id, 0.0)
for child_id in self.search(cr, uid,
@ -140,7 +140,7 @@ class account_analytic_account(osv.osv):
if child_id != obj_id:
res[obj_id] += res.get(child_id, 0.0)
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _total_cost_calc(self, cr, uid, ids, name, arg, context={}):
@ -155,11 +155,11 @@ class account_analytic_account(osv.osv):
on account_analytic_line.journal_id = account_analytic_journal.id \
where account_analytic_line.account_id =ANY(%s) \
and amount<0 \
GROUP BY account_analytic_line.account_id""",(ids2,))
GROUP BY account_analytic_line.account_id""", (ids2,))
for account_id, sum in cr.fetchall():
res[account_id] = round(sum,2)
res[account_id] = round(sum, 2)
return self._compute_currency_for_level_tree(cr, uid, ids, ids2, res, acc_set, context)
# TODO Take care of pricelist and purchase !
def _ca_theorical_calc(self, cr, uid, ids, name, arg, context={}):
res = {}
@ -187,10 +187,10 @@ class account_analytic_account(osv.osv):
where account_analytic_line.account_id =ANY(%s) \
and a.to_invoice IS NOT NULL \
and account_analytic_journal.type in ('purchase','general')
GROUP BY account_analytic_line.account_id""",(ids2,))
GROUP BY account_analytic_line.account_id""", (ids2,))
for account_id, sum in cr.fetchall():
res2[account_id] = round(sum,2)
res2[account_id] = round(sum, 2)
for obj_id in ids:
res.setdefault(obj_id, 0.0)
res2.setdefault(obj_id, 0.0)
@ -199,10 +199,10 @@ class account_analytic_account(osv.osv):
if child_id != obj_id:
res[obj_id] += res.get(child_id, 0.0)
res[obj_id] += res2.get(child_id, 0.0)
# sum both result on account_id
for id in ids:
res[id] = round(res.get(id, 0.0),2) + round(res2.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2) + round(res2.get(id, 0.0), 2)
return res
def _last_worked_date_calc (self, cr, uid, ids, name, arg, context={}):
@ -213,7 +213,7 @@ class account_analytic_account(osv.osv):
from account_analytic_line \
where account_id =ANY(%s) \
and invoice_id is null \
GROUP BY account_analytic_line.account_id" ,(ids2,))
GROUP BY account_analytic_line.account_id" , (ids2,))
for account_id, sum in cr.fetchall():
res[account_id] = sum
for obj_id in ids:
@ -237,7 +237,7 @@ class account_analytic_account(osv.osv):
on account_analytic_line.invoice_id = account_invoice.id \
where account_analytic_line.account_id =ANY(%s) \
and account_analytic_line.invoice_id is not null \
GROUP BY account_analytic_line.account_id",(ids2,))
GROUP BY account_analytic_line.account_id", (ids2,))
for account_id, sum in cr.fetchall():
res[account_id] = sum
for obj_id in ids:
@ -258,7 +258,7 @@ class account_analytic_account(osv.osv):
from account_analytic_line \
where account_id =ANY(%s) \
and invoice_id is not null \
GROUP BY account_analytic_line.account_id;",(ids2,))
GROUP BY account_analytic_line.account_id;", (ids2,))
for account_id, sum in cr.fetchall():
res[account_id] = sum
for obj_id in ids:
@ -277,9 +277,9 @@ class account_analytic_account(osv.osv):
if account.quantity_max != 0:
res[account.id] = account.quantity_max - account.hours_quantity
else:
res[account.id]=0.0
res[account.id] = 0.0
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _hours_qtt_invoiced_calc(self, cr, uid, ids, name, arg, context={}):
@ -287,33 +287,33 @@ class account_analytic_account(osv.osv):
for account in self.browse(cr, uid, ids):
res[account.id] = account.hours_quantity - account.hours_qtt_non_invoiced
if res[account.id] < 0:
res[account.id]=0.0
res[account.id] = 0.0
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _revenue_per_hour_calc(self, cr, uid, ids, name, arg, context={}):
res = {}
for account in self.browse(cr, uid, ids):
if account.hours_qtt_invoiced == 0:
res[account.id]=0.0
res[account.id] = 0.0
else:
res[account.id] = account.ca_invoiced / account.hours_qtt_invoiced
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _real_margin_rate_calc(self, cr, uid, ids, name, arg, context={}):
res = {}
for account in self.browse(cr, uid, ids):
if account.ca_invoiced == 0:
res[account.id]=0.0
res[account.id] = 0.0
elif account.total_cost != 0.0:
res[account.id] = -(account.real_margin / account.total_cost) * 100
else:
res[account.id] = 0.0
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _remaining_ca_calc(self, cr, uid, ids, name, arg, context={}):
@ -322,9 +322,9 @@ class account_analytic_account(osv.osv):
if account.amount_max != 0:
res[account.id] = account.amount_max - account.ca_invoiced
else:
res[account.id]=0.0
res[account.id] = 0.0
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _real_margin_calc(self, cr, uid, ids, name, arg, context={}):
@ -332,7 +332,7 @@ class account_analytic_account(osv.osv):
for account in self.browse(cr, uid, ids):
res[account.id] = account.ca_invoiced + account.total_cost
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _theorical_margin_calc(self, cr, uid, ids, name, arg, context={}):
@ -340,7 +340,7 @@ class account_analytic_account(osv.osv):
for account in self.browse(cr, uid, ids):
res[account.id] = account.ca_theorical + account.total_cost
for id in ids:
res[id] = round(res.get(id, 0.0),2)
res[id] = round(res.get(id, 0.0), 2)
return res
def _month(self, cr, uid, ids, name, arg, context=None):
@ -349,7 +349,7 @@ class account_analytic_account(osv.osv):
ids2 = self.search(cr, uid, [('parent_id', 'child_of', [id])])
if ids2:
cr.execute('SELECT DISTINCT(month_id) FROM account_analytic_analysis_summary_month ' \
'WHERE account_id =ANY(%s) AND unit_amount <> 0.0',(ids2,))
'WHERE account_id =ANY(%s) AND unit_amount <> 0.0', (ids2,))
res[id] = [int(id * 1000000 + int(x[0])) for x in cr.fetchall()]
else:
res[id] = []
@ -363,13 +363,13 @@ class account_analytic_account(osv.osv):
ids2 = self.search(cr, uid, [('parent_id', 'child_of', [id])])
if ids2:
cr.execute('SELECT DISTINCT("user") FROM account_analytic_analysis_summary_user ' \
'WHERE account_id =ANY(%s) AND unit_amount <> 0.0',(ids2,))
'WHERE account_id =ANY(%s) AND unit_amount <> 0.0', (ids2,))
res[id] = [int((id * max_user) + x[0]) for x in cr.fetchall()]
else:
res[id] = []
return res
_columns ={
_columns = {
'ca_invoiced': fields.function(_ca_invoiced_calc, method=True, type='float', string='Invoiced Amount', help="Total customer invoiced amount for this account."),
'total_cost': fields.function(_total_cost_calc, method=True, type='float', string='Total Costs', help="Total of costs for this account. It includes real costs (from invoices) and indirect costs, like time spent on timesheets."),
'ca_to_invoice': fields.function(_ca_to_invoice_calc, method=True, type='float', string='Uninvoiced Amount', help="If invoice from analytic account, the remaining amount you can invoice to the customer based on the total costs."),
@ -394,7 +394,7 @@ account_analytic_account()
class account_analytic_account_summary_user(osv.osv):
_name = "account_analytic_analysis.summary.user"
_description = "Hours summary by user"
_order='user'
_order = 'user'
_auto = False
_rec_name = 'user'
@ -403,22 +403,22 @@ class account_analytic_account_summary_user(osv.osv):
account_obj = self.pool.get('account.analytic.account')
cr.execute('SELECT MAX(id) FROM res_users')
max_user = cr.fetchone()[0]
account_ids = [int(str(x/max_user - (x%max_user == 0 and 1 or 0))) for x in ids]
user_ids = [int(str(x-((x/max_user - (x%max_user == 0 and 1 or 0)) *max_user))) for x in ids]
account_ids = [int(str(x / max_user - (x % max_user == 0 and 1 or 0))) for x in ids]
user_ids = [int(str(x - ((x / max_user - (x % max_user == 0 and 1 or 0)) * max_user))) for x in ids]
account_ids2 = account_obj.search(cr, uid, [('parent_id', 'child_of', account_ids)])
if account_ids2:
cr.execute('SELECT id, unit_amount ' \
'FROM account_analytic_analysis_summary_user ' \
'WHERE account_id =ANY(%s) ' \
'AND "user" =ANY(%s)',(account_ids2, user_ids,))
'AND "user" =ANY(%s)', (account_ids2, user_ids,))
for sum_id, unit_amount in cr.fetchall():
res[sum_id] = unit_amount
for obj_id in ids:
res.setdefault(obj_id, 0.0)
for child_id in account_obj.search(cr, uid,
[('parent_id', 'child_of', [int(str(obj_id/max_user - (obj_id%max_user == 0 and 1 or 0)))])]):
if child_id != int(str(obj_id/max_user - (obj_id%max_user == 0 and 1 or 0))):
res[obj_id] += res.get((child_id * max_user) + obj_id -((obj_id/max_user - (obj_id%max_user == 0 and 1 or 0)) * max_user), 0.0)
[('parent_id', 'child_of', [int(str(obj_id / max_user - (obj_id % max_user == 0 and 1 or 0)))])]):
if child_id != int(str(obj_id / max_user - (obj_id % max_user == 0 and 1 or 0))):
res[obj_id] += res.get((child_id * max_user) + obj_id - ((obj_id / max_user - (obj_id % max_user == 0 and 1 or 0)) * max_user), 0.0)
for id in ids:
res[id] = round(res.get(id, 0.0), 2)
return res
@ -467,35 +467,35 @@ class account_analytic_account_summary_user(osv.osv):
def _read_flat(self, cr, user, ids, fields, context=None, load='_classic_read'):
if not context:
context={}
context = {}
if not ids:
return []
if fields==None:
if fields == None:
fields = self._columns.keys()
# construct a clause for the rules :
d1, d2 = self.pool.get('ir.rule').domain_get(cr, user, self._name)
# all inherited fields + all non inherited fields for which the attribute whose name is in load is True
fields_pre = filter(lambda x: x in self._columns and getattr(self._columns[x],'_classic_write'), fields) + self._inherits.values()
fields_pre = filter(lambda x: x in self._columns and getattr(self._columns[x], '_classic_write'), fields) + self._inherits.values()
res = []
cr.execute('SELECT MAX(id) FROM res_users')
max_user = cr.fetchone()[0]
if len(fields_pre) :
fields_pre2 = map(lambda x: (x in ('create_date', 'write_date')) and ('date_trunc(\'second\', '+x+') as '+x) or '"'+x+'"', fields_pre)
fields_pre2 = map(lambda x: (x in ('create_date', 'write_date')) and ('date_trunc(\'second\', ' + x + ') as ' + x) or '"' + x + '"', fields_pre)
for i in range(0, len(ids), cr.IN_MAX):
sub_ids = ids[i:i+cr.IN_MAX]
sub_ids = ids[i:i + cr.IN_MAX]
if d1:
cr.execute('select %s from \"%s\" where id in (%s) ' \
'and account_id in (%s) ' \
'and "user" in (%s) and %s order by %s' % \
(','.join(fields_pre2 + ['id']), self._table,
','.join([str(x) for x in sub_ids]),
','.join([str(x/max_user - (x%max_user == 0 and 1 or 0)) for x in sub_ids]),
','.join([str(x-((x/max_user - (x%max_user == 0 and 1 or 0)) *max_user)) for x in sub_ids]), d1,
self._order),d2)
','.join([str(x / max_user - (x % max_user == 0 and 1 or 0)) for x in sub_ids]),
','.join([str(x - ((x / max_user - (x % max_user == 0 and 1 or 0)) * max_user)) for x in sub_ids]), d1,
self._order), d2)
if not cr.rowcount == len({}.fromkeys(sub_ids)):
raise except_orm(_('AccessError'),
_('You try to bypass an access rule (Document type: %s).') % self._description)
@ -505,8 +505,8 @@ class account_analytic_account_summary_user(osv.osv):
'and "user" in (%s) order by %s' % \
(','.join(fields_pre2 + ['id']), self._table,
','.join([str(x) for x in sub_ids]),
','.join([str(x/max_user - (x%max_user == 0 and 1 or 0)) for x in sub_ids]),
','.join([str(x-((x/max_user - (x%max_user == 0 and 1 or 0)) *max_user)) for x in sub_ids]),
','.join([str(x / max_user - (x % max_user == 0 and 1 or 0)) for x in sub_ids]),
','.join([str(x - ((x / max_user - (x % max_user == 0 and 1 or 0)) * max_user)) for x in sub_ids]),
self._order))
res.extend(cr.dictfetchall())
else:
@ -515,7 +515,7 @@ class account_analytic_account_summary_user(osv.osv):
for f in fields_pre:
if self._columns[f].translate:
ids = map(lambda x: x['id'], res)
res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context.get('lang', False) or 'en_US', ids)
res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name + ',' + f, 'model', context.get('lang', False) or 'en_US', ids)
for r in res:
r[f] = res_trans.get(r['id'], False) or r[f]
@ -575,7 +575,7 @@ class account_analytic_account_summary_month(osv.osv):
cr.execute('SELECT id, unit_amount ' \
'FROM account_analytic_analysis_summary_month ' \
'WHERE account_id =ANY(%s) ' \
'AND month_id =ANY(%s) ',(account_ids2, month_ids,))
'AND month_id =ANY(%s) ', (account_ids2, month_ids,))
for sum_id, unit_amount in cr.fetchall():
res[sum_id] = unit_amount
for obj_id in ids:
@ -645,24 +645,24 @@ class account_analytic_account_summary_month(osv.osv):
def _read_flat(self, cr, user, ids, fields, context=None, load='_classic_read'):
if not context:
context={}
context = {}
if not ids:
return []
if fields==None:
if fields == None:
fields = self._columns.keys()
# construct a clause for the rules :
d1, d2 = self.pool.get('ir.rule').domain_get(cr, user, self._name)
# all inherited fields + all non inherited fields for which the attribute whose name is in load is True
fields_pre = filter(lambda x: x in self._columns and getattr(self._columns[x],'_classic_write'), fields) + self._inherits.values()
fields_pre = filter(lambda x: x in self._columns and getattr(self._columns[x], '_classic_write'), fields) + self._inherits.values()
res = []
if len(fields_pre) :
fields_pre2 = map(lambda x: (x in ('create_date', 'write_date')) and ('date_trunc(\'second\', '+x+') as '+x) or '"'+x+'"', fields_pre)
fields_pre2 = map(lambda x: (x in ('create_date', 'write_date')) and ('date_trunc(\'second\', ' + x + ') as ' + x) or '"' + x + '"', fields_pre)
for i in range(0, len(ids), cr.IN_MAX):
sub_ids = ids[i:i+cr.IN_MAX]
sub_ids = ids[i:i + cr.IN_MAX]
if d1:
cr.execute('select %s from \"%s\" where id in (%s) ' \
'and account_id in (%s) ' \
@ -671,7 +671,7 @@ class account_analytic_account_summary_month(osv.osv):
','.join([str(x) for x in sub_ids]),
','.join([str(x)[:-6] for x in sub_ids]),
','.join([str(x)[-6:] for x in sub_ids]), d1,
self._order),d2)
self._order), d2)
if not cr.rowcount == len({}.fromkeys(sub_ids)):
raise except_orm(_('AccessError'),
_('You try to bypass an access rule (Document type: %s).') % self._description)
@ -691,7 +691,7 @@ class account_analytic_account_summary_month(osv.osv):
for f in fields_pre:
if self._columns[f].translate:
ids = map(lambda x: x['id'], res)
res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context.get('lang', False) or 'en_US', ids)
res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name + ',' + f, 'model', context.get('lang', False) or 'en_US', ids)
for r in res:
r[f] = res_trans.get(r['id'], False) or r[f]

View File

@ -19,7 +19,7 @@
#
##############################################################################
from osv import fields,osv
from osv import fields, osv
from osv import orm
import time
@ -41,27 +41,27 @@ class account_analytic_default(osv.osv):
def account_get(self, cr, uid, product_id=None, partner_id=None, user_id=None, date=None, context={}):
domain = []
if product_id:
domain += ['|',('product_id','=',product_id)]
domain += [('product_id','=',False)]
domain += ['|', ('product_id', '=', product_id)]
domain += [('product_id', '=', False)]
if partner_id:
domain += ['|',('partner_id','=',partner_id)]
domain += [('partner_id','=',False)]
domain += ['|', ('partner_id', '=', partner_id)]
domain += [('partner_id', '=', False)]
if user_id:
domain += ['|',('user_id','=',uid)]
domain += [('user_id','=',False)]
domain += ['|', ('user_id', '=', uid)]
domain += [('user_id', '=', False)]
if date:
domain += ['|',('date_start','<=',date),('date_start','=',False)]
domain += ['|',('date_stop','>=',date),('date_stop','=',False)]
domain += ['|', ('date_start', '<=', date), ('date_start', '=', False)]
domain += ['|', ('date_stop', '>=', date), ('date_stop', '=', False)]
best_index = -1
res = False
for rec in self.browse(cr, uid, self.search(cr, uid, domain, context=context), context=context):
index = 0
if rec.product_id: index+=1
if rec.partner_id: index+=1
if rec.user_id: index+=1
if rec.date_start: index+=1
if rec.date_stop: index+=1
if index>best_index:
if rec.product_id: index += 1
if rec.partner_id: index += 1
if rec.user_id: index += 1
if rec.date_start: index += 1
if rec.date_stop: index += 1
if index > best_index:
res = rec
best_index = index
return res
@ -70,51 +70,51 @@ account_analytic_default()
class account_invoice_line(osv.osv):
_inherit = 'account.invoice.line'
_description = 'account invoice line'
def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition=False, price_unit=False, address_invoice_id=False, context={}):
res_prod = super(account_invoice_line,self).product_id_change(cr, uid, ids, product, uom, qty, name, type, partner_id, fposition, price_unit, address_invoice_id, context)
res_prod = super(account_invoice_line, self).product_id_change(cr, uid, ids, product, uom, qty, name, type, partner_id, fposition, price_unit, address_invoice_id, context)
rec = self.pool.get('account.analytic.default').account_get(cr, uid, product, partner_id, uid, time.strftime('%Y-%m-%d'), context)
if rec:
res_prod['value'].update({'account_analytic_id':rec.analytic_id.id})
else:
res_prod['value'].update({'account_analytic_id':False})
res_prod['value'].update({'account_analytic_id':False})
return res_prod
account_invoice_line()
class stock_picking(osv.osv):
_inherit = "stock.picking"
def _get_account_analytic_invoice(self, cursor, user, picking, move_line):
partner_id = picking.address_id and picking.address_id.partner_id or False
rec = self.pool.get('account.analytic.default').account_get(cursor, user, move_line.product_id.id, partner_id and partner_id.id, user, time.strftime('%Y-%m-%d'), context={})
if rec:
return rec.analytic_id.id
return super(stock_picking, self)._get_account_analytic_invoice(cursor,
user, picking, move_line)
stock_picking()
class sale_order_line(osv.osv):
_inherit = 'sale.order.line'
# Method overridden to set the analytic account by default on criterion match
def invoice_line_create(self, cr, uid, ids, context={}):
create_ids = super(sale_order_line,self).invoice_line_create(cr, uid, ids, context)
create_ids = super(sale_order_line, self).invoice_line_create(cr, uid, ids, context)
sale_line_obj = self.browse(cr, uid, ids[0], context)
pool_inv_line = self.pool.get('account.invoice.line')
for line in pool_inv_line.browse(cr, uid, create_ids, context):
rec = self.pool.get('account.analytic.default').account_get(cr, uid, line.product_id.id, sale_line_obj.order_id.partner_id.id, uid, time.strftime('%Y-%m-%d'), context)
if rec:
pool_inv_line.write(cr, uid, [line.id], {'account_analytic_id':rec.analytic_id.id}, context=context)
return create_ids
sale_order_line()
sale_order_line()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -25,7 +25,7 @@ from mx.DateTime import now
import time
import netsvc
from osv import fields, osv,orm
from osv import fields, osv, orm
import ir
import tools
@ -41,15 +41,15 @@ class one2many_mod2(fields.one2many):
ids2 = None
if 'journal_id' in context:
journal = obj.pool.get('account.journal').browse(cr, user, context['journal_id'], context)
pnum = int(name[7]) -1
pnum = int(name[7]) - 1
plan = journal.plan_id
if plan and len(plan.plan_ids)>pnum:
if plan and len(plan.plan_ids) > pnum:
acc_id = plan.plan_ids[pnum].root_analytic_id.id
ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id,'in',ids),('analytic_account_id','child_of',[acc_id])], limit=self._limit)
ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids), ('analytic_account_id', 'child_of', [acc_id])], limit=self._limit)
if ids2 is None:
ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id,'in',ids)], limit=self._limit)
ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
res[r[self._fields_id]].append( r['id'] )
res[r[self._fields_id]].append(r['id'])
return res
class account_analytic_plan(osv.osv):
@ -57,7 +57,7 @@ class account_analytic_plan(osv.osv):
_description = "Analytic Plans"
_columns = {
'name': fields.char('Analytic Plan', size=64, required=True, select=True,),
'plan_ids': fields.one2many('account.analytic.plan.line','plan_id','Analytic Plans'),
'plan_ids': fields.one2many('account.analytic.plan.line', 'plan_id', 'Analytic Plans'),
}
account_analytic_plan()
@ -65,34 +65,34 @@ class account_analytic_plan_line(osv.osv):
_name = "account.analytic.plan.line"
_description = "Analytic Plan Lines"
_columns = {
'plan_id':fields.many2one('account.analytic.plan','Analytic Plan'),
'plan_id':fields.many2one('account.analytic.plan', 'Analytic Plan'),
'name': fields.char('Plan Name', size=64, required=True, select=True),
'sequence':fields.integer('Sequence'),
'root_analytic_id': fields.many2one('account.analytic.account','Root Account',help="Root account of this plan.",required=True),
'root_analytic_id': fields.many2one('account.analytic.account', 'Root Account', help="Root account of this plan.", required=True),
'min_required': fields.float('Minimum Allowed (%)'),
'max_required': fields.float('Maximum Allowed (%)'),
}
_defaults = {
'min_required': lambda *args: 100.0,
'max_required': lambda *args: 100.0,
'min_required': lambda * args: 100.0,
'max_required': lambda * args: 100.0,
}
_order = "sequence,id"
account_analytic_plan_line()
class account_analytic_plan_instance(osv.osv):
_name='account.analytic.plan.instance'
_name = 'account.analytic.plan.instance'
_description = 'Analytic Plan Instance'
_columns={
'name':fields.char('Analytic Distribution',size=64),
'code':fields.char('Distribution Code',size=16),
_columns = {
'name':fields.char('Analytic Distribution', size=64),
'code':fields.char('Distribution Code', size=16),
'journal_id': fields.many2one('account.analytic.journal', 'Analytic Journal', required=True),
'account_ids':fields.one2many('account.analytic.plan.instance.line','plan_id','Account Id'),
'account1_ids':one2many_mod2('account.analytic.plan.instance.line','plan_id','Account1 Id'),
'account2_ids':one2many_mod2('account.analytic.plan.instance.line','plan_id','Account2 Id'),
'account3_ids':one2many_mod2('account.analytic.plan.instance.line','plan_id','Account3 Id'),
'account4_ids':one2many_mod2('account.analytic.plan.instance.line','plan_id','Account4 Id'),
'account5_ids':one2many_mod2('account.analytic.plan.instance.line','plan_id','Account5 Id'),
'account6_ids':one2many_mod2('account.analytic.plan.instance.line','plan_id','Account6 Id'),
'account_ids':fields.one2many('account.analytic.plan.instance.line', 'plan_id', 'Account Id'),
'account1_ids':one2many_mod2('account.analytic.plan.instance.line', 'plan_id', 'Account1 Id'),
'account2_ids':one2many_mod2('account.analytic.plan.instance.line', 'plan_id', 'Account2 Id'),
'account3_ids':one2many_mod2('account.analytic.plan.instance.line', 'plan_id', 'Account3 Id'),
'account4_ids':one2many_mod2('account.analytic.plan.instance.line', 'plan_id', 'Account4 Id'),
'account5_ids':one2many_mod2('account.analytic.plan.instance.line', 'plan_id', 'Account5 Id'),
'account6_ids':one2many_mod2('account.analytic.plan.instance.line', 'plan_id', 'Account6 Id'),
'plan_id':fields.many2one('account.analytic.plan', "Model's Plan"),
}
def copy(self, cr, uid, id, default=None, context=None):
@ -110,7 +110,7 @@ class account_analytic_plan_instance(osv.osv):
return False
_defaults = {
'plan_id': lambda *args: False,
'plan_id': lambda * args: False,
'journal_id': _default_journal,
}
def name_get(self, cr, uid, ids, context={}):
@ -118,12 +118,12 @@ class account_analytic_plan_instance(osv.osv):
for inst in self.browse(cr, uid, ids, context):
name = inst.name or '/'
if name and inst.code:
name=name+' ('+inst.code+')'
name = name + ' (' + inst.code + ')'
res.append((inst.id, name))
return res
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
args= args or []
args = args or []
if name:
ids = self.search(cr, uid, [('code', '=', name)] + args, limit=limit, context=context or {})
if not ids:
@ -133,34 +133,34 @@ class account_analytic_plan_instance(osv.osv):
return self.name_get(cr, uid, ids, context or {})
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
wiz_id = self.pool.get('ir.actions.wizard').search(cr, uid, [("wiz_name","=","create.model")])
res = super(account_analytic_plan_instance,self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
wiz_id = self.pool.get('ir.actions.wizard').search(cr, uid, [("wiz_name", "=", "create.model")])
res = super(account_analytic_plan_instance, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
if (res['type']=='form'):
if (res['type'] == 'form'):
plan_id = False
if context.get('journal_id',False):
if context.get('journal_id', False):
plan_id = self.pool.get('account.journal').browse(cr, uid, int(context['journal_id']), context).plan_id
elif context.get('plan_id',False):
elif context.get('plan_id', False):
plan_id = self.pool.get('account.analytic.plan').browse(cr, uid, int(context['plan_id']), context)
if plan_id:
i=1
i = 1
res['arch'] = """<form string="%s">
<field name="name"/>
<field name="code"/>
<field name="journal_id"/>
<button name="%d" string="Save This Distribution as a Model" type="action" colspan="2"/>
"""% (tools.to_xml(plan_id.name), wiz_id[0])
""" % (tools.to_xml(plan_id.name), wiz_id[0])
for line in plan_id.plan_ids:
res['arch']+="""
res['arch'] += """
<field name="account%d_ids" string="%s" colspan="4">
<tree string="%s" editable="bottom">
<field name="rate"/>
<field name="analytic_account_id" domain="[('parent_id','child_of',[%d])]"/>
</tree>
</field>
<newline/>"""%(i,tools.to_xml(line.name),tools.to_xml(line.name),line.root_analytic_id and line.root_analytic_id.id or 0)
i+=1
<newline/>""" % (i, tools.to_xml(line.name), tools.to_xml(line.name), line.root_analytic_id and line.root_analytic_id.id or 0)
i += 1
res['arch'] += "</form>"
doc = etree.fromstring(res['arch'].encode('utf8'))
xarch, xfields = self._view_look_dom_arch(cr, uid, doc, view_id, context=context)
@ -172,54 +172,54 @@ class account_analytic_plan_instance(osv.osv):
def create(self, cr, uid, vals, context=None):
if context and 'journal_id' in context:
journal= self.pool.get('account.journal').browse(cr,uid,context['journal_id'])
journal = self.pool.get('account.journal').browse(cr, uid, context['journal_id'])
pids = self.pool.get('account.analytic.plan.instance').search(cr, uid, [('name','=',vals['name']),('code','=',vals['code']),('plan_id','<>',False)])
pids = self.pool.get('account.analytic.plan.instance').search(cr, uid, [('name', '=', vals['name']), ('code', '=', vals['code']), ('plan_id', '<>', False)])
if pids:
raise osv.except_osv(_('Error'), _('A model having this name and code already exists !'))
res = self.pool.get('account.analytic.plan.line').search(cr,uid,[('plan_id','=',journal.plan_id.id)])
res = self.pool.get('account.analytic.plan.line').search(cr, uid, [('plan_id', '=', journal.plan_id.id)])
for i in res:
total_per_plan = 0
item = self.pool.get('account.analytic.plan.line').browse(cr,uid,i)
temp_list=['account1_ids','account2_ids','account3_ids','account4_ids','account5_ids','account6_ids']
item = self.pool.get('account.analytic.plan.line').browse(cr, uid, i)
temp_list = ['account1_ids', 'account2_ids', 'account3_ids', 'account4_ids', 'account5_ids', 'account6_ids']
for l in temp_list:
if vals.has_key(l):
for tempo in vals[l]:
if self.pool.get('account.analytic.account').search(cr,uid,[('parent_id','child_of',[item.root_analytic_id.id]),('id','=',tempo[2]['analytic_account_id'])]):
if self.pool.get('account.analytic.account').search(cr, uid, [('parent_id', 'child_of', [item.root_analytic_id.id]), ('id', '=', tempo[2]['analytic_account_id'])]):
total_per_plan += tempo[2]['rate']
if total_per_plan < item.min_required or total_per_plan > item.max_required:
raise osv.except_osv(_('Value Error') ,_('The Total Should be Between %s and %s') % (str(item.min_required), str(item.max_required)))
raise osv.except_osv(_('Value Error') , _('The Total Should be Between %s and %s') % (str(item.min_required), str(item.max_required)))
return super(account_analytic_plan_instance, self).create(cr, uid, vals, context)
def write(self, cr, uid, ids, vals, context={}, check=True, update_check=True):
this = self.browse(cr,uid,ids[0])
this = self.browse(cr, uid, ids[0])
if this.plan_id and not vals.has_key('plan_id'):
#this instance is a model, so we have to create a new plan instance instead of modifying it
#copy the existing model
temp_id = self.copy(cr, uid, this.id, None, context)
#get the list of the invoice line that were linked to the model
list = self.pool.get('account.invoice.line').search(cr,uid,[('analytics_id','=',this.id)])
list = self.pool.get('account.invoice.line').search(cr, uid, [('analytics_id', '=', this.id)])
#make them link to the copy
self.pool.get('account.invoice.line').write(cr, uid, list, {'analytics_id':temp_id}, context)
#and finally modify the old model to be not a model anymore
vals['plan_id'] = False
if not vals.has_key('name'):
vals['name'] = this.name and (str(this.name)+'*') or "*"
vals['name'] = this.name and (str(this.name) + '*') or "*"
if not vals.has_key('code'):
vals['code'] = this.code and (str(this.code)+'*') or "*"
vals['code'] = this.code and (str(this.code) + '*') or "*"
return super(account_analytic_plan_instance, self).write(cr, uid, ids, vals, context)
account_analytic_plan_instance()
class account_analytic_plan_instance_line(osv.osv):
_name='account.analytic.plan.instance.line'
_name = 'account.analytic.plan.instance.line'
_description = 'Analytic Instance Line'
_columns={
'plan_id':fields.many2one('account.analytic.plan.instance','Plan Id'),
'analytic_account_id':fields.many2one('account.analytic.account','Analytic Account', required=True),
_columns = {
'plan_id':fields.many2one('account.analytic.plan.instance', 'Plan Id'),
'analytic_account_id':fields.many2one('account.analytic.account', 'Analytic Account', required=True),
'rate':fields.float('Rate (%)', required=True),
}
def name_get(self, cr, uid, ids, context={}):
@ -234,32 +234,32 @@ class account_analytic_plan_instance_line(osv.osv):
account_analytic_plan_instance_line()
class account_journal(osv.osv):
_inherit='account.journal'
_name='account.journal'
_inherit = 'account.journal'
_name = 'account.journal'
_columns = {
'plan_id':fields.many2one('account.analytic.plan','Analytic Plans'),
'plan_id':fields.many2one('account.analytic.plan', 'Analytic Plans'),
}
account_journal()
class account_invoice_line(osv.osv):
_inherit='account.invoice.line'
_name='account.invoice.line'
_inherit = 'account.invoice.line'
_name = 'account.invoice.line'
_columns = {
'analytics_id':fields.many2one('account.analytic.plan.instance','Analytic Distribution'),
'analytics_id':fields.many2one('account.analytic.plan.instance', 'Analytic Distribution'),
}
def create(self, cr, uid, vals, context=None):
if 'analytics_id' in vals and isinstance(vals['analytics_id'],tuple):
if 'analytics_id' in vals and isinstance(vals['analytics_id'], tuple):
vals['analytics_id'] = vals['analytics_id'][0]
return super(account_invoice_line, self).create(cr, uid, vals, context)
def move_line_get_item(self, cr, uid, line, context=None):
res= super(account_invoice_line,self).move_line_get_item(cr, uid, line, context={})
res ['analytics_id']=line.analytics_id and line.analytics_id.id or False
res = super(account_invoice_line, self).move_line_get_item(cr, uid, line, context={})
res ['analytics_id'] = line.analytics_id and line.analytics_id.id or False
return res
def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, address_invoice_id=False, context=None):
res_prod = super(account_invoice_line,self).product_id_change(cr, uid, ids, product, uom, qty, name, type, partner_id, fposition_id, price_unit, address_invoice_id, context)
res_prod = super(account_invoice_line, self).product_id_change(cr, uid, ids, product, uom, qty, name, type, partner_id, fposition_id, price_unit, address_invoice_id, context)
rec = self.pool.get('account.analytic.default').account_get(cr, uid, product, partner_id, uid, time.strftime('%Y-%m-%d'), context)
if rec and rec.analytics_id:
res_prod['value'].update({'analytics_id':rec.analytics_id.id})
@ -268,10 +268,10 @@ account_invoice_line()
class account_move_line(osv.osv):
_inherit='account.move.line'
_name='account.move.line'
_inherit = 'account.move.line'
_name = 'account.move.line'
_columns = {
'analytics_id':fields.many2one('account.analytic.plan.instance','Analytic Distribution'),
'analytics_id':fields.many2one('account.analytic.plan.instance', 'Analytic Distribution'),
}
def _default_get_move_form_hook(self, cursor, user, data):
@ -284,13 +284,13 @@ class account_move_line(osv.osv):
super(account_move_line, self).create_analytic_lines(cr, uid, ids, context)
for line in self.browse(cr, uid, ids, context):
if line.analytics_id:
toremove = self.pool.get('account.analytic.line').search(cr, uid, [('move_id','=',line.id)], context=context)
toremove = self.pool.get('account.analytic.line').search(cr, uid, [('move_id', '=', line.id)], context=context)
if toremove:
line.unlink(cr, uid, toremove, context=context)
for line2 in line.analytics_id.account_ids:
val = (line.credit or 0.0) - (line.debit or 0.0)
amt=val * (line2.rate/100)
al_vals={
amt = val * (line2.rate / 100)
al_vals = {
'name': line.name,
'date': line.date,
'account_id': line2.analytic_account_id.id,
@ -303,18 +303,18 @@ class account_move_line(osv.osv):
'journal_id': line.analytics_id.journal_id.id,
'ref': line.ref,
}
ali_id=self.pool.get('account.analytic.line').create(cr,uid,al_vals)
ali_id = self.pool.get('account.analytic.line').create(cr, uid, al_vals)
return True
account_move_line()
class account_invoice(osv.osv):
_name = "account.invoice"
_inherit="account.invoice"
_inherit = "account.invoice"
def line_get_convert(self, cr, uid, x, part, date, context={}):
res=super(account_invoice,self).line_get_convert(cr, uid, x, part, date, context)
res['analytics_id']=x.get('analytics_id',False)
res = super(account_invoice, self).line_get_convert(cr, uid, x, part, date, context)
res['analytics_id'] = x.get('analytics_id', False)
return res
def _get_analytic_lines(self, cr, uid, id):
@ -336,14 +336,14 @@ class account_invoice(osv.osv):
ref = inv.reference
else:
ref = self._convert_ref(cr, uid, inv.number)
obj_move_line=self.pool.get('account.analytic.plan.instance').browse(cr,uid,il['analytics_id'])
amount_calc=cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, il['price'], context={'date': inv.date_invoice}) * sign
qty=il['quantity']
il['analytic_lines']=[]
obj_move_line = self.pool.get('account.analytic.plan.instance').browse(cr, uid, il['analytics_id'])
amount_calc = cur_obj.compute(cr, uid, inv.currency_id.id, company_currency, il['price'], context={'date': inv.date_invoice}) * sign
qty = il['quantity']
il['analytic_lines'] = []
for line2 in obj_move_line.account_ids:
amt=amount_calc * (line2.rate/100)
qtty=qty* (line2.rate/100)
al_vals={
amt = amount_calc * (line2.rate / 100)
qtty = qty * (line2.rate / 100)
al_vals = {
'name': il['name'],
'date': inv['date_invoice'],
'unit_amount':qtty,
@ -355,7 +355,7 @@ class account_invoice(osv.osv):
'journal_id': self._get_journal_analytic(cr, uid, inv.type),
'ref': ref,
}
il['analytic_lines'].append((0,0,al_vals))
il['analytic_lines'].append((0, 0, al_vals))
return iml
account_invoice()
@ -379,7 +379,7 @@ class sale_order_line(osv.osv):
# Method overridden to set the analytic account by default on criterion match
def invoice_line_create(self, cr, uid, ids, context={}):
create_ids = super(sale_order_line,self).invoice_line_create(cr, uid, ids, context)
create_ids = super(sale_order_line, self).invoice_line_create(cr, uid, ids, context)
if ids:
sale_line_obj = self.browse(cr, uid, ids[0], context)
pool_inv_line = self.pool.get('account.invoice.line')

View File

@ -26,15 +26,15 @@ from report import report_sxw
class crossovered_analytic(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(crossovered_analytic, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
self.localcontext.update({
'time': time,
'lines': self._lines,
'ref_lines' : self._ref_lines,
'find_children':self.find_children,
})
self.base_amount=0.00
self.base_amount = 0.00
def find_children(self,ref_ids):
def find_children(self, ref_ids):
to_return_ids = []
final_list = []
parent_list = []
@ -42,8 +42,8 @@ class crossovered_analytic(report_sxw.rml_parse):
for id in ref_ids:
# to avoid duplicate entries
if id not in to_return_ids:
to_return_ids.append(self.pool.get('account.analytic.account').search(self.cr,self.uid,[('parent_id','child_of',[id])]))
data_accnt = self.pool.get('account.analytic.account').browse(self.cr,self.uid,to_return_ids[0])
to_return_ids.append(self.pool.get('account.analytic.account').search(self.cr, self.uid, [('parent_id', 'child_of', [id])]))
data_accnt = self.pool.get('account.analytic.account').browse(self.cr, self.uid, to_return_ids[0])
for data in data_accnt:
if data.parent_id and data.parent_id.id == ref_ids[0]:
parent_list.append(data.id)
@ -52,16 +52,16 @@ class crossovered_analytic(report_sxw.rml_parse):
final_list.extend(set_list)
return final_list #to_return_ids[0]
def set_account(self,cats):
def set_account(self, cats):
lst = []
category = self.pool.get('account.analytic.account').read(self.cr,self.uid,cats)
category = self.pool.get('account.analytic.account').read(self.cr, self.uid, cats)
for cat in category:
lst.append(cat['id'])
if cat['child_ids']:
lst.extend(self.set_account(cat['child_ids']))
return lst
def _ref_lines(self,form):
def _ref_lines(self, form):
result = []
res = {}
acc_id = []
@ -75,101 +75,101 @@ class crossovered_analytic(report_sxw.rml_parse):
else:
journal = 'is not null'
query_general = "select id from account_analytic_line where (journal_id " + journal +") AND date>='"+ str(form['date1']) +"'"" AND date<='" + str(form['date2']) + "'"
query_general = "select id from account_analytic_line where (journal_id " + journal + ") AND date>='" + str(form['date1']) + "'"" AND date<='" + str(form['date2']) + "'"
self.cr.execute(query_general)
l_ids=self.cr.fetchall()
l_ids = self.cr.fetchall()
line_ids = [x[0] for x in l_ids]
obj_line = line_pool.browse(self.cr,self.uid,line_ids)
obj_line = line_pool.browse(self.cr, self.uid, line_ids)
#this structure will be usefull for easily knowing the account_analytic_line that are related to the reference account. At this purpose, we save the move_id of analytic lines.
self.dict_acc_ref[form['ref']] = []
children_list = self.pool.get('account.analytic.account').search(self.cr,self.uid,[('parent_id','child_of',[form['ref']])])
children_list = self.pool.get('account.analytic.account').search(self.cr, self.uid, [('parent_id', 'child_of', [form['ref']])])
for obj in obj_line:
if obj.account_id.id in children_list:
if obj.move_id and obj.move_id.id not in self.dict_acc_ref[form['ref']]:
self.dict_acc_ref[form['ref']].append(obj.move_id.id)
res['ref_name'] = acc_pool.name_get(self.cr,self.uid,[form['ref']])[0][1]
res['ref_code'] = acc_pool.browse(self.cr,self.uid,form['ref']).code
res['ref_name'] = acc_pool.name_get(self.cr, self.uid, [form['ref']])[0][1]
res['ref_code'] = acc_pool.browse(self.cr, self.uid, form['ref']).code
self.final_list = children_list
selected_ids = line_pool.search(self.cr,self.uid,[('account_id','in',self.final_list)])
selected_ids = line_pool.search(self.cr, self.uid, [('account_id', 'in', self.final_list)])
query="SELECT sum(aal.amount) AS amt, sum(aal.unit_amount) AS qty FROM account_analytic_line AS aal, account_analytic_account AS aaa \
WHERE aal.account_id=aaa.id AND aal.id IN ("+','.join(map(str,selected_ids))+") AND (aal.journal_id " + journal +") AND aal.date>='"+ str(form['date1']) +"'"" AND aal.date<='" + str(form['date2']) + "'"
query = "SELECT sum(aal.amount) AS amt, sum(aal.unit_amount) AS qty FROM account_analytic_line AS aal, account_analytic_account AS aaa \
WHERE aal.account_id=aaa.id AND aal.id IN (" + ','.join(map(str, selected_ids)) + ") AND (aal.journal_id " + journal + ") AND aal.date>='" + str(form['date1']) + "'"" AND aal.date<='" + str(form['date2']) + "'"
self.cr.execute(query)
info=self.cr.dictfetchall()
info = self.cr.dictfetchall()
res['ref_qty']=info[0]['qty']
res['ref_amt']=info[0]['amt']
self.base_amount= info[0]['amt']
res['ref_qty'] = info[0]['qty']
res['ref_amt'] = info[0]['amt']
self.base_amount = info[0]['amt']
result.append(res)
return result
def _lines(self,form,ids={}):
def _lines(self, form, ids={}):
if not ids:
ids = self.ids
if form['journal_ids'][0][2]:
journal=" in (" + ','.join(map(lambda x: str(x), form['journal_ids'][0][2])) + ")"
journal = " in (" + ','.join(map(lambda x: str(x), form['journal_ids'][0][2])) + ")"
else:
journal= 'is not null'
journal = 'is not null'
acc_pool = self.pool.get('account.analytic.account')
line_pool=self.pool.get('account.analytic.line')
acc_id=[]
final=[]
child_ids=[]
self.list_ids=[]
line_pool = self.pool.get('account.analytic.line')
acc_id = []
final = []
child_ids = []
self.list_ids = []
self.final_list = self.find_children(ids)
for acc_id in self.final_list:
selected_ids = line_pool.search(self.cr,self.uid,[('account_id','=',acc_id),('move_id','in',self.dict_acc_ref[form['ref']])])
selected_ids = line_pool.search(self.cr, self.uid, [('account_id', '=', acc_id), ('move_id', 'in', self.dict_acc_ref[form['ref']])])
if selected_ids:
query="SELECT aaa.code as code , sum(aal.amount) AS amt, sum(aal.unit_amount) AS qty,aaa.name as acc_name,aal.account_id as id FROM account_analytic_line AS aal, account_analytic_account AS aaa \
WHERE aal.account_id=aaa.id AND aal.id IN ("+','.join(map(str,selected_ids))+") AND (aal.journal_id " + journal +") AND aal.date>='"+ str(form['date1']) +"'"" AND aal.date<='" + str(form['date2']) + "'"" GROUP BY aal.account_id,aaa.name,aaa.code ORDER BY aal.account_id"
query = "SELECT aaa.code as code , sum(aal.amount) AS amt, sum(aal.unit_amount) AS qty,aaa.name as acc_name,aal.account_id as id FROM account_analytic_line AS aal, account_analytic_account AS aaa \
WHERE aal.account_id=aaa.id AND aal.id IN (" + ','.join(map(str, selected_ids)) + ") AND (aal.journal_id " + journal + ") AND aal.date>='" + str(form['date1']) + "'"" AND aal.date<='" + str(form['date2']) + "'"" GROUP BY aal.account_id,aaa.name,aaa.code ORDER BY aal.account_id"
self.cr.execute(query)
res = self.cr.dictfetchall()
if res:
for element in res:
if self.base_amount<>0.00:
element['perc']= (element['amt'] / self.base_amount) * 100.00
if self.base_amount <> 0.00:
element['perc'] = (element['amt'] / self.base_amount) * 100.00
else:
element['perc']=0.00
element['perc'] = 0.00
else:
result={}
res=[]
result['id']=acc_id
data_account = acc_pool.browse(self.cr,self.uid,acc_id)
result['acc_name']=data_account.name
result = {}
res = []
result['id'] = acc_id
data_account = acc_pool.browse(self.cr, self.uid, acc_id)
result['acc_name'] = data_account.name
result['code'] = data_account.code
result['amt']=result['qty']=result['perc']=0.00
result['amt'] = result['qty'] = result['perc'] = 0.00
if not form['empty_line']:
res.append(result)
else:
result={}
res=[]
result['id']=acc_id
data_account = acc_pool.browse(self.cr,self.uid,acc_id)
result['acc_name']=data_account.name
result = {}
res = []
result['id'] = acc_id
data_account = acc_pool.browse(self.cr, self.uid, acc_id)
result['acc_name'] = data_account.name
result['code'] = data_account.code
result['amt']=result['qty']=result['perc']=0.00
result['amt'] = result['qty'] = result['perc'] = 0.00
if not form['empty_line']:
res.append(result)
for item in res:
obj_acc=acc_pool.name_get(self.cr,self.uid,[item['id']])
item['acc_name']=obj_acc[0][1]
obj_acc = acc_pool.name_get(self.cr, self.uid, [item['id']])
item['acc_name'] = obj_acc[0][1]
final.append(item)
return final
report_sxw.report_sxw('report.account.analytic.account.crossovered.analytic', 'account.analytic.account', 'addons/account_analytic_plans/report/crossovered_analytic.rml',parser=crossovered_analytic, header=False)
report_sxw.report_sxw('report.account.analytic.account.crossovered.analytic', 'account.analytic.account', 'addons/account_analytic_plans/report/crossovered_analytic.rml', parser=crossovered_analytic, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -37,10 +37,10 @@ def activate(self, cr, uid, data, context):
plan = plan_obj.browse(cr, uid, data['id'], context)
if (not plan.name) or (not plan.code):
raise wizard.except_wizard(_('Error'), _('Please put a name and a code before saving the model !'))
pids = pooler.get_pool(cr.dbname).get('account.analytic.plan').search(cr, uid, [], context=context)
pids = pooler.get_pool(cr.dbname).get('account.analytic.plan').search(cr, uid, [], context=context)
if (not pids):
raise wizard.except_wizard(_('Error'), _('No analytic plan defined !'))
plan_obj.write(cr,uid,[data['id']],{'plan_id':pids[0]})
plan_obj.write(cr, uid, [data['id']], {'plan_id':pids[0]})
return 'info'
else:
return 'endit'
@ -53,15 +53,15 @@ class create_model(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type':'choice','next_state':activate}
'result': {'type':'choice', 'next_state':activate}
},
'info': {
'actions': [],
'result': {'type':'form', 'arch':info, 'fields':{}, 'state':[('end','OK')]}
'result': {'type':'form', 'arch':info, 'fields':{}, 'state':[('end', 'OK')]}
},
'endit': {
'actions': [],
'result': {'type':'action','action':_do_nothing , 'state':'end'} #FIXME: check
'result': {'type':'action', 'action':_do_nothing , 'state':'end'} #FIXME: check
},
}
create_model('create.model')

View File

@ -35,21 +35,21 @@ form = """<?xml version="1.0"?>
</form>"""
fields = {
'date1': {'string':'Start Date', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')},
'date2': {'string':'End Date', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')},
'date1': {'string':'Start Date', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-01-01')},
'date2': {'string':'End Date', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')},
'journal_ids': {'string':'Analytic Journal', 'type':'many2many', 'relation':'account.analytic.journal'},
'ref' :{'string':'Analytic Account Reference', 'type':'many2one', 'relation':'account.analytic.account','required':True},
'empty_line': {'string':'Dont show empty lines', 'type':'boolean', 'default': lambda *a:False},
'ref' :{'string':'Analytic Account Reference', 'type':'many2one', 'relation':'account.analytic.account', 'required':True},
'empty_line': {'string':'Dont show empty lines', 'type':'boolean', 'default': lambda * a:False},
}
class wizard_crossovered_analytic(wizard.interface):
def _checklines(self, cr, uid, data, context):
cr.execute('select account_id from account_analytic_line')
res=cr.fetchall()
acc_ids=[x[0] for x in res]
res = cr.fetchall()
acc_ids = [x[0] for x in res]
obj_acc = pooler.get_pool(cr.dbname).get('account.analytic.account').browse(cr,uid,data['form']['ref'])
name=obj_acc.name
obj_acc = pooler.get_pool(cr.dbname).get('account.analytic.account').browse(cr, uid, data['form']['ref'])
name = obj_acc.name
account_ids = pooler.get_pool(cr.dbname).get('account.analytic.account').search(cr, uid, [('parent_id', 'child_of', [data['form']['ref']])])
@ -60,13 +60,13 @@ class wizard_crossovered_analytic(wizard.interface):
break
if flag:
raise wizard.except_wizard(_('User Error'),_('There are no Analytic lines related to Account %s' % name))
raise wizard.except_wizard(_('User Error'), _('There are no Analytic lines related to Account %s' % name))
return {}
states = {
'init': {
'actions': [],
'result': {'type':'form', 'arch':form, 'fields':fields, 'state':[('end','Cancel'),('print','Print')]},
'result': {'type':'form', 'arch':form, 'fields':fields, 'state':[('end', 'Cancel'), ('print', 'Print')]},
},
'print': {
'actions': [_checklines],

View File

@ -22,4 +22,4 @@ import product
import stock
import purchase
import invoice
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -33,8 +33,8 @@
"category" : "Generic Modules/Inventory Control",
"init_xml" : [],
"demo_xml" : [],
"update_xml" : ["product_view.xml",],
"update_xml" : ["product_view.xml", ],
"active": False,
"installable": True
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -25,11 +25,11 @@ from osv import fields, osv
class account_invoice_line(osv.osv):
_inherit = "account.invoice.line"
def move_line_get(self, cr, uid, invoice_id, context=None):
res = super(account_invoice_line,self).move_line_get(cr, uid, invoice_id, context)
res = super(account_invoice_line, self).move_line_get(cr, uid, invoice_id, context)
inv = self.pool.get('account.invoice').browse(cr, uid, invoice_id)
if inv.type in ('out_invoice','out_refund'):
if inv.type in ('out_invoice', 'out_refund'):
for i_line in inv.invoice_line:
if i_line.product_id:
if inv.type == 'out_invoice':
@ -63,20 +63,20 @@ class account_invoice_line(osv.osv):
'account_analytic_id':i_line.account_analytic_id.id,
'taxes':i_line.invoice_line_tax_id,
})
res.append({
'type':'src',
'name': i_line.name[:64],
'price_unit':i_line.product_id.product_tmpl_id.standard_price,
'quantity':i_line.quantity,
'price': -1 * i_line.product_id.product_tmpl_id.standard_price * i_line.quantity,
'price':-1 * i_line.product_id.product_tmpl_id.standard_price * i_line.quantity,
'account_id':cacc,
'product_id':i_line.product_id.id,
'uos_id':i_line.uos_id.id,
'account_analytic_id':i_line.account_analytic_id.id,
'taxes':i_line.invoice_line_tax_id,
})
elif inv.type in ('in_invoice','in_refund'):
elif inv.type in ('in_invoice', 'in_refund'):
for i_line in inv.invoice_line:
if i_line.product_id:
if i_line.product_id.product_tmpl_id.type != 'service':
@ -122,18 +122,18 @@ class account_invoice_line(osv.osv):
'product_id':line['product_id'],
'uos_id':line['uos_id'],
'account_analytic_id':line['account_analytic_id'],
'taxes':line.get('taxes',[]),
'taxes':line.get('taxes', []),
})
res += diff_res
return res
return res
def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, address_invoice_id=False, context=None):
if not product:
return super(account_invoice_line, self).product_id_change(cr, uid, ids, product, uom, qty, name, type, partner_id, fposition_id, price_unit, address_invoice_id, context)
else:
res = super(account_invoice_line, self).product_id_change(cr, uid, ids, product, uom, qty, name, type, partner_id, fposition_id, price_unit, address_invoice_id, context)
if type in ('in_invoice','in_refund'):
if type in ('in_invoice', 'in_refund'):
product_obj = self.pool.get('product.product').browse(cr, uid, product, context=context)
if type == 'in_invoice':
oa = product_obj.product_tmpl_id.property_stock_account_input and product_obj.product_tmpl_id.property_stock_account_input.id
@ -146,9 +146,9 @@ class account_invoice_line(osv.osv):
if oa:
fpos = fposition_id and self.pool.get('account.fiscal.position').browse(cr, uid, fposition_id) or False
a = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, oa)
res['value'].update({'account_id':a})
res['value'].update({'account_id':a})
return res
account_invoice_line()
class account_invoice(osv.osv):
@ -157,20 +157,20 @@ class account_invoice(osv.osv):
def _refund_cleanup_lines(self, cr, uid, lines):
for line in lines:
inv_id = line['invoice_id']
inv_obj = self.browse(cr,uid,inv_id[0])
inv_obj = self.browse(cr, uid, inv_id[0])
if inv_obj.type == 'in_invoice':
if line.get('product_id',False):
product_obj = self.pool.get('product.product').browse(cr,uid,line['product_id'][0])
if line.get('product_id', False):
product_obj = self.pool.get('product.product').browse(cr, uid, line['product_id'][0])
oa = product_obj.product_tmpl_id.property_stock_account_output and product_obj.product_tmpl_id.property_stock_account_output.id
if not oa:
oa = product_obj.categ_id.property_stock_account_output_categ and product_obj.categ_id.property_stock_account_output_categ.id
if oa:
fpos = inv_obj.fiscal_position or False
a = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, oa)
account_data = self.pool.get('account.account').read(cr,uid,[a],['name'])[0]
line.update({'account_id': (account_data['id'],account_data['name'])})
res = super(account_invoice,self)._refund_cleanup_lines(cr, uid, lines)
account_data = self.pool.get('account.account').read(cr, uid, [a], ['name'])[0]
line.update({'account_id': (account_data['id'], account_data['name'])})
res = super(account_invoice, self)._refund_cleanup_lines(cr, uid, lines)
return res
account_invoice()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -30,7 +30,7 @@ class product_category(osv.osv):
string="Price Difference Account",
method=True,
view_load=True,
help="This account will be used to value price difference between purchase price and cost price."),
help="This account will be used to value price difference between purchase price and cost price."),
}
product_category()
@ -45,7 +45,7 @@ class product_template(osv.osv):
string="Price Difference Account",
method=True,
view_load=True,
help="This account will be used to value price difference between purchase price and cost price."),
help="This account will be used to value price difference between purchase price and cost price."),
}
product_template()

View File

@ -37,5 +37,5 @@ class purchase_order(osv.osv):
a = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, oa)
line[2].update({'account_id': a})
return line
purchase_order()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
purchase_order()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -19,7 +19,7 @@
#
##############################################################################
from osv import fields,osv
from osv import fields, osv
#----------------------------------------------------------
# Stock Picking
@ -31,7 +31,7 @@ class stock_picking(osv.osv):
def action_invoice_create(self, cr, uid, ids, journal_id=False,
group=False, type='out_invoice', context=None):
'''Return ids of created invoices for the pickings'''
res = super(stock_picking,self).action_invoice_create(cr, uid, ids, journal_id, group, type, context)
res = super(stock_picking, self).action_invoice_create(cr, uid, ids, journal_id, group, type, context)
if type == 'in_refund':
for inv in self.pool.get('account.invoice').browse(cr, uid, res.values(), context=context):
for ol in inv.invoice_line:
@ -43,14 +43,14 @@ class stock_picking(osv.osv):
fpos = ol.invoice_id.fiscal_position or False
a = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, oa)
self.pool.get('account.invoice.line').write(cr, uid, [ol.id], {'account_id': a})
elif type == 'in_invoice':
for inv in self.pool.get('account.invoice').browse(cr, uid, res.values(), context=context):
for ol in inv.invoice_line:
if ol.product_id:
oa = ol.product_id.product_tmpl_id.property_stock_account_input and ol.product_id.product_tmpl_id.property_stock_account_input.id
if not oa:
oa = ol.product_id.categ_id.property_stock_account_input_categ and ol.product_id.categ_id.property_stock_account_input_categ.id
oa = ol.product_id.categ_id.property_stock_account_input_categ and ol.product_id.categ_id.property_stock_account_input_categ.id
if oa:
fpos = ol.invoice_id.fiscal_position or False
a = self.pool.get('account.fiscal.position').map_account(cr, uid, fpos, oa)

View File

@ -25,8 +25,8 @@ from osv import fields, osv
class account_move_line(osv.osv):
_name="account.move.line"
_inherit="account.move.line"
_name = "account.move.line"
_inherit = "account.move.line"
_description = "Entry lines"
def _query_get(self, cr, uid, obj='l', context={}):
@ -37,7 +37,7 @@ class account_move_line(osv.osv):
#the query have to be build with no reference to periods but thanks to the creation date
if context['periods']:
#if one or more period are given, use them
p_ids = self.pool.get('account.period').search(cr,uid,[('id','in',context['periods'])])
p_ids = self.pool.get('account.period').search(cr, uid, [('id', 'in', context['periods'])])
else:
#else we have to consider all the periods of the selected fiscal year(s)
fiscalyear_obj = self.pool.get('account.fiscalyear')
@ -47,7 +47,7 @@ class account_move_line(osv.osv):
fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')])
else:
fiscalyear_ids = [context['fiscalyear']]
p_ids = self.pool.get('account.period').search(cr,uid,[('fiscalyear_id','in',fiscalyear_ids)])
p_ids = self.pool.get('account.period').search(cr, uid, [('fiscalyear_id', 'in', fiscalyear_ids)])
if p_ids == []:
return query
@ -56,7 +56,7 @@ class account_move_line(osv.osv):
res = ''
count = 1
clause_list = query.split('AND')
ref_string = ' '+obj+'.period_id in'
ref_string = ' ' + obj + '.period_id in'
for clause in clause_list:
if count != 1 and not clause.startswith(ref_string):
res += "AND"
@ -67,13 +67,13 @@ class account_move_line(osv.osv):
#add to 'res' a new clause containing the creation date criterion
count = 1
res += " AND ("
periods = self.pool.get('account.period').read(cr,uid,p_ids,['date_start','date_stop'])
periods = self.pool.get('account.period').read(cr, uid, p_ids, ['date_start', 'date_stop'])
for period in periods:
if count != 1:
res += " OR "
#creation date criterion: the creation date of the move_line has to be
# between the date_start and the date_stop of the selected periods
res += "("+obj+".create_date between to_date('" + period['date_start'] + "','yyyy-mm-dd') and to_date('" + period['date_stop'] + "','yyyy-mm-dd'))"
res += "(" + obj + ".create_date between to_date('" + period['date_start'] + "','yyyy-mm-dd') and to_date('" + period['date_stop'] + "','yyyy-mm-dd'))"
count += 1
res += ")"
return res

View File

@ -35,16 +35,16 @@ parents = {
class account_balance(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(account_balance, self).__init__(cr, uid, name, context=context)
self.flag=1
self.dr_total= 0.00
self.cr_total= 0.00
self.parent_bal=0
self.status=0
self.done_total=0
self.baldiv={}
self.empty_parent=0
self.flag = 1
self.dr_total = 0.00
self.cr_total = 0.00
self.parent_bal = 0
self.status = 0
self.done_total = 0
self.baldiv = {}
self.empty_parent = 0
self.result_total = {}
self.total_for_perc=[]
self.total_for_perc = []
self.localcontext.update({
'time': time,
'lines': self.lines,
@ -319,10 +319,10 @@ class account_balance(report_sxw.rml_parse):
# i+=1
# return super(account_balance,self).repeatIn(lst, name, nodes_parent=False)
#end
def linesForYear(self,form):
temp=0
years={}
def linesForYear(self, form):
temp = 0
years = {}
global pattern
global show
@ -330,190 +330,190 @@ class account_balance(report_sxw.rml_parse):
global bal_zero
global ref_bal
pattern=form['compare_pattern']
pattern = form['compare_pattern']
if form['show_columns']!=1:
show=0
if form['show_columns'] != 1:
show = 0
else:
show=form['show_columns']
show = form['show_columns']
if form['format_perc']!=1:
perc=0
if form['format_perc'] != 1:
perc = 0
else:
perc=form['format_perc']
perc = form['format_perc']
if form['account_choice']=='bal_zero':
bal_zero=0
if form['account_choice'] == 'bal_zero':
bal_zero = 0
else:
bal_zero=1
bal_zero = 1
ctx = self.context.copy()
if perc==1:
if form['select_account']!=False:
ref_ac=self.pool.get('account.account').browse(self.cr, self.uid,form['select_account'],ctx.copy())
if ref_ac.balance<>0.00:
ref_bal=ref_ac.balance
if perc == 1:
if form['select_account'] != False:
ref_ac = self.pool.get('account.account').browse(self.cr, self.uid, form['select_account'], ctx.copy())
if ref_ac.balance <> 0.00:
ref_bal = ref_ac.balance
else:
ref_bal=1.00
ref_bal = 1.00
else:
ref_bal='nothing'
ref_bal = 'nothing'
else:
ref_bal='nothing'
ref_bal = 'nothing'
total_for_perc=[]
total_for_perc = []
# if perc==1:
self.done_total=1
self.total_for_perc=self.linesForTotal(form,ids={},doneAccount={},level=1)
self.done_total=0
self.done_total = 1
self.total_for_perc = self.linesForTotal(form, ids={}, doneAccount={}, level=1)
self.done_total = 0
for t1 in range(0,len(form['fiscalyear'][0][2])):
for t1 in range(0, len(form['fiscalyear'][0][2])):
locale.setlocale(locale.LC_ALL, '')
self.result_total["sum_credit" + str(t1)]=locale.format("%.2f", self.result_total["sum_credit" + str(t1)], grouping=True)
self.result_total["sum_debit" + str(t1)]=locale.format("%.2f", self.result_total["sum_debit" + str(t1)], grouping=True)
self.result_total["sum_credit" + str(t1)] = locale.format("%.2f", self.result_total["sum_credit" + str(t1)], grouping=True)
self.result_total["sum_debit" + str(t1)] = locale.format("%.2f", self.result_total["sum_debit" + str(t1)], grouping=True)
# self.flag=1
# self.result_total = {}
for temp in range(0,len(form['fiscalyear'][0][2])):
fy=self.pool.get('account.fiscalyear').name_get(self.cr,self.uid,form['fiscalyear'][0][2][temp])
years["year"+str(temp)]=fy[0][1][12:16]
for temp in range(0, len(form['fiscalyear'][0][2])):
fy = self.pool.get('account.fiscalyear').name_get(self.cr, self.uid, form['fiscalyear'][0][2][temp])
years["year" + str(temp)] = fy[0][1][12:16]
return [years]
def linesForTotal(self,form,ids={},doneAccount={},level=1):
if self.done_total==1:
self.done_total==1
def linesForTotal(self, form, ids={}, doneAccount={}, level=1):
if self.done_total == 1:
self.done_total == 1
else:
return [self.result_total]
accounts=[]
accounts = []
if not ids:
ids = self.ids
if not ids:
return []
ctx = self.context.copy()
result_total_parent=[]
result_total_parent = []
for id in form['fiscalyear'][0][2]:
tmp=[]
tmp = []
ctx['fiscalyear'] = id
ctx['periods'] = form['periods'][0][2]
ctx['period_manner'] = form['period_manner']
ctx['state'] = form['context'].get('state','all')
ctx['state'] = form['context'].get('state', 'all')
tmp = self.pool.get('account.account').browse(self.cr, self.uid, ids, ctx.copy())
if len(tmp):
accounts.append(tmp)
merged_accounts=zip(*accounts)
merged_accounts = zip(*accounts)
# used to check for the frst record so all sum_credit and sum_debit r set to 0.00
if level==1:
doneAccount={}
if level == 1:
doneAccount = {}
for entry in merged_accounts:
if entry[0].id in doneAccount:
continue
doneAccount[entry[0].id] = 1
for k in range(0,len(entry)):
temp_credit=0.00
temp_debit=0.00
for k in range(0, len(entry)):
temp_credit = 0.00
temp_debit = 0.00
if entry[0].type <> 'view':
temp_credit+=entry[k].credit
temp_debit+=entry[k].debit
temp_credit += entry[k].credit
temp_debit += entry[k].debit
if self.flag==1:
self.result_total["sum_credit" + str(k)]=0.00
self.result_total["sum_debit" + str(k)]=0.00
if form['account_choice']=='bal_zero':
if temp_credit<>temp_debit:
self.result_total["sum_credit" + str(k)]+=temp_credit
self.result_total["sum_debit" + str(k)]+=temp_debit
if self.flag == 1:
self.result_total["sum_credit" + str(k)] = 0.00
self.result_total["sum_debit" + str(k)] = 0.00
if form['account_choice'] == 'bal_zero':
if temp_credit <> temp_debit:
self.result_total["sum_credit" + str(k)] += temp_credit
self.result_total["sum_debit" + str(k)] += temp_debit
else:
self.result_total["sum_credit" + str(k)]+=temp_credit
self.result_total["sum_debit" + str(k)]+=temp_debit
self.result_total["sum_credit" + str(k)] += temp_credit
self.result_total["sum_debit" + str(k)] += temp_debit
self.flag=2
self.flag = 2
if entry[0].child_id:
ids2 = [(x.code,x.id) for x in entry[0].child_id]
ids2 = [(x.code, x.id) for x in entry[0].child_id]
ids2.sort()
result_total_parent = self.linesForTotal(form, [x[1] for x in ids2],doneAccount,level+1)
result_total_parent = self.linesForTotal(form, [x[1] for x in ids2], doneAccount, level + 1)
return [self.result_total]
def lines(self, form, ids={}, done={}, level=1):
accounts=[]
accounts = []
if not ids:
ids = self.ids
if not ids:
return []
result = []
ctx = self.context.copy()
tmp1=[]
tmp1 = []
for id in form['fiscalyear'][0][2]:
ctx['fiscalyear'] = id
ctx['periods'] = form['periods'][0][2]
ctx['period_manner']=form['period_manner']
ctx['state'] = form['context'].get('state','all')
tmp1 = self.pool.get('account.account').browse(self.cr, self.uid, ids,ctx.copy())
ctx['period_manner'] = form['period_manner']
ctx['state'] = form['context'].get('state', 'all')
tmp1 = self.pool.get('account.account').browse(self.cr, self.uid, ids, ctx.copy())
if len(tmp1):
accounts.append(tmp1)
if level==1: #if parent is called,done is not empty when called again.
done={}
if level == 1: #if parent is called,done is not empty when called again.
done = {}
def cmp_code(x, y):
return cmp(x.code, y.code)
for n in range(0,len(accounts)):
for n in range(0, len(accounts)):
accounts[n].sort(cmp_code)
common={}
merged_accounts=zip(*accounts)
common = {}
merged_accounts = zip(*accounts)
for entry in merged_accounts:
j=0
checked=1
j = 0
checked = 1
if form['account_choice']!='all': # if checked,include empty a/c;not otherwise
checked=0
if form['account_choice'] != 'all': # if checked,include empty a/c;not otherwise
checked = 0
if entry[0].id in done:
continue
done[entry[0].id] = 1
if entry[0].child_id: # this is for parent account,dont check 0 for it
checked=4
self.status=1 # for displaying it Bold
checked = 4
self.status = 1 # for displaying it Bold
else:
self.status=0
if checked==0:
i=0
for i in range(0,len(entry)):
if bal_zero==0:
if entry[i].balance<>0.0:
checked=4
self.status = 0
if checked == 0:
i = 0
for i in range(0, len(entry)):
if bal_zero == 0:
if entry[i].balance <> 0.0:
checked = 4
break
else:
checked=3
i=i+1
checked = 3
i = i + 1
else:
if entry[i].credit <> 0.0 or entry[i].debit <> 0.0:
checked=4
checked = 4
break
else:
checked=3
i=i+1
checked = 3
i = i + 1
if checked==3:
if checked == 3:
# this is the point where we skip those accounts which are encountered as empty ones
continue
self.empty_parent=0
self.empty_parent = 0
else:
self.empty_parent=1
self.empty_parent = 1
res = {
'code': entry[0].code,
'name': entry[0].name,
@ -521,96 +521,96 @@ class account_balance(report_sxw.rml_parse):
'status': self.status,
}
for j in range(0,len(entry)):
for j in range(0, len(entry)):
locale.setlocale(locale.LC_ALL, '')
res["debit"+str(j)]=locale.format("%.2f", entry[j].debit, grouping=True)
res["credit"+str(j)]=locale.format("%.2f", entry[j].credit, grouping=True)
res["balance"+str(j)]=locale.format("%.2f", entry[j].balance, grouping=True)
res["debit" + str(j)] = locale.format("%.2f", entry[j].debit, grouping=True)
res["credit" + str(j)] = locale.format("%.2f", entry[j].credit, grouping=True)
res["balance" + str(j)] = locale.format("%.2f", entry[j].balance, grouping=True)
if j==0:
res["bal_cash"+str(j)]="0.00"
res["bal_perc"+str(j)]="0.00%"
if j == 0:
res["bal_cash" + str(j)] = "0.00"
res["bal_perc" + str(j)] = "0.00%"
else:
temp_cash=entry[j].balance - entry[j-1].balance
res["bal_cash"+str(j)]=locale.format("%.2f", temp_cash, grouping=True)
if entry[j-1].balance<>0.00:
temp_perc=(entry[j].balance - entry[j-1].balance )*100/entry[j-1].balance
temp_cash = entry[j].balance - entry[j - 1].balance
res["bal_cash" + str(j)] = locale.format("%.2f", temp_cash, grouping=True)
if entry[j - 1].balance <> 0.00:
temp_perc = (entry[j].balance - entry[j - 1].balance) * 100 / entry[j - 1].balance
else:
temp_perc=(entry[j].balance) *100
temp_perc = (entry[j].balance) * 100
res["bal_perc"+str(j)]=locale.format("%.2f", temp_perc) + "%"
res["bal_perc" + str(j)] = locale.format("%.2f", temp_perc) + "%"
if ref_bal=='nothing':
if level==1:
self.parent_bal=1
if ref_bal == 'nothing':
if level == 1:
self.parent_bal = 1
else:
self.parent_bal=0
self.parent_bal = 0
if self.parent_bal==1:
res["balance_perc"+str(j)]="/"
if self.parent_bal == 1:
res["balance_perc" + str(j)] = "/"
else:
if entry[j].balance==0.00:
if self.baldiv["baldiv"+str(level-1)+str(j)]<>0.00:
res["balance_perc"+str(j)]="0.00%"
if entry[j].balance == 0.00:
if self.baldiv["baldiv" + str(level - 1) + str(j)] <> 0.00:
res["balance_perc" + str(j)] = "0.00%"
else:
res["balance_perc"+str(j)]="/"
res["balance_perc" + str(j)] = "/"
else:
if self.baldiv["baldiv"+str(level-1)+str(j)]<>0.00:
temp=self.baldiv["baldiv"+str(level-1)+str(j)]
temp1=(entry[j].balance * 100 )/ float(temp)
temp1=round(temp1,2)
res["balance_perc" + str(j)]=str(temp1)+"%"
if self.baldiv["baldiv" + str(level - 1) + str(j)] <> 0.00:
temp = self.baldiv["baldiv" + str(level - 1) + str(j)]
temp1 = (entry[j].balance * 100) / float(temp)
temp1 = round(temp1, 2)
res["balance_perc" + str(j)] = str(temp1) + "%"
else:
res["balance_perc"+str(j)]="/"
res["balance_perc" + str(j)] = "/"
else:
res["balance_perc"+str(j)]=str( (entry[j].balance * 100 )/ float(ref_bal)) + "%"
res["balance_perc" + str(j)] = str((entry[j].balance * 100) / float(ref_bal)) + "%"
result.append(res)
if entry[0].child_id:
for q in range(0,len(form['fiscalyear'][0][2])):
self.baldiv["baldiv"+str(level)+str(q)]=entry[q].balance
for q in range(0, len(form['fiscalyear'][0][2])):
self.baldiv["baldiv" + str(level) + str(q)] = entry[q].balance
ids2 = [(x.code,x.id) for x in entry[0].child_id]
ids2 = [(x.code, x.id) for x in entry[0].child_id]
ids2.sort()
dir=[]
dir += self.lines(form, [x[1] for x in ids2], done, level+1)
if dir==[]:
for w in range(0,len(form['fiscalyear'][0][2])):
if entry[w].credit <> 0.0 or entry[w].debit <> 0.0 or entry[w].balance<>0.00:
dont_pop=1
dir = []
dir += self.lines(form, [x[1] for x in ids2], done, level + 1)
if dir == []:
for w in range(0, len(form['fiscalyear'][0][2])):
if entry[w].credit <> 0.0 or entry[w].debit <> 0.0 or entry[w].balance <> 0.00:
dont_pop = 1
break
else:
dont_pop=0
if dont_pop==1:
result +=dir
dont_pop = 0
if dont_pop == 1:
result += dir
else:
result.pop(-1) # here we pop up the parent having its children as emprty accounts
else:
result +=dir
result += dir
return result
def get_years(self,form):
result =[]
res={}
for temp in range(0,len(form['fiscalyear'][0][2])):
res={}
fy=self.pool.get('account.fiscalyear').name_get(self.cr,self.uid,form['fiscalyear'][0][2][temp])
res['year']=fy[0][1]
res['last_str']=temp
def get_years(self, form):
result = []
res = {}
for temp in range(0, len(form['fiscalyear'][0][2])):
res = {}
fy = self.pool.get('account.fiscalyear').name_get(self.cr, self.uid, form['fiscalyear'][0][2][temp])
res['year'] = fy[0][1]
res['last_str'] = temp
result.append(res)
self.linesForYear(form)
return result
def get_lines(self,year_dict,form):
def get_lines(self, year_dict, form):
final_result = []
line_l =[]
res = {}
line_l = []
res = {}
line_l = self.lines(form)
self.cal_total(year_dict)
if line_l:
@ -619,44 +619,44 @@ class account_balance(report_sxw.rml_parse):
res['code'] = l['code']
res['name'] = l['name']
res['level'] = l['level']
for k,v in l.items():
if k.startswith('debit'+str(year_dict['last_str'])):
res['debit'] = v
if k.startswith('credit'+str(year_dict['last_str'])):
for k, v in l.items():
if k.startswith('debit' + str(year_dict['last_str'])):
res['debit'] = v
if k.startswith('credit' + str(year_dict['last_str'])):
res['credit'] = v
if k.startswith('balance'+str(year_dict['last_str'])) and not k.startswith('balance_perc'+str(year_dict['last_str'])):
res['balance'] =v
if k.startswith('balance_perc'+str(year_dict['last_str'])) and not k.startswith('balance'+str(year_dict['last_str'])):
if k.startswith('balance' + str(year_dict['last_str'])) and not k.startswith('balance_perc' + str(year_dict['last_str'])):
res['balance'] = v
if k.startswith('balance_perc' + str(year_dict['last_str'])) and not k.startswith('balance' + str(year_dict['last_str'])):
res['balance_perc'] = v
if form['compare_pattern'] == 'bal_perc':
if k.startswith('bal_perc'+str(year_dict['last_str'])):
if k.startswith('bal_perc' + str(year_dict['last_str'])):
res['pattern'] = v
elif form['compare_pattern'] == 'bal_cash':
if k.startswith('bal_cash'+str(year_dict['last_str'])):
if k.startswith('bal_cash' + str(year_dict['last_str'])):
res['pattern'] = v
else:
res['pattern'] = ''
final_result.append(res)
return final_result
def cal_total(self,year_dict):
def cal_total(self, year_dict):
total_l = self.result_total
if total_l:
for k,v in total_l.items():
if k.startswith('sum_debit'+str(year_dict['last_str'])):
for k, v in total_l.items():
if k.startswith('sum_debit' + str(year_dict['last_str'])):
self.dr_total = v
elif k.startswith('sum_credit'+str(year_dict['last_str'])):
elif k.startswith('sum_credit' + str(year_dict['last_str'])):
self.cr_total = v
else:
continue
return True
def total_dr(self):
return self.dr_total
def total_cr(self):
return self.cr_total
report_sxw.report_sxw('report.account.balance.account.balance', 'account.account', 'addons/account_balance/report/account_balance.rml', parser=account_balance, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -36,16 +36,16 @@ parents = {
class account_balance_landscape(rml_parse.rml_parse):
def __init__(self, cr, uid, name, context):
super(account_balance_landscape, self).__init__(cr, uid, name, context=context)
self.flag=1
self.dr_total= 0.00
self.cr_total= 0.00
self.parent_bal=0
self.status=0
self.done_total=0
self.baldiv={}
self.empty_parent=0
self.flag = 1
self.dr_total = 0.00
self.cr_total = 0.00
self.parent_bal = 0
self.status = 0
self.done_total = 0
self.baldiv = {}
self.empty_parent = 0
self.result_total = {}
self.total_for_perc=[]
self.total_for_perc = []
self.localcontext.update({
'time': time,
'lines': self.lines,
@ -320,9 +320,9 @@ class account_balance_landscape(rml_parse.rml_parse):
# i+=1
# return super(account_balance_landscape,self).repeatIn(lst, name, nodes_parent=False)
#end
def linesForYear(self,form):
temp=0
years={}
def linesForYear(self, form):
temp = 0
years = {}
global pattern
global show
@ -330,193 +330,193 @@ class account_balance_landscape(rml_parse.rml_parse):
global bal_zero
global ref_bal
pattern=form['compare_pattern']
pattern = form['compare_pattern']
if form['show_columns']!=1:
show=0
if form['show_columns'] != 1:
show = 0
else:
show=form['show_columns']
show = form['show_columns']
if form['format_perc']!=1:
perc=0
if form['format_perc'] != 1:
perc = 0
else:
perc=form['format_perc']
perc = form['format_perc']
if form['account_choice']=='bal_zero':
bal_zero=0
if form['account_choice'] == 'bal_zero':
bal_zero = 0
else:
bal_zero=1
bal_zero = 1
ctx = self.context.copy()
if perc==1:
if form['select_account']!=False:
ref_ac=self.pool.get('account.account').browse(self.cr, self.uid,form['select_account'],ctx.copy())
if ref_ac.balance<>0.00:
ref_bal=ref_ac.balance
if perc == 1:
if form['select_account'] != False:
ref_ac = self.pool.get('account.account').browse(self.cr, self.uid, form['select_account'], ctx.copy())
if ref_ac.balance <> 0.00:
ref_bal = ref_ac.balance
else:
ref_bal=1.00
ref_bal = 1.00
else:
ref_bal='nothing'
ref_bal = 'nothing'
else:
ref_bal='nothing'
ref_bal = 'nothing'
total_for_perc=[]
total_for_perc = []
# if perc==1:
self.done_total=1
self.total_for_perc=self.linesForTotal(form,ids={},doneAccount={},level=1)
self.done_total=0
self.done_total = 1
self.total_for_perc = self.linesForTotal(form, ids={}, doneAccount={}, level=1)
self.done_total = 0
for t1 in range(0,len(form['fiscalyear'][0][2])):
for t1 in range(0, len(form['fiscalyear'][0][2])):
locale.setlocale(locale.LC_ALL, '')
self.result_total["sum_credit" + str(t1)]=locale.format("%.2f", self.result_total["sum_credit" + str(t1)], grouping=True)
self.result_total["sum_debit" + str(t1)]=locale.format("%.2f", self.result_total["sum_debit" + str(t1)], grouping=True)
self.result_total["sum_credit" + str(t1)] = locale.format("%.2f", self.result_total["sum_credit" + str(t1)], grouping=True)
self.result_total["sum_debit" + str(t1)] = locale.format("%.2f", self.result_total["sum_debit" + str(t1)], grouping=True)
# self.flag=1
# self.result_total = {}
for temp in range(0,len(form['fiscalyear'][0][2])):
fy=self.pool.get('account.fiscalyear').name_get(self.cr,self.uid,form['fiscalyear'][0][2][temp])
years["year"+str(temp)]=fy[0][1][12:16]
for temp in range(0, len(form['fiscalyear'][0][2])):
fy = self.pool.get('account.fiscalyear').name_get(self.cr, self.uid, form['fiscalyear'][0][2][temp])
years["year" + str(temp)] = fy[0][1][12:16]
return [years]
def linesForTotal(self,form,ids={},doneAccount={},level=1):
if self.done_total==1:
self.done_total==1
def linesForTotal(self, form, ids={}, doneAccount={}, level=1):
if self.done_total == 1:
self.done_total == 1
else:
return [self.result_total]
accounts=[]
accounts = []
if not ids:
ids = self.ids
if not ids:
return []
ctx = self.context.copy()
result_total_parent=[]
result_total_parent = []
for id in form['fiscalyear'][0][2]:
tmp=[]
tmp = []
ctx['fiscalyear'] = id
ctx['periods'] = form['periods'][0][2]
ctx['period_manner'] = form['period_manner']
ctx['state'] = form['context'].get('state','all')
ctx['state'] = form['context'].get('state', 'all')
tmp = self.pool.get('account.account').browse(self.cr, self.uid, ids, ctx.copy())
if len(tmp):
accounts.append(tmp)
merged_accounts=zip(*accounts)
merged_accounts = zip(*accounts)
# used to check for the frst record so all sum_credit and sum_debit r set to 0.00
if level==1:
doneAccount={}
if level == 1:
doneAccount = {}
for entry in merged_accounts:
if entry[0].id in doneAccount:
continue
doneAccount[entry[0].id] = 1
for k in range(0,len(entry)):
temp_credit=0.00
temp_debit=0.00
for k in range(0, len(entry)):
temp_credit = 0.00
temp_debit = 0.00
if entry[0].type <> 'view':
temp_credit+=entry[k].credit
temp_debit+=entry[k].debit
temp_credit += entry[k].credit
temp_debit += entry[k].debit
if self.flag==1:
self.result_total["sum_credit" + str(k)]=0.00
self.result_total["sum_debit" + str(k)]=0.00
if self.flag == 1:
self.result_total["sum_credit" + str(k)] = 0.00
self.result_total["sum_debit" + str(k)] = 0.00
if form['account_choice']=='bal_zero':
if temp_credit<>temp_debit:
self.result_total["sum_credit" + str(k)]+=temp_credit
self.result_total["sum_debit" + str(k)]+=temp_debit
if form['account_choice'] == 'bal_zero':
if temp_credit <> temp_debit:
self.result_total["sum_credit" + str(k)] += temp_credit
self.result_total["sum_debit" + str(k)] += temp_debit
else:
self.result_total["sum_credit" + str(k)]+=temp_credit
self.result_total["sum_debit" + str(k)]+=temp_debit
self.result_total["sum_credit" + str(k)] += temp_credit
self.result_total["sum_debit" + str(k)] += temp_debit
self.flag=2
self.flag = 2
if entry[0].child_id:
ids2 = [(x.code,x.id) for x in entry[0].child_id]
ids2 = [(x.code, x.id) for x in entry[0].child_id]
ids2.sort()
result_total_parent = self.linesForTotal(form, [x[1] for x in ids2],doneAccount,level+1)
result_total_parent = self.linesForTotal(form, [x[1] for x in ids2], doneAccount, level + 1)
return [self.result_total]
def lines(self, form, ids={}, done={}, level=1):
accounts=[]
accounts = []
if not ids:
ids = self.ids
if not ids:
return []
result = []
ctx = self.context.copy()
tmp1=[]
tmp1 = []
for id in form['fiscalyear'][0][2]:
ctx['fiscalyear'] = id
ctx['periods'] = form['periods'][0][2]
ctx['period_manner']=form['period_manner']
ctx['state'] = form['context'].get('state','all')
tmp1 = self.pool.get('account.account').browse(self.cr, self.uid, ids,ctx.copy())
ctx['period_manner'] = form['period_manner']
ctx['state'] = form['context'].get('state', 'all')
tmp1 = self.pool.get('account.account').browse(self.cr, self.uid, ids, ctx.copy())
if len(tmp1):
accounts.append(tmp1)
if level==1: #if parent is called,done is not empty when called again.
done={}
if level == 1: #if parent is called,done is not empty when called again.
done = {}
def cmp_code(x, y):
return cmp(x.code, y.code)
for n in range(0,len(accounts)):
for n in range(0, len(accounts)):
accounts[n].sort(cmp_code)
common={}
merged_accounts=zip(*accounts)
common = {}
merged_accounts = zip(*accounts)
for entry in merged_accounts:
j=0
checked=1
j = 0
checked = 1
if form['account_choice']!='all': # if checked,include empty a/c;not otherwise
checked=0
if form['account_choice'] != 'all': # if checked,include empty a/c;not otherwise
checked = 0
if entry[0].id in done:
continue
done[entry[0].id] = 1
if entry[0].child_id: # this is for parent account,dont check 0 for it
checked=4
self.status=1 # for displaying it Bold
checked = 4
self.status = 1 # for displaying it Bold
else:
self.status=0
if checked==0:
i=0
for i in range(0,len(entry)):
if bal_zero==0:
if entry[i].balance<>0.0:
checked=4
self.status = 0
if checked == 0:
i = 0
for i in range(0, len(entry)):
if bal_zero == 0:
if entry[i].balance <> 0.0:
checked = 4
break
else:
checked=3
i=i+1
checked = 3
i = i + 1
else:
if entry[i].credit <> 0.0 or entry[i].debit <> 0.0:
checked=4
checked = 4
break
else:
checked=3
i=i+1
checked = 3
i = i + 1
if checked==3:
if checked == 3:
# this is the point where we skip those accounts which are encountered as empty ones
continue
self.empty_parent=0
self.empty_parent = 0
else:
self.empty_parent=1
self.empty_parent = 1
res = {
'code': entry[0].code,
'name': entry[0].name,
@ -524,97 +524,97 @@ class account_balance_landscape(rml_parse.rml_parse):
'status': self.status,
}
for j in range(0,len(entry)):
for j in range(0, len(entry)):
locale.setlocale(locale.LC_ALL, '')
res["debit"+str(j)]=locale.format("%.2f", entry[j].debit, grouping=True)
res["credit"+str(j)]=locale.format("%.2f", entry[j].credit, grouping=True)
res["balance"+str(j)]=locale.format("%.2f", entry[j].balance, grouping=True)
res["debit" + str(j)] = locale.format("%.2f", entry[j].debit, grouping=True)
res["credit" + str(j)] = locale.format("%.2f", entry[j].credit, grouping=True)
res["balance" + str(j)] = locale.format("%.2f", entry[j].balance, grouping=True)
if j==0:
res["bal_cash"+str(j)]="0.00"
res["bal_perc"+str(j)]="0.00%"
if j == 0:
res["bal_cash" + str(j)] = "0.00"
res["bal_perc" + str(j)] = "0.00%"
else:
temp_cash=entry[j].balance - entry[j-1].balance
res["bal_cash"+str(j)]=locale.format("%.2f", temp_cash, grouping=True)
if entry[j-1].balance<>0.00:
temp_perc=(entry[j].balance - entry[j-1].balance )*100/entry[j-1].balance
temp_cash = entry[j].balance - entry[j - 1].balance
res["bal_cash" + str(j)] = locale.format("%.2f", temp_cash, grouping=True)
if entry[j - 1].balance <> 0.00:
temp_perc = (entry[j].balance - entry[j - 1].balance) * 100 / entry[j - 1].balance
else:
temp_perc=(entry[j].balance) *100
temp_perc = (entry[j].balance) * 100
res["bal_perc"+str(j)]=locale.format("%.2f", temp_perc) + "%"
res["bal_perc" + str(j)] = locale.format("%.2f", temp_perc) + "%"
if ref_bal=='nothing':
if level==1:
self.parent_bal=1
if ref_bal == 'nothing':
if level == 1:
self.parent_bal = 1
else:
self.parent_bal=0
self.parent_bal = 0
if self.parent_bal==1:
res["balance_perc"+str(j)]="/"
if self.parent_bal == 1:
res["balance_perc" + str(j)] = "/"
else:
if entry[j].balance==0.00:
if self.baldiv["baldiv"+str(level-1)+str(j)]<>0.00:
res["balance_perc"+str(j)]="0.00%"
if entry[j].balance == 0.00:
if self.baldiv["baldiv" + str(level - 1) + str(j)] <> 0.00:
res["balance_perc" + str(j)] = "0.00%"
else:
res["balance_perc"+str(j)]="/"
res["balance_perc" + str(j)] = "/"
else:
if self.baldiv["baldiv"+str(level-1)+str(j)]<>0.00:
temp=self.baldiv["baldiv"+str(level-1)+str(j)]
temp1=(entry[j].balance * 100 )/ float(temp)
temp1=round(temp1,2)
res["balance_perc" + str(j)]=str(temp1)+"%"
if self.baldiv["baldiv" + str(level - 1) + str(j)] <> 0.00:
temp = self.baldiv["baldiv" + str(level - 1) + str(j)]
temp1 = (entry[j].balance * 100) / float(temp)
temp1 = round(temp1, 2)
res["balance_perc" + str(j)] = str(temp1) + "%"
else:
res["balance_perc"+str(j)]="/"
res["balance_perc" + str(j)] = "/"
else:
res["balance_perc"+str(j)]=str( (entry[j].balance * 100 )/ float(ref_bal)) + "%"
res["balance_perc" + str(j)] = str((entry[j].balance * 100) / float(ref_bal)) + "%"
result.append(res)
if entry[0].child_id:
for q in range(0,len(form['fiscalyear'][0][2])):
self.baldiv["baldiv"+str(level)+str(q)]=entry[q].balance
for q in range(0, len(form['fiscalyear'][0][2])):
self.baldiv["baldiv" + str(level) + str(q)] = entry[q].balance
ids2 = [(x.code,x.id) for x in entry[0].child_id]
ids2 = [(x.code, x.id) for x in entry[0].child_id]
ids2.sort()
dir=[]
dir += self.lines(form, [x[1] for x in ids2], done, level+1)
if dir==[]:
for w in range(0,len(form['fiscalyear'][0][2])):
if entry[w].credit <> 0.0 or entry[w].debit <> 0.0 or entry[w].balance<>0.00:
dont_pop=1
dir = []
dir += self.lines(form, [x[1] for x in ids2], done, level + 1)
if dir == []:
for w in range(0, len(form['fiscalyear'][0][2])):
if entry[w].credit <> 0.0 or entry[w].debit <> 0.0 or entry[w].balance <> 0.00:
dont_pop = 1
break
else:
dont_pop=0
if dont_pop==1:
result +=dir
dont_pop = 0
if dont_pop == 1:
result += dir
else:
result.pop(-1) # here we pop up the parent having its children as emprty accounts
else:
result +=dir
result += dir
return result
def get_years(self,form):
result =[]
res={}
for temp in range(0,len(form['fiscalyear'][0][2])):
res={}
fy=self.pool.get('account.fiscalyear').name_get(self.cr,self.uid,form['fiscalyear'][0][2][temp])
res['year']=fy[0][1]
res['last_str']=temp
def get_years(self, form):
result = []
res = {}
for temp in range(0, len(form['fiscalyear'][0][2])):
res = {}
fy = self.pool.get('account.fiscalyear').name_get(self.cr, self.uid, form['fiscalyear'][0][2][temp])
res['year'] = fy[0][1]
res['last_str'] = temp
result.append(res)
self.linesForYear(form)
return result
def get_lines(self,year_dict,form):
def get_lines(self, year_dict, form):
final_result = []
line_l =[]
res = {}
line_l = []
res = {}
line_l = self.lines(form)
self.cal_total(year_dict)
if line_l:
@ -623,41 +623,41 @@ class account_balance_landscape(rml_parse.rml_parse):
res['code'] = l['code']
res['name'] = l['name']
res['level'] = l['level']
for k,v in l.items():
if k.startswith('debit'+str(year_dict['last_str'])):
res['debit'] = v
if k.startswith('credit'+str(year_dict['last_str'])):
for k, v in l.items():
if k.startswith('debit' + str(year_dict['last_str'])):
res['debit'] = v
if k.startswith('credit' + str(year_dict['last_str'])):
res['credit'] = v
if k.startswith('balance'+str(year_dict['last_str'])) and not k.startswith('balance_perc'+str(year_dict['last_str'])):
res['balance'] =v
if k.startswith('balance_perc'+str(year_dict['last_str'])) and not k.startswith('balance'+str(year_dict['last_str'])):
if k.startswith('balance' + str(year_dict['last_str'])) and not k.startswith('balance_perc' + str(year_dict['last_str'])):
res['balance'] = v
if k.startswith('balance_perc' + str(year_dict['last_str'])) and not k.startswith('balance' + str(year_dict['last_str'])):
res['balance_perc'] = v
if form['compare_pattern'] == 'bal_perc':
if k.startswith('bal_perc'+str(year_dict['last_str'])):
if k.startswith('bal_perc' + str(year_dict['last_str'])):
res['pattern'] = v
elif form['compare_pattern'] == 'bal_cash':
if k.startswith('bal_cash'+str(year_dict['last_str'])):
if k.startswith('bal_cash' + str(year_dict['last_str'])):
res['pattern'] = v
else:
res['pattern'] = ''
final_result.append(res)
return final_result
def cal_total(self,year_dict):
def cal_total(self, year_dict):
total_l = self.result_total
if total_l:
for k,v in total_l.items():
if k.startswith('sum_debit'+str(year_dict['last_str'])):
for k, v in total_l.items():
if k.startswith('sum_debit' + str(year_dict['last_str'])):
self.dr_total = v
elif k.startswith('sum_credit'+str(year_dict['last_str'])):
elif k.startswith('sum_credit' + str(year_dict['last_str'])):
self.cr_total = v
else:
continue
return True
def total_dr(self):
return self.dr_total
def total_cr(self):
return self.cr_total

View File

@ -40,12 +40,12 @@ class rml_parse(report_sxw.rml_parse):
'explode_name' : self._explode_name,
})
def comma_me(self,amount):
def comma_me(self, amount):
#print "#" + str(amount) + "#"
if not amount:
amount = 0.0
if type(amount) is float :
amount = str('%.2f'%amount)
amount = str('%.2f' % amount)
else :
amount = str(amount)
if (amount == '0'):
@ -56,31 +56,31 @@ class rml_parse(report_sxw.rml_parse):
return new
else:
return self.comma_me(new)
def _ellipsis(self, string, maxlen=100, ellipsis = '...'):
def _ellipsis(self, string, maxlen=100, ellipsis='...'):
ellipsis = ellipsis or ''
try:
return string[:maxlen - len(ellipsis) ] + (ellipsis, '')[len(string) < maxlen]
except Exception, e:
return False
def _strip_name(self, name, maxlen=50):
return self._ellipsis(name, maxlen, '...')
def _get_and_change_date_format_for_swiss (self,date_to_format):
date_formatted=''
def _get_and_change_date_format_for_swiss (self, date_to_format):
date_formatted = ''
if date_to_format:
date_formatted = strptime (date_to_format,'%Y-%m-%d').strftime('%d.%m.%Y')
date_formatted = strptime (date_to_format, '%Y-%m-%d').strftime('%d.%m.%Y')
return date_formatted
def _explode_name(self,chaine,length):
def _explode_name(self, chaine, length):
# We will test if the size is less then account
full_string = ''
if (len(str(chaine)) <= length):
return chaine
#
else:
chaine = unicode(chaine,'utf8').encode('iso-8859-1')
chaine = unicode(chaine, 'utf8').encode('iso-8859-1')
rup = 0
for carac in chaine:
rup = rup + 1
@ -93,7 +93,7 @@ class rml_parse(report_sxw.rml_parse):
return full_string
def makeAscii(self,str):
def makeAscii(self, str):
try:
Stringer = str.encode("utf-8")
except UnicodeDecodeError:
@ -107,19 +107,19 @@ class rml_parse(report_sxw.rml_parse):
else:
return Stringer
return Stringer
def explode_this(self,chaine,length):
def explode_this(self, chaine, length):
#chaine = self.repair_string(chaine)
chaine = rstrip(chaine)
ast = list(chaine)
i = length
while i <= len(ast):
ast.insert(i,'\n')
ast.insert(i, '\n')
i = i + length
chaine = str("".join(ast))
return chaine
def repair_string(self,chaine):
def repair_string(self, chaine):
ast = list(chaine)
UnicodeAst = []
_previouslyfound = False
@ -130,11 +130,11 @@ class rml_parse(report_sxw.rml_parse):
try:
Stringer = elem.encode("utf-8")
except UnicodeDecodeError:
to_reencode = elem + ast[i+1]
to_reencode = elem + ast[i + 1]
print str(to_reencode)
Good_char = to_reencode.decode('utf-8')
UnicodeAst.append(Good_char)
i += i +2
i += i + 2
else:
UnicodeAst.append(elem)
i += i + 1
@ -142,7 +142,7 @@ class rml_parse(report_sxw.rml_parse):
return "".join(UnicodeAst)
def ReencodeAscii(self,str):
def ReencodeAscii(self, str):
print sys.stdin.encoding
try:
Stringer = str.decode("ascii")
@ -156,13 +156,13 @@ class rml_parse(report_sxw.rml_parse):
else:
print Stringer
return Stringer
def _add_header(self, node, header=1):
if header==2:
rml_head = self.rml_header2
if header == 2:
rml_head = self.rml_header2
else:
rml_head = self.rml_header
rml_head = rml_head.replace('<pageGraphics>','''<pageGraphics> <image x="10" y="26cm" height="770.0" width="1120.0" >[[company.logo]] </image> ''')
rml_head = self.rml_header
rml_head = rml_head.replace('<pageGraphics>', '''<pageGraphics> <image x="10" y="26cm" height="770.0" width="1120.0" >[[company.logo]] </image> ''')
return True

View File

@ -57,17 +57,17 @@ dates_form = '''<?xml version="1.0"?>
dates_fields = {
'fiscalyear': {'string': 'Fiscal year', 'type': 'many2many', 'relation': 'account.fiscalyear'},
'select_account': {'string': 'Select Reference Account(for % comparision)', 'type': 'many2one', 'relation': 'account.account','help': 'Keep empty for comparision to its parent'},
'account_choice': {'string': 'Show Accounts', 'type': 'selection','selection':[('all','All accounts'),('bal_zero','With balance is not equal to 0'),('moves','With movements')]},
'select_account': {'string': 'Select Reference Account(for % comparision)', 'type': 'many2one', 'relation': 'account.account', 'help': 'Keep empty for comparision to its parent'},
'account_choice': {'string': 'Show Accounts', 'type': 'selection', 'selection':[('all', 'All accounts'), ('bal_zero', 'With balance is not equal to 0'), ('moves', 'With movements')]},
'show_columns': {'string': 'Show Debit/Credit Information', 'type': 'boolean'},
'landscape': {'string': 'Show Report in Landscape Form', 'type': 'boolean'},
'format_perc': {'string': 'Show Comparision in %', 'type': 'boolean'},
'compare_pattern':{'string':"Compare Selected Years In Terms Of",'type':'selection','selection':[('bal_cash','Cash'),('bal_perc','Percentage'),('none','Don'+ "'" +'t Compare')]},
'period_manner':{'string':"Entries Selection Based on",'type':'selection','selection':[('actual','Financial Period'),('created','Creation Date')]},
'compare_pattern':{'string':"Compare Selected Years In Terms Of", 'type':'selection', 'selection':[('bal_cash', 'Cash'), ('bal_perc', 'Percentage'), ('none', 'Don' + "'" + 't Compare')]},
'period_manner':{'string':"Entries Selection Based on", 'type':'selection', 'selection':[('actual', 'Financial Period'), ('created', 'Creation Date')]},
'periods': {'string': 'Periods', 'type': 'many2many', 'relation': 'account.period', 'help': 'All periods if empty'}
}
back_form='''<?xml version="1.0"?>
back_form = '''<?xml version="1.0"?>
<form string="Notification">
<separator string="You might have done following mistakes. Please correct them and try again." colspan="4"/>
<separator string="1. You have selected more than 3 years in any case." colspan="4"/>
@ -77,39 +77,39 @@ back_form='''<?xml version="1.0"?>
<label string="You have to select 'Landscape' option. Please Check it." colspan="4"/>
</form>'''
back_fields={
back_fields = {
}
zero_form='''<?xml version="1.0"?>
zero_form = '''<?xml version="1.0"?>
<form string="Notification">
<separator string="You have to select at least 1 Fiscal Year. Try again." colspan="4"/>
<label string="You may have selected the compare options with more than 1 year with credit/debit columns and % option.This can lead contents to be printed out of the paper.Please try again."/>
</form>'''
zero_fields={
zero_fields = {
}
def _check(self, cr, uid, data, context):
if (len(data['form']['fiscalyear'][0][2])==0) or (len(data['form']['fiscalyear'][0][2])>1 and (data['form']['compare_pattern']!='none') and (data['form']['format_perc']==1) and (data['form']['show_columns']==1) and (data['form']['landscape']!=1)):
if (len(data['form']['fiscalyear'][0][2]) == 0) or (len(data['form']['fiscalyear'][0][2]) > 1 and (data['form']['compare_pattern'] != 'none') and (data['form']['format_perc'] == 1) and (data['form']['show_columns'] == 1) and (data['form']['landscape'] != 1)):
return 'zero_years'
if ((len(data['form']['fiscalyear'][0][2])==3) and (data['form']['format_perc']!=1) and (data['form']['show_columns']!=1)):
if data['form']['landscape']==1:
if ((len(data['form']['fiscalyear'][0][2]) == 3) and (data['form']['format_perc'] != 1) and (data['form']['show_columns'] != 1)):
if data['form']['landscape'] == 1:
return 'report_landscape'
else:
return 'report'
if data['form']['format_perc']==1:
if len(data['form']['fiscalyear'][0][2])<=2:
if data['form']['landscape']==1:
if data['form']['format_perc'] == 1:
if len(data['form']['fiscalyear'][0][2]) <= 2:
if data['form']['landscape'] == 1:
return 'report_landscape'
else:
return 'report'
else:
if len(data['form']['fiscalyear'][0][2])==3:
if data['form']['landscape']==1:
if len(data['form']['fiscalyear'][0][2]) == 3:
if data['form']['landscape'] == 1:
return 'report_landscape'
else:
return 'backtoinit'
@ -117,13 +117,13 @@ def _check(self, cr, uid, data, context):
return 'backtoinit'
else:
if len(data['form']['fiscalyear'][0][2])>2:
if data['form']['landscape']==1:
if len(data['form']['fiscalyear'][0][2]) > 2:
if data['form']['landscape'] == 1:
return 'report_landscape'
else:
return 'backtoinit'
else:
if data['form']['landscape']==1:
if data['form']['landscape'] == 1:
return 'report_landscape'
else:
return 'report'
@ -135,31 +135,31 @@ class wizard_report(wizard.interface):
def _get_defaults(self, cr, uid, data, context={}):
data['form']['context'] = context
fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
data['form']['fiscalyear']=[fiscalyear_obj.find(cr, uid)]
data['form']['fiscalyear'] = [fiscalyear_obj.find(cr, uid)]
# p_ids=pooler.get_pool(cr.dbname).get('account.period').search(cr,uid,[('fiscalyear_id','=',fiscalyear_obj.find(cr, uid))])
# data['form']['periods']=p_ids
data['form']['compare_pattern']='none'
data['form']['account_choice']='moves'
data['form']['period_manner']='actual'
data['form']['compare_pattern'] = 'none'
data['form']['account_choice'] = 'moves'
data['form']['period_manner'] = 'actual'
return data['form']
states = {
'init': {
'actions': [_get_defaults],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('checkyear','Print')]}
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('checkyear', 'Print')]}
},
'backtoinit': {
'actions': [],
'result': {'type':'form','arch':back_form,'fields':back_fields,'state':[('end','Ok')]}
'result': {'type':'form', 'arch':back_form, 'fields':back_fields, 'state':[('end', 'Ok')]}
},
'zero_years': {
'actions': [],
'result': {'type':'form','arch':zero_form,'fields':zero_fields,'state':[('end','Ok')]}
'result': {'type':'form', 'arch':zero_form, 'fields':zero_fields, 'state':[('end', 'Ok')]}
},
'checkyear': {
'actions': [],
'result': {'type':'choice','next_state':_check}
'result': {'type':'choice', 'next_state':_check}
},
'report_landscape': {
'actions': [],

View File

@ -19,7 +19,7 @@
#
##############################################################################
from osv import osv,fields
from osv import osv, fields
import tools
import netsvc
from mx import DateTime
@ -29,7 +29,7 @@ from tools.translate import _
def strToDate(dt):
dt_date=datetime.date(int(dt[0:4]),int(dt[5:7]),int(dt[8:10]))
dt_date = datetime.date(int(dt[0:4]), int(dt[5:7]), int(dt[8:10]))
return dt_date
# ---------------------------------------------------------
@ -45,11 +45,11 @@ class account_budget_post(osv.osv):
'account_ids': fields.many2many('account.account', 'account_budget_rel', 'budget_id', 'account_id', 'Accounts'),
'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'general_budget_id', 'Budget Lines'),
'company_id': fields.many2one('res.company', 'Company', required=True),
'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of budgetary position."),
'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of budgetary position."),
}
_defaults = {
'sequence': lambda *a: 1,
'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.budget.post', context=c)
'sequence': lambda * a: 1,
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.budget.post', context=c)
}
_order = "sequence, name"
@ -57,42 +57,42 @@ class account_budget_post(osv.osv):
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)]))
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})
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):
def _tot_planned(self, cr, uid, ids,name,args,context):
res={}
def _tot_planned(self, cr, uid, ids, name, args, context):
res = {}
for line in self.browse(cr, uid, ids):
if line.period_id:
obj_period=self.pool.get('account.period').browse(cr, uid,line.period_id.id)
obj_period = self.pool.get('account.period').browse(cr, uid, line.period_id.id)
total_days=strToDate(obj_period.date_stop) - strToDate(obj_period.date_start)
budget_id=line.post_id and line.post_id.id or False
query="select id from crossovered_budget_lines where \
total_days = strToDate(obj_period.date_stop) - strToDate(obj_period.date_start)
budget_id = line.post_id and line.post_id.id or False
query = "select id from crossovered_budget_lines where \
general_budget_id= %s AND (date_from >=%s and date_from <= %s ) \
OR (date_to >=%s and date_to <= %s) OR (date_from < %s and date_to > %s)"
cr.execute(query,(budget_id,obj_period.date_start,obj_period.date_stop,obj_period.date_start,obj_period.date_stop,obj_period.date_start,obj_period.date_stop,))
res1=cr.fetchall()
cr.execute(query, (budget_id, obj_period.date_start, obj_period.date_stop, obj_period.date_start, obj_period.date_stop, obj_period.date_start, obj_period.date_stop,))
res1 = cr.fetchall()
tot_planned=0.00
tot_planned = 0.00
for record in res1:
obj_lines = self.pool.get('crossovered.budget.lines').browse(cr, uid,record[0])
count_days = min(strToDate(obj_period.date_stop),strToDate(obj_lines.date_to)) - max(strToDate(obj_period.date_start), strToDate(obj_lines.date_from))
days_in_period = count_days.days +1
obj_lines = self.pool.get('crossovered.budget.lines').browse(cr, uid, record[0])
count_days = min(strToDate(obj_period.date_stop), strToDate(obj_lines.date_to)) - max(strToDate(obj_period.date_start), strToDate(obj_lines.date_from))
days_in_period = count_days.days + 1
count_days = strToDate(obj_lines.date_to) - strToDate(obj_lines.date_from)
total_days_of_rec = count_days.days +1
tot_planned += obj_lines.planned_amount/total_days_of_rec* days_in_period
res[line.id]=tot_planned
total_days_of_rec = count_days.days + 1
tot_planned += obj_lines.planned_amount / total_days_of_rec * days_in_period
res[line.id] = tot_planned
else:
res[line.id]=0.00
res[line.id] = 0.00
return res
_name = 'account.budget.post.dotation'
@ -101,8 +101,8 @@ class account_budget_post_dotation(osv.osv):
'name': fields.char('Name', size=64),
'post_id': fields.many2one('account.budget.post', 'Item', select=True),
'period_id': fields.many2one('account.period', 'Period'),
'amount': fields.float('Amount', digits=(16,2)),
'tot_planned':fields.function(_tot_planned,method=True, string='Total Planned Amount',type='float',store=True),
'amount': fields.float('Amount', digits=(16, 2)),
'tot_planned':fields.function(_tot_planned, method=True, string='Total Planned Amount', type='float', store=True),
}
account_budget_post_dotation()
@ -112,19 +112,19 @@ class crossovered_budget(osv.osv):
_description = "Budget"
_columns = {
'name': fields.char('Name', size=50, required=True,states={'done':[('readonly',True)]}),
'code': fields.char('Code', size=20, required=True,states={'done':[('readonly',True)]}),
'creating_user_id': fields.many2one('res.users','Responsible User'),
'validating_user_id': fields.many2one('res.users','Validate User', readonly=True),
'date_from': fields.date('Start Date',required=True,states={'done':[('readonly',True)]}),
'date_to': fields.date('End Date',required=True,states={'done':[('readonly',True)]}),
'state' : fields.selection([('draft','Draft'),('confirm','Confirmed'),('validate','Validated'),('done','Done'),('cancel', 'Cancelled')], 'Status', select=True, required=True, readonly=True),
'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'crossovered_budget_id', 'Budget Lines',states={'done':[('readonly',True)]} ),
'name': fields.char('Name', size=50, required=True, states={'done':[('readonly', True)]}),
'code': fields.char('Code', size=20, required=True, states={'done':[('readonly', True)]}),
'creating_user_id': fields.many2one('res.users', 'Responsible User'),
'validating_user_id': fields.many2one('res.users', 'Validate User', readonly=True),
'date_from': fields.date('Start Date', required=True, states={'done':[('readonly', True)]}),
'date_to': fields.date('End Date', required=True, states={'done':[('readonly', True)]}),
'state' : fields.selection([('draft', 'Draft'), ('confirm', 'Confirmed'), ('validate', 'Validated'), ('done', 'Done'), ('cancel', 'Cancelled')], 'Status', select=True, required=True, readonly=True),
'crossovered_budget_line': fields.one2many('crossovered.budget.lines', 'crossovered_budget_id', 'Budget Lines', states={'done':[('readonly', True)]}),
}
_defaults = {
'state': lambda *a: 'draft',
'creating_user_id': lambda self,cr,uid,context: uid,
'state': lambda * a: 'draft',
'creating_user_id': lambda self, cr, uid, context: uid,
}
# def action_set_to_draft(self, cr, uid, ids, *args):
@ -164,12 +164,12 @@ crossovered_budget()
class crossovered_budget_lines(osv.osv):
def _prac_amt(self, cr, uid, ids,context={}):
def _prac_amt(self, cr, uid, ids, context={}):
res = {}
for line in self.browse(cr, uid, ids):
acc_ids = [x.id for x in line.general_budget_id.account_ids]
if not acc_ids:
raise osv.except_osv(_('Error!'),_("The General Budget '%s' has no Accounts!") % str(line.general_budget_id.name))
raise osv.except_osv(_('Error!'), _("The General Budget '%s' has no Accounts!") % str(line.general_budget_id.name))
date_to = line.date_to
date_from = line.date_from
@ -179,24 +179,24 @@ class crossovered_budget_lines(osv.osv):
date_to = context['wizard_date_to']
cr.execute("select sum(amount) from account_analytic_line where account_id=%s and (date "
"between to_date(%s,'yyyy-mm-dd') and to_date(%s,'yyyy-mm-dd')) and "
"general_account_id=ANY(%s)", (line.analytic_account_id.id, date_from, date_to,acc_ids,))
"general_account_id=ANY(%s)", (line.analytic_account_id.id, date_from, date_to, acc_ids,))
result = cr.fetchone()[0]
if result is None:
result = 0.00
res[line.id] = result
return res
def _prac(self, cr, uid, ids,name,args,context):
res={}
def _prac(self, cr, uid, ids, name, args, context):
res = {}
for line in self.browse(cr, uid, ids):
res[line.id]=self._prac_amt(cr,uid,[line.id],context=context)[line.id]
res[line.id] = self._prac_amt(cr, uid, [line.id], context=context)[line.id]
return res
def _theo_amt(self, cr, uid, ids,context={}):
def _theo_amt(self, cr, uid, ids, context={}):
res = {}
for line in self.browse(cr, uid, ids):
today=datetime.datetime.today()
today = datetime.datetime.today()
date_to = today.strftime("%Y-%m-%d")
date_from = line.date_from
if context.has_key('wizard_date_from'):
@ -205,52 +205,52 @@ class crossovered_budget_lines(osv.osv):
date_to = context['wizard_date_to']
if line.paid_date:
if strToDate(line.date_to)<=strToDate(line.paid_date):
theo_amt=0.00
if strToDate(line.date_to) <= strToDate(line.paid_date):
theo_amt = 0.00
else:
theo_amt=line.planned_amount
theo_amt = line.planned_amount
else:
total=strToDate(line.date_to) - strToDate(line.date_from)
elapsed = min(strToDate(line.date_to),strToDate(date_to)) - max(strToDate(line.date_from),strToDate(date_from))
total = strToDate(line.date_to) - strToDate(line.date_from)
elapsed = min(strToDate(line.date_to), strToDate(date_to)) - max(strToDate(line.date_from), strToDate(date_from))
if strToDate(date_to) < strToDate(line.date_from):
elapsed = strToDate(date_to) - strToDate(date_to)
if total.days:
theo_amt = float(elapsed.days/float(total.days))*line.planned_amount
theo_amt = float(elapsed.days / float(total.days)) * line.planned_amount
else:
theo_amt = line.planned_amount
res[line.id]=theo_amt
res[line.id] = theo_amt
return res
def _theo(self, cr, uid, ids,name,args,context):
res={}
for line in self.browse(cr, uid, ids):
res[line.id]=self._theo_amt(cr,uid,[line.id],context=context)[line.id]
return res
def _perc(self, cr, uid, ids,name,args,context):
def _theo(self, cr, uid, ids, name, args, context):
res = {}
for line in self.browse(cr, uid, ids):
if line.theoritical_amount<>0.00:
res[line.id]=float(line.practical_amount or 0.0 / line.theoritical_amount)*100
else:
res[line.id]=0.00
res[line.id] = self._theo_amt(cr, uid, [line.id], context=context)[line.id]
return res
_name="crossovered.budget.lines"
def _perc(self, cr, uid, ids, name, args, context):
res = {}
for line in self.browse(cr, uid, ids):
if line.theoritical_amount <> 0.00:
res[line.id] = float(line.practical_amount or 0.0 / line.theoritical_amount) * 100
else:
res[line.id] = 0.00
return res
_name = "crossovered.budget.lines"
_description = "Budget Lines"
_columns = {
'crossovered_budget_id': fields.many2one('crossovered.budget', 'Budget', ondelete='cascade', select=True, required=True),
'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account',required=True),
'general_budget_id': fields.many2one('account.budget.post', 'Budgetary Position',required=True),
'date_from': fields.date('Start Date',required=True),
'date_to': fields.date('End Date',required=True),
'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account', required=True),
'general_budget_id': fields.many2one('account.budget.post', 'Budgetary Position', required=True),
'date_from': fields.date('Start Date', required=True),
'date_to': fields.date('End Date', required=True),
'paid_date': fields.date('Paid Date'),
'planned_amount':fields.float('Planned Amount',required=True,digits=(16,2)),
'practical_amount':fields.function(_prac,method=True, string='Practical Amount',type='float',digits=(16,2)),
'theoritical_amount':fields.function(_theo,method=True, string='Theoritical Amount',type='float',digits=(16,2)),
'percentage':fields.function(_perc,method=True, string='Percentage',type='float'),
'planned_amount':fields.float('Planned Amount', required=True, digits=(16, 2)),
'practical_amount':fields.function(_prac, method=True, string='Practical Amount', type='float', digits=(16, 2)),
'theoritical_amount':fields.function(_theo, method=True, string='Theoritical Amount', type='float', digits=(16, 2)),
'percentage':fields.function(_perc, method=True, string='Percentage', type='float'),
}
crossovered_budget_lines()

View File

@ -27,37 +27,37 @@ import datetime
class analytic_account_budget_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(analytic_account_budget_report, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
self.localcontext.update({
'funct': self.funct,
'funct_total': self.funct_total,
'time': time,
})
self.context=context
self.context = context
def funct(self,object,form,ids={}, done=None, level=1):
def funct(self, object, form, ids={}, done=None, level=1):
if not ids:
ids = self.ids
# if not ids:
# return []
if not done:
done={}
done = {}
global tot
tot={
tot = {
'theo':0.00,
'pln':0.00,
'prac':0.00,
'perc':0.00
}
result=[]
result = []
accounts = self.pool.get('account.analytic.account').browse(self.cr, self.uid, [object.id], self.context.copy())
c_b_lines_obj=self.pool.get('crossovered.budget.lines')
c_b_lines_obj = self.pool.get('crossovered.budget.lines')
for account_id in accounts:
res={}
b_line_ids=[]
res = {}
b_line_ids = []
for line in account_id.crossovered_budget_line:
b_line_ids.append(line.id)
@ -65,18 +65,18 @@ class analytic_account_budget_report(report_sxw.rml_parse):
if not b_line_ids:
return []
d_from=form['date_from']
d_to=form['date_to']
d_from = form['date_from']
d_to = form['date_to']
# bd_ids = ','.join([str(x) for x in budget_lines])
self.cr.execute('select distinct(crossovered_budget_id) from crossovered_budget_lines where id =ANY(%s)',(b_line_ids,))
budget_ids=self.cr.fetchall()
self.cr.execute('select distinct(crossovered_budget_id) from crossovered_budget_lines where id =ANY(%s)', (b_line_ids,))
budget_ids = self.cr.fetchall()
context={'wizard_date_from':d_from,'wizard_date_to':d_to}
for i in range(0,len(budget_ids)):
context = {'wizard_date_from':d_from, 'wizard_date_to':d_to}
for i in range(0, len(budget_ids)):
budget_name=self.pool.get('crossovered.budget').browse(self.cr, self.uid,[budget_ids[i][0]])
res={
budget_name = self.pool.get('crossovered.budget').browse(self.cr, self.uid, [budget_ids[i][0]])
res = {
'b_id':'-1',
'a_id':'-1',
'name':budget_name[0].name,
@ -88,34 +88,34 @@ class analytic_account_budget_report(report_sxw.rml_parse):
}
result.append(res)
line_ids = c_b_lines_obj.search(self.cr, self.uid, [('id', 'in', b_line_ids),('crossovered_budget_id','=',budget_ids[i][0])])
line_id =c_b_lines_obj.browse(self.cr,self.uid,line_ids)
tot_theo=tot_pln=tot_prac=tot_perc=0
line_ids = c_b_lines_obj.search(self.cr, self.uid, [('id', 'in', b_line_ids), ('crossovered_budget_id', '=', budget_ids[i][0])])
line_id = c_b_lines_obj.browse(self.cr, self.uid, line_ids)
tot_theo = tot_pln = tot_prac = tot_perc = 0
done_budget=[]
done_budget = []
for line in line_id:
if line.id in b_line_ids:
theo=pract=0.00
theo=c_b_lines_obj._theo_amt(self.cr, self.uid, [line.id],context)[line.id]
pract=c_b_lines_obj._prac_amt(self.cr, self.uid, [line.id],context)[line.id]
theo = pract = 0.00
theo = c_b_lines_obj._theo_amt(self.cr, self.uid, [line.id], context)[line.id]
pract = c_b_lines_obj._prac_amt(self.cr, self.uid, [line.id], context)[line.id]
if line.general_budget_id.id in done_budget:
for record in result:
if record['b_id']==line.general_budget_id.id and record['a_id']==line.analytic_account_id.id:
if record['b_id'] == line.general_budget_id.id and record['a_id'] == line.analytic_account_id.id:
record['theo'] +=theo
record['pln'] +=line.planned_amount
record['prac'] +=pract
record['perc'] +=line.percentage
tot_theo +=theo
tot_pln +=line.planned_amount
tot_prac +=pract
tot_perc +=line.percentage
record['theo'] += theo
record['pln'] += line.planned_amount
record['prac'] += pract
record['perc'] += line.percentage
tot_theo += theo
tot_pln += line.planned_amount
tot_prac += pract
tot_perc += line.percentage
else:
res1={
res1 = {
'b_id':line.general_budget_id.id,
'a_id':line.analytic_account_id.id,
'name':line.general_budget_id.name,
@ -127,16 +127,16 @@ class analytic_account_budget_report(report_sxw.rml_parse):
}
tot_theo += theo
tot_pln +=line.planned_amount
tot_prac +=pract
tot_perc +=line.percentage
tot_pln += line.planned_amount
tot_prac += pract
tot_perc += line.percentage
result.append(res1)
done_budget.append(line.general_budget_id.id)
else:
if line.general_budget_id.id in done_budget:
continue
else:
res1={
res1 = {
'b_id':line.general_budget_id.id,
'a_id':line.analytic_account_id.id,
'name':line.general_budget_id.name,
@ -150,30 +150,30 @@ class analytic_account_budget_report(report_sxw.rml_parse):
result.append(res1)
done_budget.append(line.general_budget_id.id)
if tot_theo==0.00:
tot_perc=0.00
if tot_theo == 0.00:
tot_perc = 0.00
else:
tot_perc=float(tot_prac /tot_theo)*100
tot_perc = float(tot_prac / tot_theo) * 100
result[-(len(done_budget) +1)]['theo']=tot_theo
tot['theo'] +=tot_theo
result[-(len(done_budget) +1)]['pln']=tot_pln
tot['pln'] +=tot_pln
result[-(len(done_budget) +1)]['prac']=tot_prac
tot['prac'] +=tot_prac
result[-(len(done_budget) +1)]['perc']=tot_perc
result[-(len(done_budget) + 1)]['theo'] = tot_theo
tot['theo'] += tot_theo
result[-(len(done_budget) + 1)]['pln'] = tot_pln
tot['pln'] += tot_pln
result[-(len(done_budget) + 1)]['prac'] = tot_prac
tot['prac'] += tot_prac
result[-(len(done_budget) + 1)]['perc'] = tot_perc
if tot['theo']==0.00:
tot['perc'] =0.00
if tot['theo'] == 0.00:
tot['perc'] = 0.00
else:
tot['perc']=float(tot['prac'] /tot['theo'])*100
tot['perc'] = float(tot['prac'] / tot['theo']) * 100
return result
def funct_total(self,form):
result=[]
res={}
res={
def funct_total(self, form):
result = []
res = {}
res = {
'tot_theo':tot['theo'],
'tot_pln':tot['pln'],
'tot_prac':tot['prac'],
@ -183,6 +183,6 @@ class analytic_account_budget_report(report_sxw.rml_parse):
return result
report_sxw.report_sxw('report.account.analytic.account.budget', 'account.analytic.account', 'addons/account_budget/report/analytic_account_budget_report.rml',parser=analytic_account_budget_report,header=False)
report_sxw.report_sxw('report.account.analytic.account.budget', 'account.analytic.account', 'addons/account_budget/report/analytic_account_budget_report.rml', parser=analytic_account_budget_report, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -27,7 +27,7 @@ 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=context)
self.localcontext.update( {
self.localcontext.update({
'lines': self.lines,
'budget_total': self.budget_total,
'post_total': self.post_total,
@ -39,15 +39,15 @@ class budget_report(report_sxw.rml_parse):
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)
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)
prev_1=1.00
if total_days<>0.00:
prev_1=prev * period_days / total_days
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)
prev_1 = 1.00
if total_days <> 0.00:
prev_1 = prev * period_days / total_days
return [{'prev': prev, 'prev_period': prev_1, 'achievements': achievements}]
def budget_total(self, post_obj, date1, date2):
@ -64,7 +64,7 @@ class budget_report(report_sxw.rml_parse):
achievements = float(self.cr.fetchone()[0])
res.append({'name': a.name, 'code': a.code, 'achievements': achievements})
return res
report_sxw.report_sxw('report.account.budget', 'account.budget.post', 'addons/account_budget/report/budget_report.rml',parser=budget_report,header=False)
report_sxw.report_sxw('report.account.budget', 'account.budget.post', 'addons/account_budget/report/budget_report.rml', parser=budget_report, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -29,41 +29,41 @@ import osv
class budget_report(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(budget_report, self).__init__(cr, uid, name, context=context)
self.localcontext.update( {
self.localcontext.update({
'funct': self.funct,
'funct_total': self.funct_total,
'time': time,
})
self.context=context
self.context = context
def funct(self,object,form,ids={}, done=None, level=1):
def funct(self, object, form, ids={}, done=None, level=1):
if not ids:
ids = self.ids
# if not ids:
# return []
if not done:
done={}
done = {}
global tot
tot={
tot = {
'theo':0.00,
'pln':0.00,
'prac':0.00,
'perc':0.00
}
result=[]
result = []
budgets = self.pool.get('crossovered.budget').browse(self.cr, self.uid, [object.id], self.context.copy())
c_b_lines_obj=self.pool.get('crossovered.budget.lines')
c_b_lines_obj = self.pool.get('crossovered.budget.lines')
for budget_id in budgets:
res={}
budget_lines=[]
budget_ids=[]
d_from=form['date_from']
d_to=form['date_to']
res = {}
budget_lines = []
budget_ids = []
d_from = form['date_from']
d_to = form['date_to']
for line in budget_id.crossovered_budget_line:
budget_ids.append(line.id)
@ -72,15 +72,15 @@ class budget_report(report_sxw.rml_parse):
return []
# bd_ids = ','.join([str(x) for x in budget_lines])
self.cr.execute('select distinct(analytic_account_id) from crossovered_budget_lines where id =ANY(%s)',(budget_ids,))
an_ids=self.cr.fetchall()
self.cr.execute('select distinct(analytic_account_id) from crossovered_budget_lines where id =ANY(%s)', (budget_ids,))
an_ids = self.cr.fetchall()
context={'wizard_date_from':d_from,'wizard_date_to':d_to}
for i in range(0,len(an_ids)):
context = {'wizard_date_from':d_from, 'wizard_date_to':d_to}
for i in range(0, len(an_ids)):
analytic_name=self.pool.get('account.analytic.account').browse(self.cr, self.uid,[an_ids[i][0]])
analytic_name = self.pool.get('account.analytic.account').browse(self.cr, self.uid, [an_ids[i][0]])
res={
res = {
'b_id':'-1',
'a_id':'-1',
'name':analytic_name[0].name,
@ -92,44 +92,44 @@ class budget_report(report_sxw.rml_parse):
}
result.append(res)
line_ids = c_b_lines_obj.search(self.cr, self.uid, [('id', 'in', budget_ids),('analytic_account_id','=',an_ids[i][0])])
line_ids = c_b_lines_obj.search(self.cr, self.uid, [('id', 'in', budget_ids), ('analytic_account_id', '=', an_ids[i][0])])
line_id = c_b_lines_obj.browse(self.cr,self.uid,line_ids)
tot_theo=tot_pln=tot_prac=tot_perc=0.00
line_id = c_b_lines_obj.browse(self.cr, self.uid, line_ids)
tot_theo = tot_pln = tot_prac = tot_perc = 0.00
done_budget=[]
done_budget = []
for line in line_id:
if line.id in budget_ids:
theo=pract=0.00
theo=c_b_lines_obj._theo_amt(self.cr, self.uid, [line.id],context)[line.id]
pract=c_b_lines_obj._prac_amt(self.cr, self.uid, [line.id],context)[line.id]
theo = pract = 0.00
theo = c_b_lines_obj._theo_amt(self.cr, self.uid, [line.id], context)[line.id]
pract = c_b_lines_obj._prac_amt(self.cr, self.uid, [line.id], context)[line.id]
if line.general_budget_id.id in done_budget:
for record in result:
if record['b_id']==line.general_budget_id.id and record['a_id']==line.analytic_account_id.id:
if record['b_id'] == line.general_budget_id.id and record['a_id'] == line.analytic_account_id.id:
record['theo'] +=theo
record['pln'] +=line.planned_amount
record['prac'] +=pract
if record['theo']<>0.00:
perc=(record['prac']/record['theo'])*100
record['theo'] += theo
record['pln'] += line.planned_amount
record['prac'] += pract
if record['theo'] <> 0.00:
perc = (record['prac'] / record['theo']) * 100
else:
perc=0.00
record['perc'] =perc
perc = 0.00
record['perc'] = perc
tot_theo += theo
tot_pln +=line.planned_amount
tot_prac +=pract
tot_perc +=perc
tot_pln += line.planned_amount
tot_prac += pract
tot_perc += perc
else:
if theo<>0.00:
perc=(pract/theo)*100
if theo <> 0.00:
perc = (pract / theo) * 100
else:
perc=0.00
res1={
perc = 0.00
res1 = {
'a_id':line.analytic_account_id.id,
'b_id':line.general_budget_id.id,
'name':line.general_budget_id.name,
@ -140,10 +140,10 @@ class budget_report(report_sxw.rml_parse):
'perc':perc,
}
tot_theo += theo
tot_pln +=line.planned_amount
tot_prac +=pract
tot_perc +=perc
if form['report']=='analytic-full':
tot_pln += line.planned_amount
tot_prac += pract
tot_perc += perc
if form['report'] == 'analytic-full':
result.append(res1)
done_budget.append(line.general_budget_id.id)
else:
@ -151,7 +151,7 @@ class budget_report(report_sxw.rml_parse):
if line.general_budget_id.id in done_budget:
continue
else:
res1={
res1 = {
'a_id':line.analytic_account_id.id,
'b_id':line.general_budget_id.id,
'name':line.general_budget_id.name,
@ -162,43 +162,43 @@ class budget_report(report_sxw.rml_parse):
'perc':0.00
}
if form['report']=='analytic-full':
if form['report'] == 'analytic-full':
result.append(res1)
done_budget.append(line.general_budget_id.id)
if tot_theo==0.00:
tot_perc=0.00
if tot_theo == 0.00:
tot_perc = 0.00
else:
tot_perc=float(tot_prac /tot_theo)*100
tot_perc = float(tot_prac / tot_theo) * 100
if form['report']=='analytic-full':
if form['report'] == 'analytic-full':
result[-(len(done_budget) +1)]['theo']=tot_theo
tot['theo'] +=tot_theo
result[-(len(done_budget) +1)]['pln']=tot_pln
tot['pln'] +=tot_pln
result[-(len(done_budget) +1)]['prac']=tot_prac
tot['prac'] +=tot_prac
result[-(len(done_budget) +1)]['perc']=tot_perc
result[-(len(done_budget) + 1)]['theo'] = tot_theo
tot['theo'] += tot_theo
result[-(len(done_budget) + 1)]['pln'] = tot_pln
tot['pln'] += tot_pln
result[-(len(done_budget) + 1)]['prac'] = tot_prac
tot['prac'] += tot_prac
result[-(len(done_budget) + 1)]['perc'] = tot_perc
else:
result[-1]['theo']=tot_theo
tot['theo'] +=tot_theo
result[-1]['pln']=tot_pln
tot['pln'] +=tot_pln
result[-1]['prac']=tot_prac
tot['prac'] +=tot_prac
result[-1]['perc']=tot_perc
if tot['theo']==0.00:
tot['perc'] =0.00
result[-1]['theo'] = tot_theo
tot['theo'] += tot_theo
result[-1]['pln'] = tot_pln
tot['pln'] += tot_pln
result[-1]['prac'] = tot_prac
tot['prac'] += tot_prac
result[-1]['perc'] = tot_perc
if tot['theo'] == 0.00:
tot['perc'] = 0.00
else:
tot['perc']=float(tot['prac'] /tot['theo'])*100
tot['perc'] = float(tot['prac'] / tot['theo']) * 100
return result
def funct_total(self,form):
result=[]
res={}
def funct_total(self, form):
result = []
res = {}
res={
res = {
'tot_theo':tot['theo'],
'tot_pln':tot['pln'],
'tot_prac':tot['prac'],
@ -208,6 +208,6 @@ class budget_report(report_sxw.rml_parse):
return result
report_sxw.report_sxw('report.crossovered.budget.report', 'crossovered.budget', 'addons/account_budget/report/crossovered_budget_report.rml',parser=budget_report,header=False)
report_sxw.report_sxw('report.crossovered.budget.report', 'crossovered.budget', 'addons/account_budget/report/crossovered_budget_report.rml', parser=budget_report, header=False)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -29,8 +29,8 @@ dates_form = '''<?xml version="1.0"?>
</form>'''
dates_fields = {
'date_from': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')},
'date_to': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')}
'date_from': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-01-01')},
'date_to': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')}
}
class wizard_report(wizard.interface):
@ -38,7 +38,7 @@ class wizard_report(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]}
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -32,22 +32,22 @@ dates_form = '''<?xml version="1.0"?>
</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):
def _default(self, cr, uid, data, context):
pool_obj = pooler.get_pool(cr.dbname)
data_model = pool_obj.get(data['model']).browse(cr,uid,data['id'])
data_model = pool_obj.get(data['model']).browse(cr, uid, data['id'])
if not data_model.dotation_ids:
raise wizard.except_wizard(_('Insufficient Data!'),_('No Depreciation or Master Budget Expenses Found on Budget %s!') % data_model.name)
raise wizard.except_wizard(_('Insufficient Data!'), _('No Depreciation or Master Budget Expenses Found on Budget %s!') % data_model.name)
return data['form']
states = {
'init': {
'actions': [_default],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]}
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -30,7 +30,7 @@ _spread_form = '''<?xml version="1.0"?>
_spread_fields = {
'fiscalyear': {'string':'Fiscal Year', 'type':'many2one', 'relation':'account.fiscalyear', 'required':True},
'amount': {'string':'Amount', 'type':'float', 'digits':(16,2)},
'amount': {'string':'Amount', 'type':'float', 'digits':(16, 2)},
}
class wizard_budget_spread(wizard.interface):
@ -43,7 +43,7 @@ class wizard_budget_spread(wizard.interface):
states = {
'init': {
'actions': [],
'result': {'type':'form', 'arch':_spread_form, 'fields':_spread_fields, 'state':[('end','Cancel'),('spread','Spread')]}
'result': {'type':'form', 'arch':_spread_form, 'fields':_spread_fields, 'state':[('end', 'Cancel'), ('spread', 'Spread')]}
},
'spread': {
'actions': [_spread],

View File

@ -29,21 +29,21 @@ dates_form = '''<?xml version="1.0"?>
</form>'''
dates_fields = {
'date_from': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')},
'date_to': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')},
'date_from': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-01-01')},
'date_to': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')},
}
class wizard_report(wizard.interface):
def _default(self, cr, uid, data, context):
data['form']['report']='analytic-full'
data['form']['report'] = 'analytic-full'
return data['form']
states = {
'init': {
'actions': [_default],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]}
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -29,20 +29,20 @@ dates_form = '''<?xml version="1.0"?>
</form>'''
dates_fields = {
'date_from': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-01-01')},
'date_to': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda *a: time.strftime('%Y-%m-%d')},
'date_from': {'string':'Start of period', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-01-01')},
'date_to': {'string':'End of period', 'type':'date', 'required':True, 'default': lambda * a: time.strftime('%Y-%m-%d')},
}
class wizard_report_summary(wizard.interface):
def _default(self, cr, uid, data, context):
data['form']['report']='analytic-one'
data['form']['report'] = 'analytic-one'
return data['form']
states = {
'init': {
'actions': [_default],
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end','Cancel'),('report','Print')]}
'result': {'type':'form', 'arch':dates_form, 'fields':dates_fields, 'state':[('end', 'Cancel'), ('report', 'Print')]}
},
'report': {
'actions': [],

View File

@ -31,19 +31,19 @@ from tools import config
from tools.translate import _
class account_journal(osv.osv):
_inherit='account.journal'
_name='account.journal'
_inherit = 'account.journal'
_name = 'account.journal'
_columns = {
'allow_date':fields.boolean('Allows date not in the period'),
}
_defaults = {
'allow_date': lambda *a: 1,
'allow_date': lambda * a: 1,
}
account_journal()
class account_move_line(osv.osv):
_inherit='account.move.line'
_name='account.move.line'
_inherit = 'account.move.line'
_name = 'account.move.line'
def check_date(self, cr, uid, vals, context=None, check=True):
if not context:
@ -60,20 +60,20 @@ class account_move_line(osv.osv):
else:
journal_id = context['journal_id']
period_id = context['period_id']
journal=self.pool.get('account.journal').browse(cr,uid,[journal_id])[0]
journal = self.pool.get('account.journal').browse(cr, uid, [journal_id])[0]
if not journal.allow_date:
period=self.pool.get('account.period').browse(cr,uid,[period_id])[0]
if not time.strptime(vals['date'],'%Y-%m-%d')>=time.strptime(period.date_start,'%Y-%m-%d') and time.strptime(vals['date'],'%Y-%m-%d')<=time.strptime(period.date_stop,'%Y-%m-%d'):
raise osv.except_osv(_('Error'),_('The date of your Ledger Posting is not in the defined period !'))
period = self.pool.get('account.period').browse(cr, uid, [period_id])[0]
if not time.strptime(vals['date'], '%Y-%m-%d') >= time.strptime(period.date_start, '%Y-%m-%d') and time.strptime(vals['date'], '%Y-%m-%d') <= time.strptime(period.date_stop, '%Y-%m-%d'):
raise osv.except_osv(_('Error'), _('The date of your Ledger Posting is not in the defined period !'))
else:
return True
def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
flag=self.check_date(cr, uid, vals, context, check)
flag = self.check_date(cr, uid, vals, context, check)
result = super(account_move_line, self).write(cr, uid, ids, vals, context, check, update_check)
return result
def create(self, cr, uid, vals, context=None, check=True):
flag=self.check_date(cr, uid, vals, context, check)
flag = self.check_date(cr, uid, vals, context, check)
result = super(account_move_line, self).create(cr, uid, vals, context, check)
return result
account_move_line()

Some files were not shown because too many files have changed in this diff Show More