def _check_make_stub_line(self, invoice): """ Return the dict used to display an invoice/refund in the stub """ # Find the account.partial.reconcile which are common to the invoice and the payment if invoice.type in ['in_invoice', 'out_refund']: invoice_sign = 1 invoice_payment_reconcile = invoice.move_id.line_ids.mapped('matched_debit_ids').filtered(lambda r: r.debit_move_id in self.move_line_ids) else: invoice_sign = -1 invoice_payment_reconcile = invoice.move_id.line_ids.mapped('matched_credit_ids').filtered(lambda r: r.credit_move_id in self.move_line_ids) if self.currency_id != self.journal_id.company_id.currency_id: amount_paid = abs(sum(invoice_payment_reconcile.mapped('amount_currency'))) else: amount_paid = abs(sum(invoice_payment_reconcile.mapped('amount'))) amount_residual = invoice_sign * invoice.residual return { 'due_date': format_date(self.env, invoice.date_due), 'number': invoice.reference and invoice.number + ' - ' + invoice.reference or invoice.number, 'amount_total': formatLang(self.env, invoice_sign * invoice.amount_total, currency_obj=invoice.currency_id), 'amount_residual': formatLang(self.env, amount_residual, currency_obj=invoice.currency_id) if amount_residual * 10**4 != 0 else '-', 'amount_paid': formatLang(self.env, invoice_sign * amount_paid, currency_obj=invoice.currency_id), 'currency': invoice.currency_id, }
def _check_build_page_info(self, i, p): multi_stub = self.company_id.account_check_printing_multi_stub return { 'sequence_number': self.check_number if (self.journal_id.check_manual_sequencing and self.check_number != 0) else False, 'payment_date': format_date(self.env, self.payment_date), 'partner_id': self.partner_id, 'partner_name': self.partner_id.name, 'currency': self.currency_id, 'state': self.state, 'amount': formatLang(self.env, self.amount, currency_obj=self.currency_id) if i == 0 else 'VOID', 'amount_in_word': self._check_fill_line(self.check_amount_in_words) if i == 0 else 'VOID', 'memo': self.communication, 'stub_cropped': not multi_stub and len(self.invoice_ids) > INV_LINES_PER_STUB, # If the payment does not reference an invoice, there is no stub line to display 'stub_lines': p, }
def test_00_accepted_types(self): date_datetime = datetime.datetime.strptime('2017-01-31 12:00:00', "%Y-%m-%d %H:%M:%S") date_date = date_datetime.date() date_str = '2017-01-31' self.assertEqual(misc.format_date(self.env, date_datetime), '01/31/2017') self.assertEqual(misc.format_date(self.env, date_date), '01/31/2017') self.assertEqual(misc.format_date(self.env, date_str), '01/31/2017') self.assertEqual(misc.format_date(self.env, ''), '') self.assertEqual(misc.format_date(self.env, False), '') self.assertEqual(misc.format_date(self.env, None), '')
def test_01_code_and_format(self): date_str = '2017-01-31' lang = self.env['res.lang'] # Activate French and Simplified Chinese (test with non-ASCII characters) lang.search([('active', '=', False), ('code', 'in', ['fr_FR', 'zh_CN'])]).write({'active': True}) # Change a single parameter self.assertEqual(misc.format_date(lang.with_context(lang='fr_FR').env, date_str), '31/01/2017') self.assertEqual(misc.format_date(lang.env, date_str, lang_code='fr_FR'), '31/01/2017') self.assertEqual(misc.format_date(lang.env, date_str, date_format='MMM d, y'), 'Jan 31, 2017') # Change 2 parameters self.assertEqual(misc.format_date(lang.with_context(lang='zh_CN').env, date_str, lang_code='fr_FR'), '31/01/2017') self.assertEqual(misc.format_date(lang.with_context(lang='zh_CN').env, date_str, date_format='MMM d, y'), u'1\u6708 31, 2017') self.assertEqual(misc.format_date(lang.env, date_str, lang_code='fr_FR', date_format='MMM d, y'), 'janv. 31, 2017') # Change 3 parameters self.assertEqual(misc.format_date(lang.with_context(lang='zh_CN').env, date_str, lang_code='en_US', date_format='MMM d, y'), 'Jan 31, 2017')
def _get_lines_custom(self, options, line_id=None): lines = [] tables, where_clause, where_params = self.env[ 'account.move.line'].with_context(strict_range=True)._query_get() # user_type_id = self.env['account.account.type'].search([('type', '=', 'receivable')]) if where_clause: where_clause = 'AND ' + where_clause # sum(\"account_move_line\".debit) FILTER (WHERE ac.group_id = 4 and \"account_move_line\".ref LIKE '%%Labor%%') AS lab_debit, # sum(\"account_move_line\".credit) FILTER (WHERE ac.group_id = 4 and \"account_move_line\".ref LIKE '%%Labor%%') AS lab_credit, # sum(\"account_move_line\".debit) FILTER (WHERE ac.group_id = 4 and \"account_move_line\".ref LIKE '%%Burden%%') AS lab_b_debit, # sum(\"account_move_line\".credit) FILTER (WHERE ac.group_id = 4 and \"account_move_line\".ref LIKE '%%Burden%%') AS lab_b_credit, # date_from = options['date']['date_from'] date_from = datetime.strptime(options['date']['date_from'], '%Y-%m-%d') date_to = datetime.strptime(options['date']['date_to'], '%Y-%m-%d') date_to = date_to + timedelta(days=1) # date_to = options['date']['date_to'] sql_query = """ SELECT sum(\"account_move_line\".balance)*-1 AS balance, sum(\"account_move_line\".debit) FILTER (WHERE ac.group_id = 4) AS lab_debit, sum(\"account_move_line\".credit) FILTER (WHERE ac.group_id = 4) AS lab_credit, sum(\"account_move_line\".debit) FILTER (WHERE ac.group_id = 5) AS mat_debit, sum(\"account_move_line\".credit) FILTER (WHERE ac.group_id = 5) AS mat_credit, sum(\"account_move_line\".debit) FILTER (WHERE ac.group_id = 6) AS lab_a_debit, sum(\"account_move_line\".credit) FILTER (WHERE ac.group_id = 6) AS lab_a_credit, sum(\"account_move_line\".debit) FILTER (WHERE ac.group_id = 7) AS mat_a_debit, sum(\"account_move_line\".credit) FILTER (WHERE ac.group_id = 7) AS mat_a_credit, (SELECT coalesce(sum(duration_expected), 0) from mrp_workorder where ssi_job_id = j.id) AS exp_mins, (SELECT coalesce(sum(duration), 0) from mrp_workorder where ssi_job_id = j.id) AS real_mins, \"account_move_line\".analytic_account_id AS aa_id, j.name as job_name, j.type as job_type, j.notes, j.urgency, j.equipment_id, j.po_number as po, j.create_date, j.deadline_date, j.completed_on, j.id as job_id FROM """ + tables + """ LEFT JOIN account_account ac on \"account_move_line\".account_id = ac.id LEFT JOIN account_move am on \"account_move_line\".move_id = am.id LEFT JOIN account_analytic_account aa on \"account_move_line\".analytic_account_id = aa.id LEFT JOIN ssi_jobs j on aa.ssi_job_id = j.id WHERE \"account_move_line\".analytic_account_id IS NOT NULL AND ac.group_id IN (4, 5, 6, 7) """ + where_clause + """ GROUP BY \"account_move_line\".analytic_account_id, job_name, job_type, po, j.id, j.create_date, j.deadline_date, j.completed_on, j.notes, j.urgency, j.equipment_id ORDER BY job_name """ params = where_params self.env.cr.execute(sql_query, params) results = self.env.cr.dictfetchall() total_l = 0 total_m = 0 # total_l_b = 0 total_l_a = 0 total_m_a = 0 count = 0 line_l = 0 line_m = 0 # line_l_b = 0 line_l_a = 0 line_m_a = 0 for k, line in enumerate(results): if not line.get('lab_credit'): line['lab_credit'] = 0 if not line.get('lab_debit'): line['lab_debit'] = 0 # if not line.get('lab_b_credit'): # line['lab_b_credit'] = 0 # if not line.get('lab_b_debit'): # line['lab_b_debit'] = 0 if not line.get('mat_credit'): line['mat_credit'] = 0 if not line.get('mat_debit'): line['mat_debit'] = 0 if not line.get('lab_a_credit'): line['lab_a_credit'] = 0 if not line.get('lab_a_debit'): line['lab_a_debit'] = 0 if not line.get('mat_a_credit'): line['mat_a_credit'] = 0 if not line.get('mat_a_debit'): line['mat_a_debit'] = 0 total_l += line.get('lab_debit') - line.get('lab_credit', 0) total_m += line.get('mat_debit', 0) - line.get('mat_credit', 0) # total_l_b += line.get('lab_b_debit') - line.get('lab_b_credit', 0) total_l_a += line.get('lab_a_debit') - line.get('lab_a_credit', 0) total_m_a += line.get('mat_a_debit', 0) - line.get( 'mat_a_credit', 0) line_l += line.get('lab_debit', 0) - line.get('lab_credit', 0) line_m += line.get('mat_debit', 0) - line.get('mat_credit', 0) # line_l_b += line.get('lab_b_debit', 0) - line.get('lab_b_credit', 0) line_l_a += line.get('lab_a_debit', 0) - line.get( 'lab_a_credit', 0) line_m_a += line.get('mat_a_debit', 0) - line.get( 'mat_a_credit', 0) if k + 1 < len(results): next_job = results[k + 1].get('job_name') else: next_job = '' # if line.get('job_name') != next_job or not line.get('job_name'): if True: ++count equip = self.env['maintenance.equipment'].search( [('id', '=', line.get('equipment_id'))], limit=1) order = self.env['sale.order'].search( [('analytic_account_id', '=', line.get('aa_id')), ('state', '!=', 'cancel')], limit=1) job = self.env['ssi_jobs'].search( [('id', '=', line.get('job_id'))], limit=1) # Get Delivery Date delivery_date = '' if order.picking_ids: for transfer in (order.picking_ids).filtered( lambda t: t.picking_type_id.id == 2): delivery_date = transfer.date_done # Get Labor Dates wos = self.env['mrp.workorder'].search([('ssi_job_id', '=', line.get('job_id'))]) times = [] first = datetime(2100, 1, 1) last = datetime(1978, 1, 1) for wo in wos: times = (wo.time_ids).sorted(key=lambda r: r.date_end) # times = (wo.time_ids).filtered(lambda t: t.date_end <= date_to).sorted(key=lambda r: r.date_end) if times: if times[0].date_end <= first: first = times[0].date_end if times[-1].date_end >= last: last = times[-1].date_end rating = '' if equip.rating and not equip.rating_unit: rating = str(equip.rating) elif equip.rating and equip.rating_unit: rating = str(equip.rating) + ' ' + equip.rating_unit id = line.get('aa_id') if order.invoice_ids: amref = order.invoice_ids[0].move_id.name else: amref = '' # browsed_partner = self.env['res.partner'].browse(line.get('partner_id')) partner_name = job.partner_id.parent_id.name and str( job.partner_id.parent_id.name ) + ', ' + job.partner_id.name or job.partner_id.name if (line_l + line_m + line_l_a + line_m_a) != 0: tz = self.env.user.tz p_first = '' p_last = '' if first != datetime(2100, 1, 1): p_first = format_date( self.env, first.astimezone(timezone(tz)).date()) if last != datetime(1978, 1, 1): p_last = format_date( self.env, last.astimezone(timezone(tz)).date()) lines.append({ 'id': id, 'name': line.get('job_name'), 'level': 2, 'unfoldable': False, 'unfolded': line_id == id and True or False, 'columns': [ { 'name': job.partner_id.ref }, { 'name': partner_name }, { 'name': line.get('po') }, { 'name': line.get('job_type') }, { 'name': job.stage_id.name }, { 'name': line.get('notes') }, { 'name': line.get('urgency') }, { 'name': job.customer_category }, { 'name': job.project_manager.name }, { 'name': job.user_id.name }, { 'name': order.name }, { 'name': format_date(self.env, order.confirmation_date) }, { 'name': order.amount_total }, { 'name': amref }, { 'name': format_date(self.env, line.get('create_date')) }, { 'name': format_date(self.env, line.get('deadline_date')) }, { 'name': format_date(self.env, delivery_date) }, { 'name': round(line.get('exp_mins') / 60, 2) }, { 'name': round(line.get('real_mins') / 60, 2) }, { 'name': self.format_value(line_l) }, # {'name': self.format_value(line_l_b)}, { 'name': self.format_value(line_m) }, { 'name': self.format_value(line_l_a) }, { 'name': self.format_value(line_m_a) }, { 'name': rating }, { 'name': equip.poles }, { 'name': equip.voltage }, { 'name': equip.mounting }, { 'name': equip.manufacture }, { 'name': p_first }, { 'name': p_last } ], }) line_m = 0 line_l = 0 # line_l_b = 0 line_m_a = 0 line_l_a = 0 if total_l and not line_id: lines.append({ 'id': 'total', 'name': _('Total'), 'level': 0, 'class': 'total', 'columns': [ { 'name': v } for v in [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', self.format_value(total_l), # self.format_value(total_l_b), self.format_value(total_m), self.format_value(total_l_a), self.format_value(total_m_a), ] ], }) return lines
def _compute_new_values(self): """Compute the proposed new values. Sets a json string on new_values representing a dictionary thats maps account.move ids to a disctionay containing the name if we execute the action, and information relative to the preview widget. """ def _get_move_key(move_id): if self.sequence_number_reset == 'year': return move_id.date.year elif self.sequence_number_reset == 'month': return (move_id.date.year, move_id.date.month) return 'default' def _sort_by_name_key(name): match = re.match(self.move_ids[0]._sequence_fixed_regex, name) return (match.group('prefix1'), int(match.group('seq') or '0'), match.group('suffix')) self.new_values = "{}" for record in self.filtered('first_name'): moves_by_period = defaultdict(lambda: record.env['account.move']) for move in record.move_ids._origin: # Sort the moves by period depending on the sequence number reset moves_by_period[_get_move_key(move)] += move if record.sequence_number_reset == 'month': sequence = re.match(self.move_ids[0]._sequence_monthly_regex, record.first_name) format = '{prefix1}%(year)04d{prefix2}%(month)02d{prefix3}%(seq)0{len}d{suffix}'.format( prefix1=sequence.group('prefix1'), prefix2=sequence.group('prefix2'), prefix3=sequence.group('prefix3'), len=len(sequence.group('seq')), suffix=sequence.group('suffix'), ) elif record.sequence_number_reset == 'year': sequence = re.match(self.move_ids[0]._sequence_yearly_regex, record.first_name) format = '{prefix1}%(year)04d{prefix2}%(seq)0{len}d{suffix}'.format( prefix1=sequence.group('prefix1'), prefix2=sequence.group('prefix2'), len=len(sequence.group('seq')), suffix=sequence.group('suffix'), ) else: sequence = re.match(self.move_ids[0]._sequence_fixed_regex, record.first_name) format = '{prefix}%(seq)0{len}d{suffix}'.format( prefix=sequence.group('prefix1'), len=len(sequence.group('seq')), suffix=sequence.group('suffix'), ) new_values = {} for j, period_recs in enumerate(moves_by_period.values()): # compute the new values period by period for move in period_recs: new_values[move.id] = { 'current_name': move.name, 'state': move.state, 'date': format_date(self.env, move.date), 'server-date': str(move.date), } new_name_list = [ format % { 'year': period_recs[0].date.year, 'month': period_recs[0].date.month, 'seq': i + (int(sequence.group('seq') or '1') if j == (len(moves_by_period) - 1) else 1), } for i in range(len(period_recs)) ] # For all the moves of this period, assign the name by increasing initial name for move, new_name in zip( period_recs.sorted( lambda m: _sort_by_name_key(m.name)), new_name_list): new_values[move.id]['new_by_name'] = new_name # For all the moves of this period, assign the name by increasing date for move, new_name in zip( period_recs.sorted(lambda m: (m.date, m.name, m.id)), new_name_list): new_values[move.id]['new_by_date'] = new_name record.new_values = json.dumps(new_values)
def _get_lines(self, options, line_id=None): # We may need to reverse the sign at some point in the future sign = 1.0 ctx = self._context lines = [] cr = self.env.cr user_company = self.env.company company_ids = self._context.get('company_ids') or [user_company.id] # expand line, filter just for this product product = False if line_id and 'product_' in line_id: # we only want to fetch data about this product because we are expanding a line product_id_str = line_id.split('_')[1] if product_id_str.isnumeric(): product = self.env['product.product'].browse( int(product_id_str)) date_from = fields.Date.from_string(self._context['date_to']) # put in to constants CTE for easier query arg_list = (date_from, ) # product filtering product_clause = '' if product: product_clause = 'AND (pp.id IN %s)' arg_list += (tuple(product.ids), ) # partner filtering partner_clause = '' if 'partner_ids' in ctx: if ctx['partner_ids']: partner_clause = 'AND (l.partner_id IN %s)' arg_list += (tuple(ctx['partner_ids'].ids), ) else: partner_clause = 'AND l.partner_id IS NULL' if ctx.get('partner_categories'): partner_clause += 'AND (l.partner_id IN %s)' partner_ids = self.env['res.partner'].search([ ('category_id', 'in', ctx['partner_categories'].ids) ]).ids arg_list += (tuple(partner_ids or [0]), ) query = ''' WITH constants (date_from) AS (VALUES (%s)), product_cores AS ( SELECT pp.id AS id, pt.product_core_validity AS product_core_validity, pt.name AS product_name FROM product_template AS pt INNER JOIN product_product AS pp ON pp.product_tmpl_id = pt.id WHERE pt.core_ok = true AND pt.type = 'service' ''' + product_clause + ''' ) SELECT pc.id AS product_id, MAX(pc.product_name) AS product_name, MAX(UPPER(pc.product_name)) AS UPNAME, SUM(CASE WHEN COALESCE(l.date_maturity, l.date) < (SELECT date_from FROM constants) AND l.debit != 0 THEN ABS(l.quantity) WHEN COALESCE(l.date_maturity, l.date) < (SELECT date_from FROM constants) THEN -ABS(l.quantity) ELSE 0.0 END) AS total_expired_qty, SUM(CASE WHEN COALESCE(l.date_maturity, l.date) < (SELECT date_from FROM constants) THEN l.debit ELSE 0.0 END) AS total_expired_debit, SUM(CASE WHEN COALESCE(l.date_maturity, l.date) < (SELECT date_from FROM constants) THEN l.credit ELSE 0.0 END) AS total_expired_credit, SUM(CASE WHEN COALESCE(l.date_maturity, l.date) >= (SELECT date_from FROM constants) AND l.debit != 0 THEN ABS(l.quantity) WHEN COALESCE(l.date_maturity, l.date) >= (SELECT date_from FROM constants) THEN -ABS(l.quantity) ELSE 0.0 END) AS total_qty, SUM(CASE WHEN COALESCE(l.date_maturity, l.date) >= (SELECT date_from FROM constants) THEN l.debit ELSE 0.0 END) AS total_debit, SUM(CASE WHEN COALESCE(l.date_maturity, l.date) >= (SELECT date_from FROM constants) THEN l.credit ELSE 0.0 END) AS total_credit, SUM(CASE WHEN COALESCE(l.date_maturity, l.date) >= (SELECT date_from FROM constants) THEN l.credit ELSE 0.0 END) AS total_credit, array_agg(l.id) FILTER (WHERE COALESCE(l.date_maturity, l.date) >= (SELECT date_from FROM constants)) AS aml_ids FROM account_move_line AS l INNER JOIN product_cores AS pc ON l.product_id = pc.id WHERE (l.date <= (SELECT date_from FROM constants)) ''' + partner_clause + ''' AND (l.company_id IN %s) GROUP BY pc.id ORDER BY UPNAME ASC ''' arg_list += (tuple(company_ids), ) cr.execute(query, arg_list) totals = { 'total': 0.0, 'total_qty': 0.0, 'total_expired': 0.0, 'total_expired_qty': 0.0 } product_cores = cr.dictfetchall() for product_core in product_cores: ref = 'product_%s' % (product_core['product_id'], ) product_total = product_core['total_debit'] - product_core[ 'total_credit'] product_total_qty = product_core['total_qty'] product_expired_total = product_core[ 'total_expired_debit'] - product_core['total_expired_credit'] product_expired_total_qty = product_core['total_expired_qty'] totals['total'] += product_total totals['total_qty'] += product_total_qty totals['total_expired'] += product_expired_total totals['total_expired_qty'] += product_expired_total_qty vals = { 'id': ref, 'name': product_core['product_name'], 'level': 2, 'columns': [{ 'name': '' }] * 4 + [ { 'name': self.format_value(sign * product_total), 'no_format': sign * product_total }, { 'name': sign * product_total_qty, 'no_format': sign * product_total_qty }, { 'name': self.format_value( sign * product_expired_total), 'no_format': sign * product_expired_total }, { 'name': sign * product_expired_total_qty, 'no_format': sign * product_expired_total_qty }, ], 'unfoldable': True, 'unfolded': ref in options.get('unfolded_lines'), } lines.append(vals) if ref in options.get('unfolded_lines'): amls = self.env['account.move.line'].browse( product_core['aml_ids']) for aml in amls: if aml.move_id.is_purchase_document(): caret_type = 'account.invoice.in' elif aml.move_id.is_sale_document(): caret_type = 'account.invoice.out' elif aml.payment_id: caret_type = 'account.payment' else: caret_type = 'account.move' expires = aml.date_maturity if aml.date_maturity else aml.date expired = expires < date_from amount = aml.debit - aml.credit amount_not_expired = amount if not expired else 0.0 amount_expired = amount if expired else 0.0 qty = abs( aml.quantity) if aml.debit else -abs(aml.quantity) qty_not_expired = qty if not expired else 0.0 qty_expired = qty if expired else 0.0 vals = { 'id': aml.id, 'name': aml.move_id.name, 'class': 'date', 'caret_options': caret_type, 'level': 4, 'parent_id': ref, 'columns': [{ 'name': v } for v in [ aml.partner_id.display_name or 'Undefined', format_date(self.env, aml.date), format_date(self.env, expires), aml.account_id.display_name ]] + [ { 'name': self.format_value(sign * amount_not_expired, blank_if_zero=True), 'no_format': sign * amount_not_expired }, { 'name': sign * qty_not_expired or '', 'no_format': sign * qty_not_expired }, { 'name': self.format_value(sign * amount_expired, blank_if_zero=True), 'no_format': sign * amount_expired }, { 'name': sign * qty_expired or '', 'no_format': sign * qty_expired }, ], 'action_context': { 'default_type': aml.move_id.type, 'default_journal_id': aml.move_id.journal_id.id, }, 'title_hover': self._format_aml_name(aml.name, aml.ref, aml.move_id.name), } lines.append(vals) if not line_id: total_line = { 'id': 0, 'name': _('Total'), 'class': 'total', 'level': 2, 'columns': [{ 'name': '' }] * 4 + [ { 'name': self.format_value(sign * totals['total']), 'no_format': sign * totals['total'] }, { 'name': sign * totals['total_qty'], 'no_format': sign * totals['total_qty'] }, { 'name': self.format_value( sign * totals['total_expired']), 'no_format': sign * totals['total_expired'] }, { 'name': sign * totals['total_expired_qty'], 'no_format': sign * totals['total_expired_qty'] }, ], } lines.append(total_line) return lines
def get_lines(self, options, line_id=None): # Get date format for the lang partner = options.get('partner_id') and self.env['res.partner'].browse(options['partner_id']) or False if not partner: return [] lang_code = partner.lang or self.env.user.lang or 'en_US' lines = [] res = {} today = datetime.today().strftime('%Y-%m-%d') line_num = 0 for l in partner.unreconciled_aml_ids: if self.env.context.get('print_mode') and l.blocked: continue currency = l.currency_id or l.company_id.currency_id if currency not in res: res[currency] = [] res[currency].append(l) for currency, aml_recs in res.items(): total = 0 total_issued = 0 aml_recs = sorted(aml_recs, key=lambda aml: aml.blocked) for aml in aml_recs: amount = aml.currency_id and aml.amount_residual_currency or aml.amount_residual date_due = format_date(self.env, aml.date_maturity or aml.date, lang_code=lang_code) total += not aml.blocked and amount or 0 is_overdue = today > aml.date_maturity if aml.date_maturity else today > aml.date is_payment = aml.payment_id if is_overdue or is_payment: total_issued += not aml.blocked and amount or 0 if is_overdue: date_due = {'name': date_due, 'class': 'color-red date', 'style': 'white-space:nowrap;text-align:center;color: red;'} if is_payment: date_due = '' move_line_name = aml.move_id.name if aml.invoice_id and aml.invoice_id.num_comprobante: move_line_name += ' ('+aml.invoice_id.num_comprobante.zfill(8)+')' if self.env.context.get('print_mode'): move_line_name = {'name': move_line_name, 'style': 'text-align:right; white-space:normal;'} amount = formatLang(self.env, amount, currency_obj=currency) line_num += 1 columns = [format_date(self.env, aml.date, lang_code=lang_code), date_due, move_line_name, aml.expected_pay_date and aml.expected_pay_date +' '+ aml.internal_note or '', {'name': aml.blocked, 'blocked': aml.blocked}, amount] if self.env.context.get('print_mode'): columns = columns[:3]+columns[5:] lines.append({ 'id': aml.id, 'name': move_line_name, 'caret_options': 'followup', 'move_id': aml.move_id.id, 'type': is_payment and 'payment' or 'unreconciled_aml', 'unfoldable': False, 'has_invoice': bool(aml.invoice_id), 'columns': [type(v) == dict and v or {'name': v} for v in columns], }) totalXXX = formatLang(self.env, total, currency_obj=currency) line_num += 1 lines.append({ 'id': line_num, 'name': '', 'class': 'total', 'unfoldable': False, 'level': 0, 'columns': [{'name': v} for v in ['']*(2 if self.env.context.get('print_mode') else 4) + [total >= 0 and _('Total Due') or '', totalXXX]], }) if total_issued > 0: total_issued = formatLang(self.env, total_issued, currency_obj=currency) line_num += 1 lines.append({ 'id': line_num, 'name': '', 'class': 'total', 'unfoldable': False, 'level': 0, 'columns': [{'name': v} for v in ['']*(2 if self.env.context.get('print_mode') else 4) + [_('Total Overdue'), total_issued]], }) return lines
def _get_lines(self, options, line_id=None): res = super(ReportGeneralLedger, self)._get_lines(options, line_id) if 'curr' in self._context: cur = self.env['res.currency'].browse(self._context.get('curr')) if cur != self.env.user.company_id.currency_id: lines = [] context = self.env.context company_id = self.env.user.company_id used_currency = cur dt_from = options['date'].get('date_from') line_id = line_id and int(line_id.split('_')[1]) or None aml_lines = [] # Aml go back to the beginning of the user chosen range but the amount on the account line should go back to either the beginning of the fy or the beginning of times depending on the account grouped_accounts = self.with_context( date_from_aml=dt_from, date_from=dt_from and company_id.compute_fiscalyear_dates( datetime.strptime(dt_from, "%Y-%m-%d"))['date_from'] or None)._group_by_account_id(options, line_id) sorted_accounts = sorted(grouped_accounts, key=lambda a: a.code) unfold_all = context.get('print_mode') and len( options.get('unfolded_lines')) == 0 for account in sorted_accounts: debit = grouped_accounts[account]['debit'] credit = grouped_accounts[account]['credit'] balance = grouped_accounts[account]['balance'] debit = cur._compute(self.env.user.company_id.currency_id, cur, debit) credit = cur._compute(self.env.user.company_id.currency_id, cur, credit) balance = cur._compute( self.env.user.company_id.currency_id, cur, balance) amount_currency = '' if not account.currency_id else self.format_value( grouped_accounts[account]['amount_currency'], currency=account.currency_id) lines.append({ 'id': 'account_%s' % (account.id, ), 'name': account.code + " " + account.name, 'columns': [{ 'name': v } for v in [ amount_currency, self.format_value(debit, cur), self.format_value(credit, cur), self.format_value(balance, cur) ]], 'level': 2, 'unfoldable': True, 'unfolded': 'account_%s' % (account.id, ) in options.get('unfolded_lines') or unfold_all, 'colspan': 4, }) if 'account_%s' % (account.id, ) in options.get( 'unfolded_lines') or unfold_all: initial_debit = grouped_accounts[account][ 'initial_bal']['debit'] initial_credit = grouped_accounts[account][ 'initial_bal']['credit'] initial_balance = grouped_accounts[account][ 'initial_bal']['balance'] initial_debit = cur._compute( self.env.user.company_id.currency_id, cur, initial_debit) initial_credit = cur._compute( self.env.user.company_id.currency_id, cur, initial_credit) initial_balance = cur._compute( self.env.user.company_id.currency_id, cur, initial_balance) initial_currency = '' if not account.currency_id else self.format_value( grouped_accounts[account]['initial_bal'] ['amount_currency'], currency=account.currency_id) domain_lines = [{ 'id': 'initial_%s' % (account.id, ), 'class': 'o_account_reports_initial_balance', 'name': _('Initial Balance'), 'parent_id': 'account_%s' % (account.id, ), 'columns': [{ 'name': v } for v in [ '', '', '', initial_currency, self.format_value(initial_debit, cur), self.format_value(initial_credit, cur), self.format_value(initial_balance, cur) ]], }] progress = initial_balance amls = amls_all = grouped_accounts[account]['lines'] too_many = False if len(amls) > 80 and not context.get('print_mode'): amls = amls[:80] too_many = True for line in amls: if options.get('cash_basis'): line_debit = line.debit_cash_basis line_credit = line.credit_cash_basis else: line_debit = line.debit line_credit = line.credit line_debit = line.company_id.currency_id.compute( line_debit, used_currency) line_credit = line.company_id.currency_id.compute( line_credit, used_currency) progress = progress + line_debit - line_credit currency = "" if not line.currency_id else self.with_context( no_format=False).format_value(cur.with_context( date=line.date)._compute( self.env.user.company_id.currency_id, cur, line.amount_currency), currency=cur) name = [] name = line.name and line.name or '' if line.ref: name = name and name + ' - ' + line.ref or line.ref name_title = name # Don't split the name when printing if len(name) > 35 and not self.env.context.get( 'no_format') and not self.env.context.get( 'print_mode'): name = name[:32] + "..." partner_name = line.partner_id.name partner_name_title = partner_name if partner_name and len( partner_name ) > 35 and not self.env.context.get( 'no_format') and not self.env.context.get( 'print_mode'): partner_name = partner_name[:32] + "..." caret_type = 'account.move' if line.invoice_id: caret_type = 'account.invoice.in' if line.invoice_id.type in ( 'in_refund', 'in_invoice') else 'account.invoice.out' elif line.payment_id: caret_type = 'account.payment' columns = [{ 'name': v } for v in [ format_date(self.env, line.date), name, partner_name, currency, line_debit != 0 and self.format_value(line_debit, cur) or '', line_credit != 0 and self.format_value(line_credit, cur) or '', self.format_value(progress, cur) ]] columns[1]['class'] = 'whitespace_print' columns[2]['class'] = 'whitespace_print' columns[1]['title'] = name_title columns[2]['title'] = partner_name_title line_value = { 'id': line.id, 'caret_options': caret_type, 'class': 'top-vertical-align', 'parent_id': 'account_%s' % (account.id, ), 'name': line.move_id.name if line.move_id.name else '/', 'columns': columns, 'level': 4, } aml_lines.append(line.id) domain_lines.append(line_value) domain_lines.append({ 'id': 'total_' + str(account.id), 'class': 'o_account_reports_domain_total', 'parent_id': 'account_%s' % (account.id, ), 'name': _('Total '), 'columns': [{ 'name': v } for v in [ '', '', '', amount_currency, self.format_value(debit, cur), self.format_value(credit, cur), self.format_value(balance, cur) ]], }) if too_many: domain_lines.append({ 'id': 'too_many' + str(account.id), 'parent_id': 'account_%s' % (account.id, ), 'name': _('There are more than 80 items in this list, click here to see all of them' ), 'colspan': 7, 'columns': [{}], 'action': 'view_too_many', 'action_id': 'account,%s' % (account.id, ), }) lines += domain_lines journals = [ j for j in options.get('journals') if j.get('selected') ] if len(journals) == 1 and journals[0].get('type') in [ 'sale', 'purchase' ] and not line_id: total = self._get_journal_total() lines.append({ 'id': 0, 'class': 'total', 'name': _('Total'), 'columns': [{ 'name': v } for v in [ '', '', '', '', self.format_value(total['debit'], cur), self.format_value(total['credit'], cur), self.format_value(total['balance'], cur) ]], 'level': 1, 'unfoldable': False, 'unfolded': False, }) lines.append({ 'id': 0, 'name': _('Tax Declaration'), 'columns': [{ 'name': v } for v in ['', '', '', '', '', '', '']], 'level': 1, 'unfoldable': False, 'unfolded': False, }) lines.append({ 'id': 0, 'name': _('Name'), 'columns': [{ 'name': v } for v in [ '', '', '', '', _('Base Amount'), _('Tax Amount'), '' ]], 'level': 2, 'unfoldable': False, 'unfolded': False, }) journal_currency = self.env['account.journal'].browse( journals[0]['id']).company_id.currency_id for tax, values in self._get_taxes(journals[0]).items(): base_amount = journal_currency.compute( values['base_amount'], used_currency) tax_amount = journal_currency.compute( values['tax_amount'], used_currency) lines.append({ 'id': '%s_tax' % (tax.id, ), 'name': tax.name + ' (' + str(tax.amount) + ')', 'caret_options': 'account.tax', 'unfoldable': False, 'columns': [{ 'name': v } for v in [ self.format_value(base_amount), self.format_value(tax_amount), '' ]], 'colspan': 5, 'level': 4, }) if self.env.context.get('aml_only', False): return aml_lines return lines return res
def _get_lines(self, options, line_id=None): sign = -1.0 if self.env.context.get('aged_balance') else 1.0 lines = [] account_types = [self.env.context.get('account_type')] context = {'include_nullified_amount': True} if line_id and 'partner_' in line_id: # we only want to fetch data about this partner because we are expanding a line context.update(partner_ids=self.env['res.partner'].browse( int(line_id.split('_')[1]))) results, total, amls = self.env[ 'report.account.report_agedpartnerbalance'].with_context( **context)._get_partner_move_lines(account_types, self._context['date_to'], 'posted', 30) for values in results: vals = { 'id': 'partner_%s' % (values['partner_id'], ), 'name': values['name'], 'level': 2, 'columns': [{ 'name': '' }] * 4 + [{ 'name': self.format_value(sign * v), 'no_format': sign * v } for v in [ values['direction'], values['4'], values['3'], values['2'], values['1'], values['0'], values['total'] ]], 'trust': values['trust'], 'unfoldable': True, 'unfolded': 'partner_%s' % (values['partner_id'], ) in options.get('unfolded_lines'), 'partner_id': values['partner_id'], } lines.append(vals) if 'partner_%s' % (values['partner_id'], ) in options.get( 'unfolded_lines'): for line in amls[values['partner_id']]: aml = line['line'] if aml.move_id.is_purchase_document(): caret_type = 'account.invoice.in' elif aml.move_id.is_sale_document(): caret_type = 'account.invoice.out' elif aml.payment_id: caret_type = 'account.payment' else: caret_type = 'account.move' #getting currency currency = aml.move_id.currency_id.name line_date = aml.date_maturity or aml.date if not self._context.get('no_format'): line_date = format_date(self.env, line_date) vals = { 'id': aml.id, 'name': aml.move_id.name, 'class': 'date', 'caret_options': caret_type, 'level': 4, 'parent_id': 'partner_%s' % (values['partner_id'], ), 'columns': [{ 'name': v } for v in [ aml.ref, format_date(self.env, aml.date_maturity or aml.date), aml.journal_id.code, aml.account_id.display_name ]] + [{ 'name': self.format_value(sign * v, blank_if_zero=True), 'no_format': sign * v } for v in [ line['period'] == 6 - i and line['amount'] or 0 for i in range(7) ]], 'action_context': { 'default_type': aml.move_id.type, 'default_journal_id': aml.move_id.journal_id.id, }, 'title_hover': self._format_aml_name(aml.name, currency, aml.move_id.name), } lines.append(vals) if total and not line_id: total_line = { 'id': 0, 'name': _('Total'), 'class': 'total', 'level': 2, 'columns': [{ 'name': '' }] * 4 + [{ 'name': self.format_value(sign * v), 'no_format': sign * v } for v in [ total[6], total[4], total[3], total[2], total[1], total[0], total[5] ]], } lines.append(total_line) return lines
def validate_and_paid_invoices_ept(self, work_flow_process_record): """ This method will create invoices, validate it and register payment it, according to the configuration in workflow sets in quotation. :param work_flow_process_record: :return: It will return boolean. Migration done by twinkalc August 2020 """ self.ensure_one() if work_flow_process_record.create_invoice: if work_flow_process_record.invoice_date_is_order_date: fiscalyear_lock_date = self.company_id._get_user_fiscal_lock_date( ) if self.date_order.date() <= fiscalyear_lock_date: log_book_id = self._context.get('log_book_id') if log_book_id: message = "You cannot create invoice for order (%s) " \ "prior to and inclusive of the lock date %s. " \ "So, order is created but invoice is not created." % (self.name, format_date( self.env, fiscalyear_lock_date)) self.env['common.log.lines.ept'].create({ 'message': message, 'order_ref': self.name, 'log_book_id': log_book_id }) _logger.info(message) return True ctx = self._context.copy() if work_flow_process_record.sale_journal_id: ctx.update( {'journal_ept': work_flow_process_record.sale_journal_id}) invoices = self._create_invoices() self.validate_invoice_ept(invoices) if work_flow_process_record.register_payment: self.paid_invoice_ept(invoices) return True
def get_lines(self, options, line_id=None): num_cols = 8 cols_span = 4 to_rem = [] name_len = 40 single, show_partner, show_currency = options.get( 'is_single', False), options.get('show_partner', False), options.get('show_currency', False) aml_level = 2 if single else 4 if not show_partner: num_cols -= 1 cols_span -= 1 to_rem.append(2) name_len = 80 if not show_currency: to_rem.append(2) if not show_currency: num_cols -= 1 if show_partner: to_rem.append(3) lines = [] context = self.env.context company_id = self.env.user.company_id dt_from = options['date'].get('date_from') line_id = line_id and int(line_id.split('_')[1]) or None max_lines = 1000 if single else 200 aml_lines = [] # Aml go back to the beginning of the user chosen range but the amount on the account line should go back to either the beginning of the fy or the beginning of times depending on the account grouped_accounts = self.with_context( date_from_aml=dt_from, date_from=dt_from and company_id.compute_fiscalyear_dates( datetime.strptime(dt_from, "%Y-%m-%d"))['date_from'] or None).group_by_account_id(options, line_id) sorted_accounts = sorted(grouped_accounts, key=lambda a: a.code) unfold_all = False #context.get('print_mode') and len(options.get('unfolded_lines')) == 0 for account in sorted_accounts: row = grouped_accounts[account] debit = row['debit'] credit = row['credit'] balance = row['balance'] amount_currency = '' if not account.currency_id else self.format_value( row['amount_currency'], currency=account.currency_id) if not single: columns = show_currency and [ amount_currency, self.format_value(debit), self.format_value(credit), self.format_value(balance) ] or [ self.format_value(debit), self.format_value(credit), self.format_value(balance) ] lines.append({ 'id': 'account_%s' % (account.id, ), 'name': account.code + " " + account.name, 'columns': [{ 'name': v } for v in columns], 'level': 2, 'unfoldable': True, 'unfolded': 'account_%s' % (account.id, ) in options.get('unfolded_lines') or unfold_all, 'colspan': cols_span, }) if single or 'account_%s' % (account.id, ) in options.get( 'unfolded_lines') or unfold_all: initial_debit = row['initial_bal']['debit'] initial_credit = row['initial_bal']['credit'] initial_balance = row['initial_bal']['balance'] initial_currency = '' if not account.currency_id else self.format_value( row['initial_bal']['amount_currency'], currency=account.currency_id) domain_lines = [{ 'id': 'initial_%s' % (account.id, ), 'class': 'o_ac_reports_initial_balance', 'name': _('Initial Balance'), 'parent_id': 'account_%s' % (account.id, ), 'columns': [{ 'name': v } for v in [ '', '', '', initial_currency, self.format_value(initial_debit), self.format_value(initial_credit), self.format_value(initial_balance) ]], }] self.index_rem(to_rem, domain_lines[0]['columns']) progress = initial_balance amls = amls_all = row['lines'] too_many = False if len(amls) > max_lines and not context.get('print_mode'): amls = amls[:max_lines] too_many = True used_currency = self.env.user.company_id.currency_id for line in amls: if options.get('cash_basis'): line_debit = line.debit_cash_basis line_credit = line.credit_cash_basis else: line_debit = line.debit line_credit = line.credit line_debit = line.company_id.currency_id.compute( line_debit, used_currency) line_credit = line.company_id.currency_id.compute( line_credit, used_currency) progress = progress + line_debit - line_credit currency = "" if not line.currency_id else self.with_context( no_format=False).format_value( line.amount_currency, currency=line.currency_id) name = [] name = line.name and line.name or '' if line.ref: name = name and name + ' - ' + line.ref or line.ref if len(name) > name_len and not self.env.context.get( 'no_format'): name = name[:name_len] + "..." partner_name = line.partner_id.name if partner_name and len( partner_name) > 35 and not self.env.context.get( 'no_format'): partner_name = partner_name[:32] + "..." caret_type = 'account.move' if line.invoice_id: caret_type = 'account.invoice.in' if line.invoice_id.type in ( 'in_refund', 'in_invoice') else 'account.invoice.out' elif line.payment_id: caret_type = 'account.payment' line_value = { 'id': line.id, 'caret_options': caret_type, 'parent_id': 'account_%s' % (account.id, ), 'name': line.move_id.name if line.move_id.name else '/', 'columns': [{ 'name': v } for v in [ format_date(self.env, line.date), name, partner_name, currency, line_debit != 0 and self. format_value(line_debit) or '', line_credit != 0 and self.format_value(line_credit) or '', self.format_value(progress) ]], 'level': aml_level, } aml_lines.append(line.id) self.index_rem(to_rem, line_value['columns']) domain_lines.append(line_value) total_val = { 'id': 'total_' + str(account.id), 'class': 'o_ac_reports_domain_total', 'parent_id': 'account_%s' % (account.id, ), 'name': _('Total '), 'columns': [{ 'name': v } for v in [ '', '', '', amount_currency, self.format_value(debit), self.format_value(credit), self.format_value(balance) ]], 'colspan': cols_span, } self.index_rem(to_rem, total_val['columns']) for i in range(3 if show_partner else 2): del total_val['columns'][0] domain_lines.append(total_val) if too_many: domain_lines.append({ 'id': 'too_many' + str(account.id), 'parent_id': 'account_%s' % (account.id, ), 'name': _('There are more than 80 items in this list, click here to see all of them' ), 'colspan': cols_span + 2, 'columns': [{}], 'action': 'view_too_many', 'action_id': 'account,%s' % (account.id, ), }) lines += domain_lines journals = [j for j in options.get('journals') if j.get('selected')] if len(journals) == 1 and journals[0].get('type') in [ 'sale', 'purchase' ] and not line_id: lines_len = len(lines) total = self._get_journal_total() lines.append({ 'id': 0, 'class': 'total', 'name': _('Total'), 'columns': [{ 'name': v } for v in [ '', '', '', '', self.format_value(total['debit']), self.format_value(total['credit']), self.format_value(total['balance']) ]], 'level': 1, 'unfoldable': False, 'unfolded': False, }) lines.append({ 'id': 0, 'name': _('Tax Declaration'), 'columns': [{ 'name': v } for v in ['', '', '', '', '', '', '']], 'level': 1, 'unfoldable': False, 'unfolded': False, }) lines.append({ 'id': 0, 'name': _('Name'), 'columns': [{ 'name': v } for v in ['', '', '', '', _('Base Amount'), _('Tax Amount'), '']], 'level': 2, 'unfoldable': False, 'unfolded': False, }) for tax, values in self._get_taxes(journals[0]).items(): lines.append({ 'id': '%s_tax' % (tax.id, ), 'name': tax.name + ' (' + str(tax.amount) + ')', 'caret_options': 'account.tax', 'unfoldable': False, 'columns': [{ 'name': v } for v in [ '', '', '', '', values['base_amount'], values['tax_amount'], '' ]], 'level': 4, }) for l in range(lines_len, len(lines)): self.index_rem(to_rem, lines[l]['columns']) if self.env.context.get('aml_only', False): return aml_lines return lines
def _get_lines(self, options, line_id=None): lines = [] context = self.env.context #partners = [] domain = [('state', '=', 'sale')] date_from = options['date'].get('date_from') date_to = options['date'].get('date_to') date_from_datetime = fields.Datetime.from_string(date_from) date_to_datetime = fields.Datetime.from_string(date_to) domain = [('date_order', '>=', date_from_datetime), ('date_order', '<=', date_to_datetime)] + domain if line_id != None: domain = [('order_partner_id', '=', line_id)] + domain unfold_query = self.env['sale.order.line'].with_context( strict_range=True).search_read(domain) #res = self. orm_query = self.env['sale.order.line'].with_context( strict_range=True).read_group( domain, ['price_total:sum', 'order_partner_id', 'order_id'], ['order_partner_id'], ['order_partner_id']) #self.env.cr.execute(sql_query, []) #results = self.env.cr.dictfetchall() total = 0 for line in orm_query: columns = ['', '', '', '', '', '', line.get('price_total'), ''] total += line.get('price_total') partner_name = self.env['res.partner'].browse( line.get('order_partner_id')[0]).name lines.append({ 'id': line.get('order_partner_id')[0], 'name': partner_name, 'level': 2, 'unfoldable': True, 'unfolded': line_id == line.get('order_partner_id') and True or False, 'columns': [{ 'name': v } for v in columns], }) #Adding sale orders lines if line_id: for child_line in unfold_query: columns = [ child_line.get('name'), child_line.get('product_uom')[1], child_line.get('lot_id'), child_line.get('payment_term'), child_line.get('product_uom_qty'), child_line.get('price_unit'), child_line.get('price_total'), child_line.get('order_id')[1] ] lines.append({ 'id': child_line.get('id'), 'name': format_date(self.env, child_line.get('date_order')), 'class': 'date', 'level': 4, 'parent_id': line_id, 'columns': [{ 'name': v } for v in columns], }) if total and not line_id: columns = ['', '', '', '', '', '', total, ''] lines.append({ 'id': 'total', 'name': _('Total'), #'colspan': 7, 'level': 0, 'class': 'total', 'columns': [{ 'name': v } for v in columns] }) return lines
def _get_lines(self, options, line_id=None): offset = int(options.get('lines_offset', 0)) lines = [] context = self.env.context # company_id = context.get('company_id') or self.env.user.company_id if line_id: line_id = int(line_id.split('_')[1]) or None # elif options.get('partner_ids') and len(options.get('partner_ids')) == 1: # # If a default partner is set, we only want to load the line referring to it. # partner_id = options['partner_ids'][0] # line_id = partner_id # if line_id: # if 'partner_' + str(line_id) not in options.get('unfolded_lines', []): # options.get('unfolded_lines', []).append('partner_' + str(line_id)) grouped_partners = self._group_by_partner_id(options, line_id) sorted_partners = sorted(grouped_partners, key=lambda p: p.name or '') unfold_all = context.get( 'print_mode') and not options.get('unfolded_lines') total_initial_balance = total_debit = total_credit = total_balance = 0.0 for partner in sorted_partners: debit = grouped_partners[partner]['debit'] credit = grouped_partners[partner]['credit'] balance = grouped_partners[partner]['balance'] initial_balance = grouped_partners[partner]['initial_bal'][ 'balance'] total_initial_balance += initial_balance total_debit += debit total_credit += credit total_balance += balance columns = [ '', '', self.format_value(initial_balance), self.format_value(debit), self.format_value(credit) ] if self.user_has_groups('base.group_multi_currency'): columns.append('') columns.append(self.format_value(balance)) # don't add header for `load more` if offset == 0: lines.append({ 'id': 'partner_' + str(partner.id), 'name': partner.name, 'columns': [{ 'name': v } for v in columns], 'level': 2, 'trust': partner.trust, 'unfoldable': True, 'unfolded': 'partner_' + str(partner.id) in options.get('unfolded_lines') or unfold_all, # 'colspan': 6, }) user_company = self.env.user.company_id used_currency = user_company.currency_id if 'partner_' + str( partner.id) in options.get('unfolded_lines') or unfold_all: if offset == 0: progress = initial_balance else: progress = float( options.get('lines_progress', initial_balance)) domain_lines = [] amls = grouped_partners[partner]['lines'] remaining_lines = 0 if not context.get('print_mode'): remaining_lines = grouped_partners[partner][ 'total_lines'] - offset - len(amls) for line in amls: if options.get('cash_basis'): line_debit = line.debit_cash_basis line_credit = line.credit_cash_basis else: line_debit = line.debit line_credit = line.credit date = amls.env.context.get('date') or fields.Date.today() line_currency = line.company_id.currency_id line_debit = line_currency._convert( line_debit, used_currency, user_company, date) line_credit = line_currency._convert( line_credit, used_currency, user_company, date) progress_before = progress progress = progress + line_debit - line_credit caret_type = 'account.move' # if line.invoice_id: # caret_type = 'account.invoice.in' if line.invoice_id.type in ( # 'in_refund', 'in_invoice') else 'account.invoice.out' domain_columns = [] if line.payment_id: caret_type = 'account.payment' #if line.payment_id.payment_type == 'inbound' and line.debit: if line.payment_id.payment_type == 'inbound': domain_columns = [ '', self._format_aml_name(line.name, line.move_id.ref, line.move_id.name), self.format_value(initial_balance), line_debit != 0 and self.format_value(line_debit) or '', '' ] if self.user_has_groups( 'base.group_multi_currency'): domain_columns.append('') domain_columns.append(self.format_value(progress)) elif line.payment_id.payment_type == 'outbound': domain_columns = [ '', self._format_aml_name(line.name, line.move_id.ref, line.move_id.name), self.format_value(initial_balance), '', line_credit != 0 and self.format_value(line_credit) or '' ] if self.user_has_groups( 'base.group_multi_currency'): domain_columns.append('') domain_columns.append(self.format_value(progress)) else: domain_columns = ['', '', '', '', ''] if self.user_has_groups( 'base.group_multi_currency'): domain_columns.append('') domain_columns.append('') columns = [{'name': v} for v in domain_columns] columns[3].update({'class': 'date'}) domain_lines.append({ 'id': line.id, 'parent_id': 'partner_' + str(partner.id), 'name': format_date(self.env, line.date), 'class': 'date', 'columns': columns, 'caret_options': caret_type, 'level': 4, }) #for line in domain_lines: # for col in line['columns']: # if col and col[: # domain_lines.remove(line) # load more if remaining_lines > 0: domain_lines.append({ 'id': 'loadmore_%s' % partner.id, 'offset': offset + self.MAX_LINES, 'progress': progress, 'class': 'o_account_reports_load_more text-center', 'parent_id': 'partner_%s' % partner.id, 'name': _('Load more... (%s remaining)') % remaining_lines, 'colspan': 10 if self.user_has_groups('base.group_multi_currency') else 9, 'columns': [{}], }) lines += domain_lines if not line_id: total_columns = [ '', '', self.format_value(total_initial_balance), self.format_value(total_debit), self.format_value(total_credit) ] if self.user_has_groups('base.group_multi_currency'): total_columns.append('') total_columns.append(self.format_value(total_balance)) lines.append({ 'id': 'grouped_partners_total', 'name': _('Total'), 'level': 0, 'class': 'o_account_reports_domain_total', 'columns': [{ 'name': v } for v in total_columns], }) return lines
def _format_date(self, value, lang_code=False, date_format=False): return misc.format_date(self._env, value, lang_code=lang_code, date_format=date_format)
def _get_report_line_move_line(self, options, partner, aml, cumulated_init_balance, cumulated_balance): if aml['payment_id']: caret_type = 'account.payment' else: caret_type = 'account.move' date_maturity = aml['date_maturity'] and format_date( self.env, fields.Date.from_string(aml['date_maturity'])) columns = [ { 'name': aml['journal_code'] }, { 'name': aml['account_code'] }, { 'name': self._format_aml_name(aml['name'], aml['ref'], aml['move_name']) }, { 'name': date_maturity or '', 'class': 'date' }, { 'name': aml['matching_number'] or '' }, { 'name': self.format_value(cumulated_init_balance), 'class': 'number' }, { 'name': self.format_value(aml['debit'], blank_if_zero=True), 'class': 'number' }, { 'name': self.format_value(aml['credit'], blank_if_zero=True), 'class': 'number' }, ] if self.user_has_groups('base.group_multi_currency'): if aml['currency_id']: currency = self.env['res.currency'].browse(aml['currency_id']) formatted_amount = self.format_value(aml['amount_currency'], currency=currency, blank_if_zero=True) columns.append({'name': formatted_amount, 'class': 'number'}) else: columns.append({'name': ''}) columns.append({ 'name': self.format_value(cumulated_balance), 'class': 'number' }) return { 'id': aml['id'], 'parent_id': 'partner_%s' % (partner.id if partner else 0), 'name': format_date(self.env, aml['date']), 'class': 'text' + aml.get('class', ''), # do not format as date to prevent text centering 'columns': columns, 'caret_options': caret_type, 'level': 2, }
def _get_lot_deadline(self, lot): if self.show_deadline_date: lot.ensure_one() deadline = lot.read()[0][self.show_deadline_date] if deadline: return format_date(self.env, deadline)
def test_01_code_and_format(self): date_str = '2017-01-31' lang = self.env['res.lang'] # Activate French and Simplified Chinese (test with non-ASCII characters) lang.search([('active', '=', False), ('code', 'in', ['fr_FR', 'zh_CN'])]).write({'active': True}) # -- test `date` # Change a single parameter self.assertEqual( misc.format_date(lang.with_context(lang='fr_FR').env, date_str), '31/01/2017') self.assertEqual( misc.format_date(lang.env, date_str, lang_code='fr_FR'), '31/01/2017') self.assertEqual( misc.format_date(lang.env, date_str, date_format='MMM d, y'), 'Jan 31, 2017') # Change 2 parameters self.assertEqual( misc.format_date(lang.with_context(lang='zh_CN').env, date_str, lang_code='fr_FR'), '31/01/2017') self.assertEqual( misc.format_date(lang.with_context(lang='zh_CN').env, date_str, date_format='MMM d, y'), u'1\u6708 31, 2017') self.assertEqual( misc.format_date(lang.env, date_str, lang_code='fr_FR', date_format='MMM d, y'), 'janv. 31, 2017') # Change 3 parameters self.assertEqual( misc.format_date(lang.with_context(lang='zh_CN').env, date_str, lang_code='en_US', date_format='MMM d, y'), 'Jan 31, 2017') # -- test `datetime` datetime_str = '2017-01-31 10:33:00' # Change languages and timezones self.assertEqual( misc.format_datetime(lang.with_context(lang='fr_FR').env, datetime_str, tz='Europe/Brussels'), '31 janv. 2017 à 11:33:00') self.assertEqual( misc.format_datetime(lang.with_context(lang='zh_CN').env, datetime_str, tz='America/New_York'), '2017\u5E741\u670831\u65E5 \u4E0A\u53485:33:00' ) # '2017年1月31日 上午5:33:00' # Change language, timezone and format self.assertEqual( misc.format_datetime(lang.with_context(lang='fr_FR').env, datetime_str, tz='America/New_York', dt_format='short'), '31/01/2017 05:33') self.assertEqual( misc.format_datetime(lang.with_context(lang='en_US').env, datetime_str, tz='Europe/Brussels', dt_format='MMM d, y'), 'Jan 31, 2017') # Check given `lang_code` overwites context lang self.assertEqual( misc.format_datetime(lang.env, datetime_str, tz='Europe/Brussels', dt_format='long', lang_code='fr_FR'), '31 janvier 2017 à 11:33:00 +0100') self.assertEqual( misc.format_datetime(lang.with_context(lang='zh_CN').env, datetime_str, tz='Europe/Brussels', dt_format='long', lang_code='en_US'), 'January 31, 2017 at 11:33:00 AM +0100')
def _get_lines(self, options, line_id=None): """ Override Compute and return the lines of the columns of the follow-ups report. """ # Get date format for the lang partner = options.get('partner_id') and self.env['res.partner'].browse(options['partner_id']) or False if not partner: return [] lang_code = partner.lang or self.env.user.lang or 'en_US' lines = [] res = {} today = fields.Date.today() line_num = 0 for l in partner.unreconciled_aml_ids.filtered(lambda l: l.company_id == self.env.user.company_id): if l.company_id == self.env.user.company_id: if self.env.context.get('print_mode') and l.blocked: continue currency = l.currency_id or l.company_id.currency_id if currency not in res: res[currency] = [] res[currency].append(l) for currency, aml_recs in res.items(): total = 0 total_issued = 0 for aml in aml_recs: amount = aml.currency_id and aml.amount_residual_currency or aml.amount_residual date_due = format_date(self.env, aml.date_maturity or aml.date, lang_code=lang_code) total += not aml.blocked and amount or 0 is_overdue = today > aml.date_maturity if aml.date_maturity else today > aml.date is_payment = aml.payment_id if is_overdue or is_payment: total_issued += not aml.blocked and amount or 0 if is_overdue: date_due = {'name': date_due, 'class': 'color-red date', 'style': 'white-space:nowrap;text-align:center;color: red;'} if is_payment: date_due = '' # import ipdb; ipdb.set_trace() # move_line_name = aml.invoice_id.name or aml.name # move_line_name = str(aml.invoice_id.fe_Serie) + '-' + str(aml.invoice_id.fe_DocNro) move_line_name = 'Factura' if self.env.context.get('print_mode'): move_line_name = {'name': move_line_name, 'style': 'text-align:right; white-space:normal;'} amount = formatLang(self.env, amount, currency_obj=currency) line_num += 1 expected_pay_date = format_date(self.env, aml.expected_pay_date, lang_code=lang_code) if aml.expected_pay_date else '' columns = [ format_date(self.env, aml.date, lang_code=lang_code), date_due, aml.invoice_id.origin, move_line_name, expected_pay_date + ' ' + (aml.internal_note or ''), {'name': aml.blocked, 'blocked': aml.blocked}, amount, ] if self.env.context.get('print_mode'): columns = columns[:4] + columns[6:] lines.append({ 'id': aml.id, 'invoice_id': aml.invoice_id.id, 'view_invoice_id': self.env['ir.model.data'].get_object_reference('account', 'invoice_form')[1], 'account_move': aml.move_id, # 'name': aml.move_id.name, 'name': str(aml.invoice_id.fe_Serie) + '-' + str(aml.invoice_id.fe_DocNro) if aml.invoice_id.type == 'out_invoice' or aml.invoice_id.type == 'out_refund' else aml.name, 'caret_options': 'followup', 'move_id': aml.move_id.id, 'type': is_payment and 'payment' or 'unreconciled_aml', 'unfoldable': False, 'has_invoice': bool(aml.invoice_id), 'columns': [type(v) == dict and v or {'name': v} for v in columns], }) total_due = formatLang(self.env, total, currency_obj=currency) line_num += 1 lines.append({ 'id': line_num, 'name': '', 'class': 'total', 'unfoldable': False, 'level': 0, 'columns': [{'name': v} for v in [''] * (3 if self.env.context.get('print_mode') else 5) + [total >= 0 and _('Total Due') or '', total_due]], }) if total_issued > 0: total_issued = formatLang(self.env, total_issued, currency_obj=currency) line_num += 1 lines.append({ 'id': line_num, 'name': '', 'class': 'total', 'unfoldable': False, 'level': 0, 'columns': [{'name': v} for v in [''] * (3 if self.env.context.get('print_mode') else 5) + [_('Total Overdue'), total_issued]], }) # Add an empty line after the total to make a space between two currencies line_num += 1 lines.append({ 'id': line_num, 'name': '', 'class': '', 'unfoldable': False, 'level': 0, 'columns': [{} for col in columns], }) # Remove the last empty line if lines: lines.pop() return lines
def _create_edit_tax_reminder(self, values=None): # Create/Edit activity type if needed if self._context.get('no_create_move', False): return self.env['account.move'] if not values: values = {} company = values.get('company_id', False) or self.company_id or self.env.company move_res_model_id = self.env['ir.model'].search( [('model', '=', 'account.move')], limit=1).id activity_type = company.account_tax_next_activity_type or False vals = { 'category': 'tax_report', 'delay_count': values.get('account_tax_periodicity', company.account_tax_periodicity) == 'monthly' and 1 or 3, 'delay_unit': 'months', 'delay_from': 'previous_activity', 'res_model_id': move_res_model_id, 'force_next': False, 'summary': _('Periodic Tax Return') } if not activity_type: vals['name'] = _('Tax Report for company %s') % (company.name, ) activity_type = self.env['mail.activity.type'].create(vals) company.account_tax_next_activity_type = activity_type else: activity_type.write(vals) # search for an existing reminder for given journal and change it's date account_tax_periodicity_journal_id = values.get( 'account_tax_periodicity_journal_id', company.account_tax_periodicity_journal_id) date = values.get('account_tax_periodicity_next_deadline', False) if not date: date = date_utils.end_of( fields.Date.today(), "quarter") + relativedelta( days=company.account_tax_periodicity_reminder_day) end_date_last_month = date_utils.end_of( date + relativedelta(months=-1), 'month') move_id = self.env['account.move'].search( [('state', '=', 'draft'), ('is_tax_closing', '=', True), ('journal_id', '=', account_tax_periodicity_journal_id.id), ('activity_ids.activity_type_id', '=', activity_type.id), ('date', '<=', end_date_last_month), ('date', '>=', date_utils.start_of( end_date_last_month + relativedelta(months=-vals['delay_count']), 'month'))], limit=1) # Create empty move if activity_type.delay_count == 1: formatted_date = format_date(self.env, end_date_last_month, date_format='LLLL') else: formatted_date = format_date(self.env, end_date_last_month, date_format='qqq') if len(move_id): for act in move_id.activity_ids: if act.activity_type_id == activity_type: act.write({'date_deadline': date}) move_id.date = end_date_last_month move_id.ref = _('Tax Return for %s') % (formatted_date, ) else: move_id = self.env['account.move'].create({ 'journal_id': account_tax_periodicity_journal_id.id, 'date': end_date_last_month, 'is_tax_closing': True, 'ref': _('Tax Return for %s') % (formatted_date, ) }) advisor_user = self.env['res.users'].search( [('company_ids', 'in', (company.id, )), ('groups_id', 'in', self.env.ref('account.group_account_manager').ids)], limit=1, order="id ASC") activity_vals = { 'res_id': move_id.id, 'res_model_id': move_res_model_id, 'activity_type_id': activity_type.id, 'summary': _('TAX Report'), 'date_deadline': date, 'automated': True, 'user_id': advisor_user.id or self.env.user.id } self.env['mail.activity'].with_context( mail_activity_quick_update=True).create(activity_vals) return move_id
def _get_columns_name(self, options): columns = [ {}, { 'name': _("Ref"), 'class': '', 'style': 'text-align:center; white-space:nowrap;' }, { 'name': _("Due Date"), 'class': 'date', 'style': 'white-space:nowrap;' }, { 'name': _("Journal"), 'class': '', 'style': 'text-align:center; white-space:nowrap;' }, { 'name': _("Account"), 'class': '', 'style': 'text-align:center; white-space:nowrap;' }, { 'name': _("As of: %s") % format_date(self.env, options['date']['date_to']), 'class': 'number sortable', 'style': 'white-space:nowrap;' }, { 'name': _("1 - 30"), 'class': 'number sortable', 'style': 'white-space:nowrap;' }, { 'name': _("31 - 60"), 'class': 'number sortable', 'style': 'white-space:nowrap;' }, { 'name': _("61 - 90"), 'class': 'number sortable', 'style': 'white-space:nowrap;' }, { 'name': _("91 - 120"), 'class': 'number sortable', 'style': 'white-space:nowrap;' }, { 'name': _("Older"), 'class': 'number sortable', 'style': 'white-space:nowrap;' }, { 'name': _("Total"), 'class': 'number sortable', 'style': 'white-space:nowrap;' }, ] return columns
def _prepare_move_lines(self, move_lines, target_currency=False, target_date=False, recs_count=0): """ Returns move lines formatted for the manual/bank reconciliation widget :param move_line_ids: :param target_currency: currency (browse) you want the move line debit/credit converted into :param target_date: date to use for the monetary conversion """ context = dict(self._context or {}) ret = [] for line in move_lines: company_currency = line.company_id.currency_id line_currency = (line.currency_id and line.amount_currency ) and line.currency_id or company_currency date_maturity = misc.format_date(self.env, line.date_maturity, lang_code=self.env.user.lang) ret_line = { 'id': line.id, 'name': line.name and line.name != '/' and line.move_id.name + ': ' + line.name or line.move_id.name, 'ref': line.move_id.ref or '', # For reconciliation between statement transactions and already registered payments (eg. checks) # NB : we don't use the 'reconciled' field because the line we're selecting is not the one that gets reconciled 'account_id': [line.account_id.id, line.account_id.display_name], 'already_paid': line.account_id.internal_type == 'liquidity', 'account_code': line.account_id.code, 'account_name': line.account_id.name, 'account_type': line.account_id.internal_type, 'date_maturity': date_maturity, 'date': line.date, 'journal_id': [line.journal_id.id, line.journal_id.display_name], 'partner_id': line.partner_id.id, 'partner_name': line.partner_id.name, 'currency_id': line_currency.id, } debit = line.debit credit = line.credit amount = line.amount_residual amount_currency = line.amount_residual_currency # For already reconciled lines, don't use amount_residual(_currency) if line.account_id.internal_type == 'liquidity': amount = debit - credit amount_currency = line.amount_currency target_currency = target_currency or company_currency # Use case: # Let's assume that company currency is in USD and that we have the 3 following move lines # Debit Credit Amount currency Currency # 1) 25 0 0 NULL # 2) 17 0 25 EUR # 3) 33 0 25 YEN # # If we ask to see the information in the reconciliation widget in company currency, we want to see # The following information # 1) 25 USD (no currency information) # 2) 17 USD [25 EUR] (show 25 euro in currency information, in the little bill) # 3) 33 USD [25 YEN] (show 25 yen in currency information) # # If we ask to see the information in another currency than the company let's say EUR # 1) 35 EUR [25 USD] # 2) 25 EUR (no currency information) # 3) 50 EUR [25 YEN] # In that case, we have to convert the debit-credit to the currency we want and we show next to it # the value of the amount_currency or the debit-credit if no amount currency if target_currency == company_currency: if line_currency == target_currency: amount = amount amount_currency = "" total_amount = debit - credit total_amount_currency = "" else: amount = amount amount_currency = amount_currency total_amount = debit - credit total_amount_currency = line.amount_currency if target_currency != company_currency: if line_currency == target_currency: amount = amount_currency amount_currency = "" total_amount = line.amount_currency total_amount_currency = "" else: amount_currency = line.currency_id and amount_currency or amount company = line.account_id.company_id date = target_date or line.date amount = company_currency._convert(amount, target_currency, company, date) total_amount = company_currency._convert( (line.debit - line.credit), target_currency, company, date) total_amount_currency = line.currency_id and line.amount_currency or ( line.debit - line.credit) ret_line['recs_count'] = recs_count ret_line['debit'] = amount > 0 and amount or 0 ret_line['credit'] = amount < 0 and -amount or 0 ret_line['amount_currency'] = amount_currency ret_line['amount_str'] = formatLang(self.env, abs(amount), currency_obj=target_currency) ret_line['total_amount_str'] = formatLang( self.env, abs(total_amount), currency_obj=target_currency) ret_line['amount_currency_str'] = amount_currency and formatLang( self.env, abs(amount_currency), currency_obj=line_currency) or "" ret_line[ 'total_amount_currency_str'] = total_amount_currency and formatLang( self.env, abs(total_amount_currency), currency_obj=line_currency) or "" ret.append(ret_line) return ret
def _get_report_line_move_line(self, options, partner, aml, cumulated_init_balance, cumulated_balance): if aml['payment_id']: caret_type = 'account.payment' elif aml['move_type'] in ('in_refund', 'in_invoice', 'in_receipt'): caret_type = 'account.invoice.in' elif aml['move_type'] in ('out_refund', 'out_invoice', 'out_receipt'): caret_type = 'account.invoice.out' else: caret_type = 'account.move' date_maturity = aml['date_maturity'] and format_date( self.env, fields.Date.from_string(aml['date_maturity'])) columns = [ { 'name': aml['journal_code'] }, { 'name': aml['account_code'] }, { 'name': self._format_aml_name(aml['name'], aml['ref'], aml['move_name']) }, { 'name': date_maturity or '', 'class': 'date' }, { 'name': aml['full_rec_name'] or '' }, { 'name': self.format_value(cumulated_init_balance), 'class': 'number' }, { 'name': self.format_value(aml['debit'], blank_if_zero=True), 'class': 'number' }, { 'name': self.format_value(aml['credit'], blank_if_zero=True), 'class': 'number' }, ] if self.user_has_groups('base.group_multi_currency'): if aml['currency_id']: currency = self.env['res.currency'].browse(aml['currency_id']) formatted_amount = self.format_value(aml['amount_currency'], currency=currency, blank_if_zero=True) columns.append({'name': formatted_amount, 'class': 'number'}) else: columns.append({'name': ''}) columns.append({ 'name': self.format_value(cumulated_balance), 'class': 'number' }) return { 'id': aml['id'], 'parent_id': 'partner_%s' % partner.id, 'name': format_date(self.env, aml['date']), 'class': 'date', 'columns': columns, 'caret_options': caret_type, 'level': 4, # making this function return the sql id 'payment': aml['payment_id'], #providing an error 'account': aml['account_id'] }
def _check_hash_integrity(self): """Checks that all posted moves have still the same data as when they were posted and raises an error with the result. """ def build_move_info(move): return (move.name, move.inalterable_hash, fields.Date.to_string(move.date)) journals = self.env['account.journal'].search([('company_id', '=', self.id)]) results_by_journal = { 'results': [], 'printing_date': format_date(self.env, fields.Date.to_string(fields.Date.today())) } for journal in journals: rslt = { 'journal_name': journal.name, 'journal_code': journal.code, 'restricted_by_hash_table': journal.restrict_mode_hash_table and 'V' or 'X', 'msg_cover': '', 'first_hash': 'None', 'first_move_name': 'None', 'first_move_date': 'None', 'last_hash': 'None', 'last_move_name': 'None', 'last_move_date': 'None', } if not journal.restrict_mode_hash_table: rslt.update( {'msg_cover': _('This journal is not in strict mode.')}) results_by_journal['results'].append(rslt) continue all_moves_count = self.env['account.move'].search_count([ ('state', '=', 'posted'), ('journal_id', '=', journal.id) ]) moves = self.env['account.move'].search( [('state', '=', 'posted'), ('journal_id', '=', journal.id), ('secure_sequence_number', '!=', 0)], order="secure_sequence_number ASC") if not moves: rslt.update({ 'msg_cover': _('There isn\'t any journal entry flagged for data inalterability yet for this journal.' ), }) results_by_journal['results'].append(rslt) continue previous_hash = u'' start_move_info = [] hash_corrupted = False for move in moves: if move.inalterable_hash != move._compute_hash( previous_hash=previous_hash): rslt.update({ 'msg_cover': _('Corrupted data on journal entry with id %s.') % move.id }) results_by_journal['results'].append(rslt) hash_corrupted = True break if not previous_hash: #save the date and sequence number of the first move hashed start_move_info = build_move_info(move) previous_hash = move.inalterable_hash end_move_info = build_move_info(move) if hash_corrupted: continue rslt.update({ 'first_move_name': start_move_info[0], 'first_hash': start_move_info[1], 'first_move_date': format_date(self.env, start_move_info[2]), 'last_move_name': end_move_info[0], 'last_hash': end_move_info[1], 'last_move_date': format_date(self.env, end_move_info[2]), }) if len(moves) == all_moves_count: rslt.update({'msg_cover': _('All entries are hashed.')}) else: rslt.update({ 'msg_cover': _('Entries are hashed from %s (%s)') % (start_move_info[0], format_date(self.env, start_move_info[2])) }) results_by_journal['results'].append(rslt) return results_by_journal
def _get_move_dict_vals_change_period(self): # set the change_period account on the selected journal items accrual_account = self.revenue_accrual_account if self.account_type == 'income' else self.expense_accrual_account total_percentage = sum(self.chg_period_line_ids.mapped('percentage')) move_data = { 'original_dates': {}, 'new_dates': {}, } # ==== Prepare journal entries (account.move) ==== for date, grouped_lines in groupby(self.move_line_ids, lambda line: line.date): grouped_lines = list(grouped_lines) amount = sum(l.balance for l in grouped_lines) move_data['original_dates'][date] = { 'move_type': 'entry', 'ref': self._format_strings( _('Adjusting Entry of {date} ({percent:f}% recognized on {new_date})' ), grouped_lines[0].move_id, amount), 'date': fields.Date.to_string(date), 'journal_id': self.journal_id.id, 'line_ids': [], } for line in self.chg_period_line_ids: ref = _("Adjusting Entry made on {date} ({percent:f}%)").format( date=format_date(self.env, line.date), percent=line.percentage, ) move_data['new_dates'][line.date] = { 'move_type': 'entry', 'ref': ref, 'date': fields.Date.to_string(line.date), 'journal_id': self.journal_id.id, 'line_ids': [], } # ==== Prepare journal items (account.move.line) ==== for aml in self.move_line_ids: total_reported_balance = 0.0 total_reported_amount_currency = 0.0 # Avoid rounding issues with 100%. if round(total_percentage, 2) == 100.0: total_balance_to_report = aml.balance total_amount_currency_to_report = aml.amount_currency else: total_balance_to_report = aml.company_currency_id.round( (total_percentage / 100) * aml.balance) total_amount_currency_to_report = aml.currency_id.round( (total_percentage / 100) * aml.amount_currency) for i, line in enumerate(self.chg_period_line_ids): # Avoid rounding issue on the last line. if i == len(self.chg_period_line_ids) - 1: reported_balance = total_balance_to_report - total_reported_balance reported_amount_currency = total_amount_currency_to_report - total_reported_amount_currency else: reported_balance = aml.company_currency_id.round( (line.percentage / 100) * aml.balance) reported_amount_currency = aml.currency_id.round( (line.percentage / 100) * aml.amount_currency) total_reported_balance += reported_balance total_reported_amount_currency += reported_amount_currency move_data['new_dates'][line.date]['line_ids'] += [ (0, 0, { 'name': aml.name or '', 'currency_id': aml.currency_id.id, 'account_id': aml.account_id.id, 'partner_id': aml.partner_id.id, 'debit': reported_balance if reported_balance > 0.0 else 0.0, 'credit': -reported_balance if reported_balance < 0.0 else 0.0, 'amount_currency': reported_amount_currency, }), (0, 0, { 'name': _('Adjusting Entry'), 'currency_id': aml.currency_id.id, 'account_id': accrual_account.id, 'partner_id': aml.partner_id.id, 'debit': -reported_balance if reported_balance < 0.0 else 0.0, 'credit': reported_balance if reported_balance > 0.0 else 0.0, 'amount_currency': -reported_amount_currency, }), ] move_data['original_dates'][aml.date]['line_ids'] += [ (0, 0, { 'name': aml.name or '', 'currency_id': aml.currency_id.id, 'account_id': aml.account_id.id, 'partner_id': aml.partner_id.id, 'debit': -total_reported_balance if total_reported_balance < 0.0 else 0.0, 'credit': total_reported_balance if total_reported_balance > 0.0 else 0.0, 'amount_currency': -total_reported_amount_currency, }), (0, 0, { 'name': _('Adjusting Entry'), 'currency_id': aml.currency_id.id, 'account_id': accrual_account.id, 'partner_id': aml.partner_id.id, 'debit': total_reported_balance if total_reported_balance > 0.0 else 0.0, 'credit': -total_reported_balance if total_reported_balance < 0.0 else 0.0, 'amount_currency': total_reported_amount_currency, }), ] return list(move_data['original_dates'].values()) + list( move_data['new_dates'].values())
def _get_aml_line(self, options, account, aml, cumulated_balance): if aml['payment_id']: caret_type = 'account.payment' elif aml['move_type'] in ('in_refund', 'in_invoice', 'in_receipt'): caret_type = 'account.invoice.in' elif aml['move_type'] in ('out_refund', 'out_invoice', 'out_receipt'): caret_type = 'account.invoice.out' else: caret_type = 'account.move' if aml['ref'] and aml['name']: title = '%s - %s' % (aml['name'], aml['ref']) elif aml['ref']: title = aml['ref'] elif aml['name']: title = aml['name'] else: title = '' if aml['currency_id']: currency = self.env['res.currency'].browse(aml['currency_id']) else: currency = False return { 'id': aml['id'], 'caret_options': caret_type, 'class': 'top-vertical-align', 'parent_id': 'account_%d' % aml['account_id'], 'name': aml['move_name'], 'columns': [ { 'name': format_date(self.env, aml['date']), 'class': 'date' }, { 'name': self._format_aml_name(aml['name'], aml['ref'], aml['move_name']), 'title': title, 'class': 'whitespace_print' }, { 'name': aml['partner_name'], 'title': aml['partner_name'], 'class': 'whitespace_print' }, { 'name': currency and self.format_value(aml['amount_currency'], currency=currency, blank_if_zero=True) or '', 'class': 'number' }, { 'name': self.format_value(aml['debit'], blank_if_zero=True), 'class': 'number' }, { 'name': self.format_value(aml['credit'], blank_if_zero=True), 'class': 'number' }, { 'name': self.format_value(cumulated_balance), 'class': 'number' }, ], 'level': 4, }
def test_01_code_and_format(self): date_str = '2017-01-31' lang = self.env['res.lang'] # Activate French and Simplified Chinese (test with non-ASCII characters) lang.search([('active', '=', False), ('code', 'in', ['fr_FR', 'zh_CN'])]).write({'active': True}) # -- test `date` # Change a single parameter self.assertEqual( misc.format_date(lang.with_context(lang='fr_FR').env, date_str), '31/01/2017') self.assertEqual( misc.format_date(lang.env, date_str, lang_code='fr_FR'), '31/01/2017') self.assertEqual( misc.format_date(lang.env, date_str, date_format='MMM d, y'), 'Jan 31, 2017') # Change 2 parameters self.assertEqual( misc.format_date(lang.with_context(lang='zh_CN').env, date_str, lang_code='fr_FR'), '31/01/2017') self.assertEqual( misc.format_date(lang.with_context(lang='zh_CN').env, date_str, date_format='MMM d, y'), u'1\u6708 31, 2017') self.assertEqual( misc.format_date(lang.env, date_str, lang_code='fr_FR', date_format='MMM d, y'), 'janv. 31, 2017') # Change 3 parameters self.assertEqual( misc.format_date(lang.with_context(lang='zh_CN').env, date_str, lang_code='en_US', date_format='MMM d, y'), 'Jan 31, 2017') # -- test `datetime` datetime_str = '2017-01-31 10:33:00' # Change languages and timezones self.assertEqual( misc.format_datetime(lang.with_context(lang='fr_FR').env, datetime_str, tz='Europe/Brussels'), '31 janv. 2017 à 11:33:00') self.assertEqual( misc.format_datetime(lang.with_context(lang='zh_CN').env, datetime_str, tz='America/New_York'), '2017\u5E741\u670831\u65E5 \u4E0A\u53485:33:00' ) # '2017年1月31日 上午5:33:00' # Change language, timezone and format self.assertEqual( misc.format_datetime(lang.with_context(lang='fr_FR').env, datetime_str, tz='America/New_York', dt_format='short'), '31/01/2017 05:33') self.assertEqual( misc.format_datetime(lang.with_context(lang='en_US').env, datetime_str, tz='Europe/Brussels', dt_format='MMM d, y'), 'Jan 31, 2017') # Check given `lang_code` overwites context lang self.assertEqual( misc.format_datetime(lang.env, datetime_str, tz='Europe/Brussels', dt_format='long', lang_code='fr_FR'), '31 janvier 2017 à 11:33:00 +0100') self.assertEqual( misc.format_datetime(lang.with_context(lang='zh_CN').env, datetime_str, tz='Europe/Brussels', dt_format='long', lang_code='en_US'), 'January 31, 2017 at 11:33:00 AM +0100') # -- test `time` time_part = datetime.time(16, 30, 22) time_part_tz = datetime.time( 16, 30, 22, tzinfo=pytz.timezone('US/Eastern')) # 4:30 PM timezoned self.assertEqual( misc.format_time(lang.with_context(lang='fr_FR').env, time_part), '16:30:22') self.assertEqual( misc.format_time(lang.with_context(lang='zh_CN').env, time_part), '\u4e0b\u53484:30:22') # Check format in different languages self.assertEqual( misc.format_time(lang.with_context(lang='fr_FR').env, time_part, time_format='short'), '16:30') self.assertEqual( misc.format_time(lang.with_context(lang='zh_CN').env, time_part, time_format='short'), '\u4e0b\u53484:30') # Check timezoned time part self.assertEqual( misc.format_time(lang.with_context(lang='fr_FR').env, time_part_tz, time_format='long'), '16:30:22 -0504') self.assertEqual( misc.format_time(lang.with_context(lang='zh_CN').env, time_part_tz, time_format='full'), '\u5317\u7f8e\u4e1c\u90e8\u6807\u51c6\u65f6\u95f4\u0020\u4e0b\u53484:30:22' ) # Check given `lang_code` overwites context lang self.assertEqual( misc.format_time(lang.with_context(lang='fr_FR').env, time_part, time_format='short', lang_code='zh_CN'), '\u4e0b\u53484:30') self.assertEqual( misc.format_time(lang.with_context(lang='zh_CN').env, time_part, time_format='medium', lang_code='fr_FR'), '16:30:22')
def action_move_create(self): res = super(AccountInvoice, self).action_move_create() dichiarazione_model = self.env['dichiarazione.intento'] # ------ Check if there is enough available amount on dichiarazioni for invoice in self: if invoice.dichiarazione_intento_ids: dichiarazioni = invoice.dichiarazione_intento_ids else: dichiarazioni = dichiarazione_model.with_context( ignore_state=True if invoice.type. endswith('_refund') else False).get_valid( type_d=invoice.type.split('_')[0], partner_id=invoice.partner_id.id, date=invoice.date_invoice) # ----- If partner hasn't dichiarazioni, do nothing if not dichiarazioni: # ---- check se posizione fiscale dichiarazione di intento # ---- e non ho dichiarazioni, segnalo errore if self.fiscal_position_id.valid_for_dichiarazione_intento: raise UserError( _('Declaration of intent not found. Add new declaration or ' 'change fiscal position and verify applied tax')) else: continue sign = 1 if invoice.type in ['out_invoice', 'in_refund'] else -1 dichiarazioni_amounts = {} for tax_line in invoice.tax_line_ids: amount = sign * tax_line.base for dichiarazione in dichiarazioni: if dichiarazione.id not in dichiarazioni_amounts: dichiarazioni_amounts[dichiarazione.id] = \ dichiarazione.available_amount if tax_line.tax_id.id in [ t.id for t in dichiarazione.taxes_ids ]: dichiarazioni_amounts[dichiarazione.id] -= amount dichiarazioni_residual = sum( [dichiarazioni_amounts[da] for da in dichiarazioni_amounts]) if dichiarazioni_residual < 0: raise UserError( _('Available plafond insufficent.\n' 'Excess value: %s') % (abs(dichiarazioni_residual))) # Check se con nota credito ho superato il plafond for dich in dichiarazioni_amounts: dichiarazione = dichiarazione_model.browse(dich) # dichiarazioni_amounts contains residual, so, if > limit_amount, # used_amount went < 0 if dichiarazioni_amounts[dich] > dichiarazione.limit_amount: raise UserError( _('Available plafond insufficent.\n' 'Excess value: %s') % (abs(dichiarazioni_amounts[dich] - dichiarazione.limit_amount))) # ----- Assign account move lines to dichiarazione for invoices for invoice in self: if invoice.dichiarazione_intento_ids: dichiarazioni = invoice.dichiarazione_intento_ids else: dichiarazioni = dichiarazione_model.with_context( ignore_state=True if invoice.type. endswith('_refund') else False).get_valid( type_d=invoice.type.split('_')[0], partner_id=invoice.partner_id.id, date=invoice.date_invoice) # ----- If partner hasn't dichiarazioni, do nothing if not dichiarazioni: continue # ----- Get only lines with taxes lines = invoice.move_id.line_ids.filtered(lambda l: l.tax_ids) if not lines: continue # ----- Group lines for tax grouped_lines = {} sign = -1 if invoice.type.endswith('_refund') else 1 # sign = 1 if invoice.type in ('in_invoice', 'out_refund') else -1 for line in lines: force_declaration = line.force_dichiarazione_intento_id tax = line.tax_ids[0] if force_declaration not in list(grouped_lines.keys()): grouped_lines.update({force_declaration: {}}) if tax not in grouped_lines[force_declaration]: grouped_lines[force_declaration].update({tax: []}) grouped_lines[force_declaration][tax].append(line) for force_declaration in grouped_lines.keys(): for tax, lines in grouped_lines[force_declaration].items(): # ----- Create a detail in dichiarazione # for every tax group if invoice.type in ('out_invoice', 'in_refund'): amount = sum([ sign * (line.credit - line.debit) for line in lines ]) else: amount = sum([ sign * (line.debit - line.credit) for line in lines ]) # Select right declaration(s) if force_declaration: declarations = [ force_declaration, ] else: declarations = dichiarazioni for dichiarazione in declarations: if tax not in dichiarazione.taxes_ids: continue dichiarazione.line_ids = [(0, 0, { 'taxes_ids': [(6, 0, [ tax.id, ])], 'move_line_ids': [(6, 0, [l.id for l in lines])], 'amount': amount, 'invoice_id': invoice.id, 'base_amount': invoice.amount_untaxed, 'currency_id': invoice.currency_id.id, })] # ----- Link dichiarazione to invoice invoice.dichiarazione_intento_ids = [ (4, dichiarazione.id) ] if invoice.type in ("out_invoice", "out_refund"): if not invoice.comment: invoice.comment = '' invoice.comment += ( "\n\nVostra dichiarazione d'intento nr %s del %s, " "nostro protocollo nr %s del %s, " "protocollo telematico nr %s." % (dichiarazione.partner_document_number, format_date( self.env, dichiarazione.partner_document_date), dichiarazione.number, format_date(self.env, dichiarazione.date), dichiarazione.telematic_protocol)) return res
def _get_statement_line(self, st_line): """ Returns the data required by the bank statement reconciliation widget to display a statement line """ statement_currency = st_line.journal_id.currency_id or st_line.journal_id.company_id.currency_id if st_line.amount_currency and st_line.currency_id: amount = st_line.amount_currency amount_currency = st_line.amount amount_currency_str = formatLang(self.env, abs(amount_currency), currency_obj=statement_currency) else: amount = st_line.amount amount_currency = amount amount_currency_str = "" amount_str = formatLang(self.env, abs(amount), currency_obj=st_line.currency_id or statement_currency) date = misc.format_date(self.env, st_line.date, lang_code=self.env.user.lang) data = { 'id': st_line.id, 'ref': st_line.ref, 'note': st_line.note or "", 'name': st_line.name, 'date': date, 'amount': amount, 'amount_str': amount_str, # Amount in the statement line currency 'currency_id': st_line.currency_id.id or statement_currency.id, 'partner_id': st_line.partner_id.id, 'journal_id': st_line.journal_id.id, 'statement_id': st_line.statement_id.id, 'account_id': [ st_line.journal_id.default_debit_account_id.id, st_line.journal_id.default_debit_account_id.display_name ], 'account_code': st_line.journal_id.default_debit_account_id.code, 'account_name': st_line.journal_id.default_debit_account_id.name, 'partner_name': st_line.partner_id.name, 'communication_partner_name': st_line.partner_name, 'amount_currency_str': amount_currency_str, # Amount in the statement currency 'amount_currency': amount_currency, # Amount in the statement currency 'has_no_partner': not st_line.partner_id.id, 'company_id': st_line.company_id.id, } if st_line.partner_id: if amount > 0: data[ 'open_balance_account_id'] = st_line.partner_id.property_account_receivable_id.id else: data[ 'open_balance_account_id'] = st_line.partner_id.property_account_payable_id.id return data
def confirm(self): """ Search all the related account.move.line and will create the related inflation adjustment journal entry for the specification. """ def FormatAmount(amount): return formatLang(self.env, amount, currency_obj=self.company_id.currency_id) self.ensure_one() account_move_line = self.env['account.move.line'] adjustment_total = {'debit': 0.0, 'credit': 0.0} lines = [] # Generate account.move.line adjustment for start of the period domain = self.get_move_line_domain() domain += [("account_id.user_type_id.include_initial_balance", '=', True), ('date', '<', self.date_from)] init_data = account_move_line.read_group( domain, ['account_id', 'balance'], ['account_id'], ) date_from = self.date_from date_to = self.date_to before_date_from = self.date_from + relativedelta(months=-1) before_index = self.env['inflation.adjustment.index'].find( before_date_from) periods = self.env['inflation.adjustment'].get_periods( before_date_from, self.date_from) initial_factor = (self.end_index / before_index.value) - 1.0 for line in init_data: adjustment = line.get('balance') * initial_factor if self.company_id.currency_id.is_zero(adjustment): continue else: adjustment = self.company_id.currency_id.round(adjustment) lines.append({ 'account_id': line.get('account_id')[0], 'name': _('Ajuste por inflación cuentas al inicio ' '(%s * %.2f%%)') % (FormatAmount(line.get('balance')), initial_factor * 100.0), 'date_maturity': before_date_from, 'debit' if adjustment > 0 else 'credit': abs(adjustment), 'analytic_account_id': self.analytic_account_id.id, }) adjustment_total['debit' if adjustment > 0 else 'credit'] += abs( adjustment) # Get period month list periods = self.get_periods() for period in periods: # search account.move.lines domain = self.get_move_line_domain() domain += [('date', '>=', period.get('date_from')), ('date', '<=', period.get('date_to'))] data = account_move_line.read_group(domain, ['account_id', 'balance'], ['account_id', 'date']) date_from = period.get('date_from') for line in data: adjustment = line.get('balance') * period.get('factor') if self.company_id.currency_id.is_zero(adjustment): continue else: adjustment = self.company_id.currency_id.round(adjustment) lines.append({ 'account_id': line.get('account_id')[0], 'name': _('Ajuste por inflación %s ' '(%s * %.2f%%)') % (format_date(self.env, date_from, date_format='MM/Y'), FormatAmount( line.get('balance')), period.get('factor') * 100.0), 'date_maturity': period.get('date_from'), 'debit' if adjustment > 0 else 'credit': abs(adjustment), 'analytic_account_id': self.analytic_account_id.id, }) adjustment_total[ 'debit' if adjustment > 0 else 'credit'] += abs(adjustment) if not lines: raise UserError( _("No hemos encontrado ningún asiento contable asociado al" " periodo seleccionado.")) # Generate total amount adjustment line adj_diff = adjustment_total.get('debit', 0.0) - adjustment_total.get( 'credit', 0.0) lines.append({ 'account_id': self.account_id.id, 'name': _('Ajuste por inflación Global [%s] / [%s]') % (self.date_from, self.date_to), 'debit' if adj_diff < 0 else 'credit': abs(adj_diff), 'date_maturity': self.date_to, 'analytic_account_id': self.analytic_account_id.id, }) # Generate account.move move = self.env['account.move'].create({ 'journal_id': self.journal_id.id, 'date': self.date_to, 'ref': _('Ajuste por inflación %s') % (date_to.year), 'line_ids': [(0, 0, line_data) for line_data in lines], }) return move.get_access_action()
def _get_lines(self, options, line_id=None): offset = int(options.get('lines_offset', 0)) lines = [] context = self.env.context company_id = self.env.user.company_id used_currency = company_id.currency_id dt_from = options['date'].get('date_from') line_id = line_id and int(line_id.split('_')[1]) or None aml_lines = [] # Aml go back to the beginning of the user chosen range but the amount on the account line should go back to either the beginning of the fy or the beginning of times depending on the account grouped_accounts = self.with_context( date_from_aml=dt_from, date_from=dt_from and company_id.compute_fiscalyear_dates( fields.Date.from_string(dt_from))['date_from'] or None)._group_by_account_id(options, line_id) sorted_accounts = sorted(grouped_accounts, key=lambda a: a.code) unfold_all = context.get('print_mode') and len( options.get('unfolded_lines')) == 0 sum_debit = sum_credit = sum_balance = 0 for account in sorted_accounts: display_name = account.code + " " + account.name if options.get('filter_accounts'): #skip all accounts where both the code and the name don't start with the given filtering string if not any([ display_name_part.startswith( options.get('filter_accounts')) for display_name_part in display_name.split(' ') ]): continue debit = grouped_accounts[account]['debit'] credit = grouped_accounts[account]['credit'] balance = grouped_accounts[account]['balance'] sum_debit += debit sum_credit += credit sum_balance += balance amount_currency = '' if not account.currency_id else self.with_context( no_format=False).format_value( grouped_accounts[account]['amount_currency'], currency=account.currency_id) # don't add header for `load more` if offset == 0: lines.append({ 'id': 'account_%s' % (account.id, ), 'name': len(display_name) > 40 and not context.get('print_mode') and display_name[:40] + '...' or display_name, 'title_hover': display_name, 'columns': [{ 'name': v } for v in [ amount_currency, self.format_value(debit), self.format_value(credit), self.format_value(balance) ]], 'level': 2, 'unfoldable': True, 'unfolded': 'account_%s' % (account.id, ) in options.get('unfolded_lines') or unfold_all, 'colspan': 4, }) if 'account_%s' % (account.id, ) in options.get( 'unfolded_lines') or unfold_all: initial_debit = grouped_accounts[account]['initial_bal'][ 'debit'] initial_credit = grouped_accounts[account]['initial_bal'][ 'credit'] initial_balance = grouped_accounts[account]['initial_bal'][ 'balance'] initial_currency = '' if not account.currency_id else self.with_context( no_format=False).format_value( grouped_accounts[account]['initial_bal'] ['amount_currency'], currency=account.currency_id) domain_lines = [] if offset == 0: domain_lines.append({ 'id': 'initial_%s' % (account.id, ), 'class': 'o_account_reports_initial_balance', 'name': _('Initial Balance'), 'parent_id': 'account_%s' % (account.id, ), 'columns': [{ 'name': v } for v in [ '', '', '', initial_currency, self.format_value(initial_debit), self.format_value(initial_credit), self.format_value(initial_balance) ]], }) progress = initial_balance else: # for load more: progress = float( options.get('lines_progress', initial_balance)) amls = grouped_accounts[account]['lines'] remaining_lines = 0 if not context.get('print_mode'): remaining_lines = grouped_accounts[account][ 'total_lines'] - offset - len(amls) for line in amls: if options.get('cash_basis'): line_debit = line.debit_cash_basis line_credit = line.credit_cash_basis else: line_debit = line.debit line_credit = line.credit date = amls.env.context.get('date') or fields.Date.today() line_debit = line.company_id.currency_id._convert( line_debit, used_currency, company_id, date) line_credit = line.company_id.currency_id._convert( line_credit, used_currency, company_id, date) progress = progress + line_debit - line_credit currency = "" if not line.currency_id else self.with_context( no_format=False).format_value( line.amount_currency, currency=line.currency_id) name = line.name and line.name or '' if line.ref: name = name and name + ' - ' + line.ref or line.ref name_title = name # Don't split the name when printing if len(name) > 35 and not self.env.context.get( 'no_format') and not self.env.context.get( 'print_mode'): name = name[:32] + "..." partner_name = line.partner_id.name partner_name_title = partner_name if partner_name and len( partner_name) > 35 and not self.env.context.get( 'no_format') and not self.env.context.get( 'print_mode'): partner_name = partner_name[:32] + "..." caret_type = 'account.move' if line.invoice_id: caret_type = 'account.invoice.in' if line.invoice_id.type in ( 'in_refund', 'in_invoice') else 'account.invoice.out' elif line.payment_id: caret_type = 'account.payment' columns = [{ 'name': v } for v in [ format_date(self.env, line.date), name, partner_name, currency, line_debit != 0 and self.format_value( line_debit) or '', line_credit != 0 and self.format_value(line_credit) or '', self.format_value(progress) ]] columns[1]['class'] = 'whitespace_print' columns[2]['class'] = 'whitespace_print' columns[1]['title'] = name_title columns[2]['title'] = partner_name_title line_value = { 'id': line.id, 'caret_options': caret_type, 'class': 'top-vertical-align', 'parent_id': 'account_%s' % (account.id, ), 'name': line.move_id.name if line.move_id.name else '/', 'columns': columns, 'level': 4, } aml_lines.append(line.id) domain_lines.append(line_value) # load more if remaining_lines > 0: domain_lines.append({ 'id': 'loadmore_%s' % account.id, # if MAX_LINES is None, there will be no remaining lines # so this should not cause a problem 'offset': offset + self.MAX_LINES, 'progress': progress, 'class': 'o_account_reports_load_more text-center', 'parent_id': 'account_%s' % (account.id, ), 'name': _('Load more... (%s remaining)') % remaining_lines, 'colspan': 7, 'columns': [{}], }) # don't add total line for `load more` if offset == 0: domain_lines.append({ 'id': 'total_' + str(account.id), 'class': 'o_account_reports_domain_total', 'parent_id': 'account_%s' % (account.id, ), 'name': _('Total '), 'columns': [{ 'name': v } for v in [ '', '', '', amount_currency, self.format_value(debit), self.format_value(credit), self.format_value(balance) ]], }) lines += domain_lines if not line_id: lines.append({ 'id': 'general_ledger_total_%s' % company_id.id, 'name': _('Total'), 'class': 'total', 'level': 1, 'columns': [{ 'name': v } for v in [ '', '', '', '', self.format_value(sum_debit), self.format_value(sum_credit), self.format_value(sum_balance) ]], }) journals = [j for j in options.get('journals') if j.get('selected')] operatings = [ opp for opp in options.get('operatings') if opp.get('selected') ] print('++++++', operatings) if len(journals) == 1 and journals[0].get('type') in [ 'sale', 'purchase' ] and not line_id: lines.append({ 'id': 0, 'name': _('Tax Declaration'), 'columns': [{ 'name': v } for v in ['', '', '', '', '', '', '']], 'level': 1, 'unfoldable': False, 'unfolded': False, }) lines.append({ 'id': 0, 'name': _('Name'), 'columns': [{ 'name': v } for v in ['', '', '', '', _('Base Amount'), _('Tax Amount'), '']], 'level': 2, 'unfoldable': False, 'unfolded': False, }) journal_currency = self.env['account.journal'].browse( journals[0]['id']).company_id.currency_id for tax, values in self._get_taxes(journals[0]).items(): base_amount = journal_currency._convert( values['base_amount'], used_currency, company_id, options['date_to']) tax_amount = journal_currency._convert(values['tax_amount'], used_currency, company_id, options['date_to']) lines.append({ 'id': '%s_tax' % (tax.id, ), 'name': tax.name + ' (' + str(tax.amount) + ')', 'caret_options': 'account.tax', 'unfoldable': False, 'columns': [{ 'name': v } for v in [ '', '', '', '', self.format_value(base_amount), self.format_value(tax_amount), '' ]], 'colspan': 5, 'level': 4, }) if self.env.context.get('aml_only', False): return aml_lines return lines
def _get_name(self): for rec in self: if rec.employee_id: rec.name = '%s - %s ' % ( 'Element Variable ' + rec.employee_id.name or '', format_date(rec.env, rec.date_from, date_format="MMMM y"))
def _check_pos_hash_integrity(self): """Checks that all posted or invoiced pos orders have still the same data as when they were posted and raises an error with the result. """ def build_order_info(order): entry_reference = _('(Receipt ref.: %s)') order_reference_string = order.pos_reference and entry_reference % order.pos_reference or '' return [ ctx_tz(order, 'date_order'), order.l10n_fr_hash, order.name, order_reference_string, ctx_tz(order, 'write_date') ] hash_verified = True msg_alert = '' report_dict = {} if self._is_accounting_unalterable(): orders = self.env['pos.order'].search( [('state', 'in', ['paid', 'done', 'invoiced']), ('company_id', '=', self.id), ('l10n_fr_secure_sequence_number', '!=', 0)], order="l10n_fr_secure_sequence_number ASC") if not orders: msg_alert = (_( 'There isn\'t any order flagged for data inalterability yet for the company %s. This mechanism only runs for point of sale orders generated after the installation of the module France - Certification CGI 286 I-3 bis. - POS', self.env.company.name)) hash_verified = False previous_hash = u'' start_order_info = [] for order in orders: if order.l10n_fr_hash != order._compute_hash( previous_hash=previous_hash): msg_alert = (_( 'Corrupted data on point of sale order with id %s.', order.id)) hash_verified = False break previous_hash = order.l10n_fr_hash if hash_verified: orders_sorted_date = orders.sorted(lambda o: o.date_order) start_order_info = build_order_info(orders_sorted_date[0]) end_order_info = build_order_info(orders_sorted_date[-1]) report_dict.update({ 'first_order_name': start_order_info[2], 'first_order_hash': start_order_info[1], 'first_order_date': start_order_info[0], 'last_order_name': end_order_info[2], 'last_order_hash': end_order_info[1], 'last_order_date': end_order_info[0], }) return { 'result': hash_verified and report_dict or 'None', 'msg_alert': msg_alert or 'None', 'printing_date': format_date(self.env, Date.to_string(Date.today())), }
def _get_lines(self, options, line_id=None): sign = -1.0 if self.env.context.get('aged_balance') else 1.0 lines = [] account_types = [self.env.context.get('account_type')] results, total, amls = self.env[ 'report.account.report_agedpartnerbalance'].with_context( include_nullified_amount=True)._get_partner_move_lines( account_types, self._context['date_to'], 'posted', 30) for values in results: if line_id and 'partner_%s' % (values['partner_id'], ) != line_id: continue vals = { 'id': 'partner_%s' % (values['partner_id'], ), 'name': values['name'], 'level': 2, 'columns': [{ 'name': '' }] * 3 + [{ 'name': self.format_value(sign * v) } for v in [ values['direction'], values['4'], values['3'], values['2'], values['1'], values['0'], values['total'] ]], 'trust': values['trust'], 'unfoldable': True, 'unfolded': 'partner_%s' % (values['partner_id'], ) in options.get('unfolded_lines'), } lines.append(vals) if 'partner_%s' % (values['partner_id'], ) in options.get( 'unfolded_lines'): for line in amls[values['partner_id']]: aml = line['line'] caret_type = 'account.move' if aml.invoice_id: caret_type = 'account.invoice.in' if aml.invoice_id.type in ( 'in_refund', 'in_invoice') else 'account.invoice.out' elif aml.payment_id: caret_type = 'account.payment' vals = { 'id': aml.id, 'name': format_date(self.env, aml.date_maturity or aml.date), 'class': 'date', 'caret_options': caret_type, 'level': 4, 'parent_id': 'partner_%s' % (values['partner_id'],), 'columns': [{'name': v} for v in [aml.journal_id.code, aml.account_id.code, self._format_aml_name(aml)]] +\ [{'name': v} for v in [line['period'] == 6-i and self.format_value(sign * line['amount']) or '' for i in range(7)]], 'action_context': aml.get_action_context(), } lines.append(vals) if total and not line_id: total_line = { 'id': 0, 'name': _('Total'), 'class': 'total', 'level': 2, 'columns': [{ 'name': '' }] * 3 + [{ 'name': self.format_value(sign * v) } for v in [ total[6], total[4], total[3], total[2], total[1], total[0], total[5] ]], } lines.append(total_line) return lines