def get_statement_line_for_reconciliation(self, cr, uid, id, context=None): """ Returns the data required by the bank statement reconciliation use case """ line = self.browse(cr, uid, id, context=context) statement_currency = line.journal_id.currency or line.journal_id.company_id.currency_id rml_parser = report_sxw.rml_parse(cr, uid, 'statement_line_widget', context=context) amount_str = line.amount > 0 and line.amount or -line.amount amount_str = rml_parser.formatLang(amount_str, currency_obj=statement_currency) amount_currency_str = "" if line.amount_currency and line.currency_id: amount_currency_str = rml_parser.formatLang(line.amount_currency, currency_obj=line.currency_id) dict = { 'id': line.id, 'ref': line.ref, 'note': line.note or "", 'name': line.name, 'date': line.date, 'amount': line.amount, 'amount_str': amount_str, 'no_match': self.get_move_lines_counterparts(cr, uid, id, count=True, context=context) == 0 and line.partner_id.id, 'partner_id': line.partner_id.id, 'statement_id': line.statement_id.id, 'account_code': line.journal_id.default_debit_account_id.code, 'account_name': line.journal_id.default_debit_account_id.name, 'partner_name': line.partner_id.name, 'amount_currency_str': amount_currency_str, 'has_no_partner': not line.partner_id.id, } if line.partner_id.id: if line.amount > 0: dict['open_balance_account_id'] = line.partner_id.property_account_receivable.id else: dict['open_balance_account_id'] = line.partner_id.property_account_payable.id return dict
def _draw_description_line(self, canvas, print_settings, initial_position, font): """ Draw a line above the payment slip The line shows the invoice number and payment term. :param canvas: payment slip reportlab component to be drawn :type canvas: :py:class:`reportlab.pdfgen.canvas.Canvas` :param print_settings: layouts print setting :type print_settings: :py:class:`PaymentSlipSettings` or subclass :para initial_position: tuple of coordinate (x, y) :type initial_position: tuple :param font: font to use :type font: :py:class:`FontMeta` """ x, y = initial_position # align with the address x += print_settings.bvr_add_horz * inch invoice = self.move_line_id.invoice date_maturity = self.move_line_id.date_maturity message = _('Payment slip related to invoice %s ' 'due on the %s') rml_parser = report_sxw.rml_parse(self.env.cr, self.env.uid, 'payment_slip', context=self.env.context) fmt_date = rml_parser.formatLang(date_maturity, date=True) canvas.setFont(font.name, font.size) canvas.drawString(x, y, message % (invoice.number, fmt_date))
def _get_currency_help_label(self, cr, uid, line_currency_id, bank_rate, bank_currency_id, context=None): rml_parser = report_sxw.rml_parse(cr, uid, 'currency_help_label', context=context) currency_pool = self.pool.get('res.currency') line_currency_str = bank_rate_str = '' if line_currency_id: line_currency_str = rml_parser.formatLang( 1.00, currency_obj=currency_pool.browse(cr, uid, line_currency_id, context=context)) if bank_currency_id: bank_rate_str = rml_parser.formatLang( bank_rate, currency_obj=currency_pool.browse(cr, uid, bank_currency_id, context=context)) currency_help_label = _( 'At the operation date, the exchange rate was\n%s = %s') % ( line_currency_str, bank_rate_str) return currency_help_label
def get_results(self, pool, cr, uid, start, end, number_start): account_move_obj = pool.get('account.move') util_parser = rml_parse(cr, uid, 'internal') util_parser.objects = [] # FIXME util_parser.setLang('it_IT') # FIXME if (dateutil.parser.parse(end) - dateutil.parser.parse(start)).days > 31: raise Exception( "Puoi richiedere solo intervalli di un mese al massimo") move_ids = account_move_obj.search(cr, uid, [ ('date', '>=', start), ('date', '<=', end), ], order='date') moves = account_move_obj.browse(cr, uid, move_ids) char_attrs = "oe_list_field_cell oe_list_field_char" num_attrs = "oe_list_field_cell oe_list_field_float oe_number" date_attrs = "oe_list_field_cell oe_list_field_date" header_attrs = "oe_list_header" html = '<table class="oe_list_content"><tbody>' html += '<thead><tr class="oe_list_header_columns">' html += '</tr></thead>' for i, move in enumerate(moves): html += '<tr>' html += '<td style="width: 40px; font-weight: bold;" class="%s">%s</td>' % ( char_attrs, int(number_start or 1) + i) html += '<td style="width: 80px; font-weight: bold;" class="%s">%s</td>' % ( date_attrs, move.date) html += '<td style="width: 200px; font-weight: bold;" class="%s">%s</td>' % ( char_attrs, move.name) html += '<td style="width: 500px; font-weight: bold;" class="%s">%s</td>' % ( char_attrs, move.ref) html += '<td style="position: relative;"><br/><table style="margin: 20px 0px; position: relative; left: -420px;">' for line in move.line_id: html += '<tr>' html += '<td style="width: 70px;">%s</td>' % line.account_id.code html += '<td style="width: 300px;">%s</td>' % line.account_id.name html += '<td style="width: 400px;">%s</td>' % line.name html += '<td style="width: 100px;" class="%s">%s</td>' % ( num_attrs, util_parser.formatLang(line.debit) if line.debit else '') html += '<td style="width: 100px;" class="%s">%s</td>' % ( num_attrs, util_parser.formatLang(line.credit) if line.credit else '') html += '</tr>' html += '</table></td>' html += '</tr>' html += '</tbody></table>' return html
def _get_parser_context(self, model_instance, data): report_xml = self.ir_actions_report_xml_id context_instance = rml_parse(self.env.cr, self.env.uid, report_xml.name, context=self.env.context) context_instance.set_context(model_instance, data, model_instance.ids, report_xml.report_type) self._extend_parser_context(context_instance, report_xml) return context_instance.localcontext
def _get_currency_help_label(self, cr, uid, currency_id, payment_rate, payment_rate_currency_id, context=None): rml_parser = report_sxw.rml_parse(cr, uid, 'currency_help_label', context=context) currency_pool = self.pool.get('res.currency') currency_str = payment_rate_str = '' if currency_id: currency_str = rml_parser.formatLang(1, currency_obj=currency_pool.browse(cr, uid, currency_id, context=context)) if payment_rate_currency_id: payment_rate_str = rml_parser.formatLang(currency_pool.browse(cr, uid, currency_id, context=context).rate, currency_obj=currency_pool.browse(cr, uid, payment_rate_currency_id, context=context)) currency_help_label = _('At the operation date, the exchange rate was\n%s = %s') % (currency_str, payment_rate_str) return currency_help_label
def create_xml(self, cr, uid, ids, data, context): # Computing the dates (start of month: som, and end of month: eom) som = datetime.date(data["form"]["year"], data["form"]["month"], 1) eom = som + datetime.timedelta(lengthmonth(som.year, som.month)) date_xml = [ '<date month="%s" year="%d" />' % (self.get_month_name(cr, uid, som.month, context=context), som.year), "<days>", ] date_xml += [ '<day number="%d" name="%s" weekday="%d" />' % ( x, self.get_weekday_name(cr, uid, som.replace(day=x).weekday() + 1, context=context), som.replace(day=x).weekday() + 1, ) for x in range(1, lengthmonth(som.year, som.month) + 1) ] date_xml.append("</days>") date_xml.append("<cols>2.5cm%s,2cm</cols>\n" % (",0.7cm" * lengthmonth(som.year, som.month))) emp_xml = "" emp_obj = pooler.get_pool(cr.dbname).get("hr.employee") for id in data["form"]["employee_ids"]: user = emp_obj.browse(cr, uid, id).user_id.id empl_name = emp_obj.browse(cr, uid, id).name if user: emp_xml += emp_create_xml(cr, user, som, eom, empl_name) # Computing the xml # Without this, report don't show non-ascii characters (TO CHECK) date_xml = "\n".join(date_xml) rpt_obj = pooler.get_pool(cr.dbname).get("hr.employee") rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context) header_xml = """ <header> <date>%s</date> <company>%s</company> </header> """ % ( str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + " " + str(time.strftime("%H:%M")), toxml(pooler.get_pool(cr.dbname).get("res.users").browse(cr, uid, uid).company_id.name), ) xml = """<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s </report> """ % ( header_xml, date_xml, ustr(emp_xml), ) return xml
def create_xml(self, cr, uid, ids, data, context): registry = openerp.registry(cr.dbname) # Computing the dates (start of month: som, and end of month: eom) som = datetime.date(data['form']['year'], data['form']['month'], 1) eom = som + datetime.timedelta(lengthmonth(som.year, som.month)) date_xml = [ '<date month="%s" year="%d" />' % (self.get_month_name( cr, uid, som.month, context=context), som.year), '<days>' ] date_xml += [ '<day number="%d" name="%s" weekday="%d" />' % (x, self.get_weekday_name( cr, uid, som.replace(day=x).weekday() + 1, context=context), som.replace(day=x).weekday() + 1) for x in range(1, lengthmonth(som.year, som.month) + 1) ] date_xml.append('</days>') date_xml.append('<cols>2.5cm%s,2cm</cols>\n' % (',0.7cm' * lengthmonth(som.year, som.month))) emp_xml = '' emp_obj = registry['hr.employee'] for id in data['form']['employee_ids']: user = emp_obj.browse(cr, uid, id).user_id.id empl_name = emp_obj.browse(cr, uid, id).name if user: emp_xml += emp_create_xml(cr, user, som, eom, empl_name) # Computing the xml #Without this, report don't show non-ascii characters (TO CHECK) date_xml = '\n'.join(date_xml) rpt_obj = emp_obj rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context) header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), toxml(registry['res.users'].browse(cr, uid, uid).company_id.name)) xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s </report> ''' % (header_xml, date_xml, ustr(emp_xml)) return xml
def render_html(self, data=None): report_obj = self.env['report'] report = report_obj._get_report_from_name('cicon_prod.cicon_steel_order_in_hand_template') rml = report_sxw.rml_parse(self._cr, self._uid, 'cicon_steel_order_in_hand_template') docargs = { 'doc_ids': data.get('ids'), 'doc_model': report.model, 'docs': self.get_docs(data.get('ids')), 'formatLang': rml.formatLang, 'digit': self._context.get('digits', 0), 'heading': self._context.get('report_heading', ''), } return report_obj.render('cicon_prod.cicon_steel_order_in_hand_template', docargs)
def formatLang(env, value, digits=None, grouping=True, monetary=False, dp=False, currency_obj=False): rml_parser = report_sxw.rml_parse(env.cr, env.uid, 'format_lang_wrapper', context=env.context) return rml_parser.formatLang(value, digits=digits, grouping=grouping, monetary=monetary, dp=dp, currency_obj=currency_obj)
def default_get(self, cr, uid, fields, context=None): res = super(account_invoice_line_collection, self).default_get(cr, uid, fields, context=context) journal_id = False if context and context.get('active_ids', False): invoice_lines = self.pool.get('account.invoice.line').browse( cr, uid, context.get('active_ids', False)) rml_parser = report_sxw.rml_parse(cr, uid, 'reconciliation_widget_aml', context=context) notes = "Dear Admin Cabang %s, \n" % ( invoice_lines[0].analytic_destination and invoice_lines[0].analytic_destination.name or "") notes += "tolong followup resi cod dengan detail sebagai berikut: \n\n" n = 1 summary = 0.0 maxlen = 0 for x in invoice_lines: note = "%s %s %s %s\n" % ( n, x.name, x.stt_date, rml_parser.formatLang( x.price_subtotal, currency_obj=x.invoice_id.currency_id)) notes += note if len(note) >= maxlen: maxlen = len(note) n += 1 summary += x.price_subtotal print "----", maxlen notes += maxlen * "_" + "________\n" notes += "Total %s\n" % (rml_parser.formatLang( summary, currency_obj=x.invoice_id.currency_id)) notes += maxlen * "_" + "________\n" notes += "\nPembayaran COD dapat melalui :\n\ Bank BCA\n\ No Rek : 270 393 5656\n\ Atas Nama : SiCepat Ekspres Indonesia\n" res.update({ 'notes': notes, }) return res
def get_statement_line_for_reconciliation(self, cr, uid, st_line, context=None): """ Returns the data required by the bank statement reconciliation widget to display a statement line """ if context is None: context = {} statement_currency = st_line.journal_id.currency or st_line.journal_id.company_id.currency_id rml_parser = report_sxw.rml_parse(cr, uid, 'reconciliation_widget_asl', context=context) if st_line.amount_currency and st_line.currency_id: amount = st_line.amount_currency amount_currency = st_line.amount amount_currency_str = amount_currency > 0 and amount_currency or -amount_currency amount_currency_str = rml_parser.formatLang(amount_currency_str, currency_obj=statement_currency) else: amount = st_line.amount amount_currency_str = "" amount_str = amount > 0 and amount or -amount amount_str = rml_parser.formatLang(amount_str, currency_obj=st_line.currency_id or statement_currency) data = { 'id': st_line.id, 'ref': st_line.ref, 'note': st_line.note or "", 'name': st_line.name, 'date': st_line.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, 'statement_id': st_line.statement_id.id, '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 'has_no_partner': not st_line.partner_id.id, } if st_line.partner_id.id: if amount > 0: data['open_balance_account_id'] = st_line.partner_id.property_account_receivable.id else: data['open_balance_account_id'] = st_line.partner_id.property_account_payable.id return data
def get_statement_line_for_reconciliation(self, cr, uid, st_line, context=None): """ Returns the data required by the bank statement reconciliation widget to display a statement line """ if context is None: context = {} statement_currency = st_line.journal_id.currency or st_line.journal_id.company_id.currency_id rml_parser = report_sxw.rml_parse(cr, uid, "reconciliation_widget_asl", context=context) if st_line.amount_currency and st_line.currency_id: amount = st_line.amount_currency amount_currency = st_line.amount amount_currency_str = amount_currency > 0 and amount_currency or -amount_currency amount_currency_str = rml_parser.formatLang(amount_currency_str, currency_obj=statement_currency) else: amount = st_line.amount amount_currency_str = "" amount_str = amount > 0 and amount or -amount amount_str = rml_parser.formatLang(amount_str, currency_obj=st_line.currency_id or statement_currency) data = { "id": st_line.id, "ref": st_line.ref, "note": st_line.note or "", "name": st_line.name, "date": st_line.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, "statement_id": st_line.statement_id.id, "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, "amount_currency_str": amount_currency_str, # Amount in the statement currency "has_no_partner": not st_line.partner_id.id, } if st_line.partner_id.id: if amount > 0: data["open_balance_account_id"] = st_line.partner_id.property_account_receivable.id else: data["open_balance_account_id"] = st_line.partner_id.property_account_payable.id return data
def change_delivery_option(self, order, carrier_id): """Apply delivery amount to current sale order.""" if not order or not carrier_id: return {'success': False} # order_id is needed to get delivery carrier price if not request.context.get('order_id'): request.context['order_id'] = order.id # recompute delivery costs request.env['sale.order']._check_carrier_quotation( order, force_carrier_id=carrier_id) # generate updated total prices updated_order = request.website.sale_get_order() rml_obj = report_sxw.rml_parse(request.cr, SUPERUSER_ID, request.env['product.product']._name, context=request.context) price_digits = rml_obj.get_digits(dp='Product Price') # get additional tax information tax_overview = request.env['sale.order'].tax_overview(updated_order) return { 'success': True, 'order_total': rml_obj.formatLang(updated_order.amount_total, digits=price_digits), 'order_subtotal': rml_obj.formatLang(updated_order.amount_subtotal, digits=price_digits), 'order_total_taxes': rml_obj.formatLang(updated_order.amount_tax, digits=price_digits), 'order_total_tax_overview': tax_overview, 'order_total_delivery': rml_obj.formatLang(updated_order.amount_delivery, digits=price_digits) }
def create_xml(self, cr, uid, ids, data, context): registry = openerp.registry(cr.dbname) # Computing the dates (start of month: som, and end of month: eom) som = datetime.date(data['form']['year'], data['form']['month'], 1) eom = som + datetime.timedelta(lengthmonth(som.year, som.month)) date_xml = ['<date month="%s" year="%d" />' % (self.get_month_name(cr, uid, som.month, context=context), som.year), '<days>'] date_xml += ['<day number="%d" name="%s" weekday="%d" />' % (x, self.get_weekday_name(cr, uid, som.replace(day=x).weekday()+1, context=context), som.replace(day=x).weekday()+1) for x in range(1, lengthmonth(som.year, som.month)+1)] date_xml.append('</days>') date_xml.append('<cols>2.5cm%s,2cm</cols>\n' % (',0.7cm' * lengthmonth(som.year, som.month))) emp_xml='' emp_obj = registry['hr.employee'] for id in data['form']['employee_ids']: user = emp_obj.browse(cr, uid, id).user_id.id empl_name = emp_obj.browse(cr, uid, id).name if user: emp_xml += emp_create_xml(cr, user, som, eom, empl_name) # Computing the xml #Without this, report don't show non-ascii characters (TO CHECK) date_xml = '\n'.join(date_xml) rpt_obj = emp_obj rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context) header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),toxml(registry['res.users'].browse(cr,uid,uid).company_id.name)) xml='''<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s </report> ''' % (header_xml,date_xml, ustr(emp_xml)) return xml
def get_statement_line_for_reconciliation(self, cr, uid, id, context=None): """ Returns the data required by the bank statement reconciliation use case """ line = self.browse(cr, uid, id, context=context) statement_currency = line.journal_id.currency or line.journal_id.company_id.currency_id amount = line.amount rml_parser = report_sxw.rml_parse(cr, uid, "statement_line_widget", context=context) amount_str = line.amount > 0 and line.amount or -line.amount amount_str = rml_parser.formatLang(amount_str, currency_obj=statement_currency) amount_currency_str = "" if line.amount_currency and line.currency_id: amount_currency_str = amount_str amount_str = rml_parser.formatLang(line.amount_currency, currency_obj=line.currency_id) amount = line.amount_currency data = { "id": line.id, "ref": line.ref, "note": line.note or "", "name": line.name, "date": line.date, "amount": amount, "amount_str": amount_str, "currency_id": line.currency_id.id or statement_currency.id, "no_match": self.get_move_lines_counterparts(cr, uid, line, count=True, context=context) == 0, "partner_id": line.partner_id.id, "statement_id": line.statement_id.id, "account_code": line.journal_id.default_debit_account_id.code, "account_name": line.journal_id.default_debit_account_id.name, "partner_name": line.partner_id.name, "amount_currency_str": amount_currency_str, "has_no_partner": not line.partner_id.id, } if line.partner_id.id: data["open_balance_account_id"] = line.partner_id.property_account_payable.id if amount > 0: data["open_balance_account_id"] = line.partner_id.property_account_receivable.id return data
def do_change_delivery(self, order, carrier_id): """Apply delivery amount to current sale order.""" if not order or not carrier_id: return {'success': False} # order_id is needed to get delivery carrier price if not request.context.get('order_id'): request.context['order_id'] = order.id # recompute delivery costs request.env['sale.order']._check_carrier_quotation( order, force_carrier_id=carrier_id) # generate updated total prices updated_order = request.website.sale_get_order() rml_obj = report_sxw.rml_parse(request.cr, SUPERUSER_ID, request.env['product.product']._name, context=request.context) price_digits = rml_obj.get_digits(dp='Product Price') # get additional tax information tax_overview = request.env['sale.order'].tax_overview(updated_order) return { 'success': True, 'order_total': rml_obj.formatLang(updated_order.amount_total, digits=price_digits), 'order_subtotal': rml_obj.formatLang(updated_order.amount_subtotal, digits=price_digits), 'order_total_taxes': rml_obj.formatLang(updated_order.amount_tax, digits=price_digits), 'order_total_tax_overview': tax_overview, 'order_total_delivery': rml_obj.formatLang( updated_order.amount_delivery, digits=price_digits) }
def create(self, cr, uid, ids, datas, context): _divide_columns_for_matrix = 0.7 _display_ans_in_rows = 5 _pageSize = ('29.7cm','21.1cm') if datas.has_key('form') and datas['form'].get('orientation','') == 'vertical': if datas['form'].get('paper_size','') == 'letter': _pageSize = ('21.6cm','27.9cm') elif datas['form'].get('paper_size','') == 'legal': _pageSize = ('21.6cm','35.6cm') elif datas['form'].get('paper_size','') == 'a4': _pageSize = ('21.1cm','29.7cm') elif datas.has_key('form') and datas['form'].get('orientation',False) == 'horizontal': if datas['form'].get('paper_size','') == 'letter': _pageSize = ('27.9cm','21.6cm') elif datas['form'].get('paper_size','') == 'legal': _pageSize = ('35.6cm','21.6cm') elif datas['form'].get('paper_size') == 'a4': _pageSize = ('29.7cm','21.1cm') _frame_width = tools.ustr(_pageSize[0]) _frame_height = tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.90))+'cm' _tbl_widths = tools.ustr(float(_pageSize[0].replace('cm','')) - float(2.10))+'cm' rml ="""<document filename="Survey Answer Report.pdf"> <template pageSize="("""+_pageSize[0]+""","""+_pageSize[1]+""")" title='Survey Answer' author="LKP([email protected])" allowSplitting="20" > <pageTemplate id="first"> <frame id="first" x1="0.0cm" y1="1.0cm" width='"""+_frame_width+"""' height='"""+_frame_height+"""'/> <pageGraphics> <lineMode width="1.0"/> <lines>1.0cm """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+"""</lines> <lines>1.0cm """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+""" 1.0cm 1.00cm</lines> <lines>"""+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[1].replace('cm','')) - float(1.00))+'cm'+""" """+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" 1.00cm</lines> <lines>1.0cm 1.00cm """+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+""" 1.00cm</lines>""" if datas.has_key('form') and datas['form']['page_number']: rml +=""" <fill color="gray"/> <setFont name="Helvetica" size="10"/> <drawRightString x='"""+tools.ustr(float(_pageSize[0].replace('cm','')) - float(1.00))+'cm'+"""' y="0.6cm">Page : <pageNumber/> </drawRightString>""" rml +="""</pageGraphics> </pageTemplate> </template> <stylesheet> <blockTableStyle id="tbl_white"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="tbl_gainsboro"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/> <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="ans_tbl_white"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="ans_tbl_gainsboro"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="simple_table"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6"/> </blockTableStyle> <blockTableStyle id="note_table"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table2"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table3"> <blockAlignment value="LEFT"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="1,0" stop="2,-1"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table4"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/> </blockTableStyle> <blockTableStyle id="Table5"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/> </blockTableStyle> <blockTableStyle id="Table41"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="Table51"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="Table_heading"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="title_tbl"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/> <blockBackground colorName="black" start="0,0" stop="-1,-1"/> <blockTextColor colorName="white" start="0,0" stop="0,0"/> </blockTableStyle> <blockTableStyle id="page_tbl"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/> <blockBackground colorName="gray" start="0,0" stop="-1,-1"/> <blockTextColor colorName="white" start="0,0" stop="0,0"/> </blockTableStyle> <initialize> <paraStyle name="all" alignment="justify"/> </initialize> <paraStyle name="title" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/> <paraStyle name="answer_right" alignment="RIGHT" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="Standard1" fontName="helvetica-bold" alignment="RIGHT" fontSize="09.0"/> <paraStyle name="Standard" alignment="LEFT" fontName="Helvetica-Bold" fontSize="11.0"/> <paraStyle name="header1" fontName="Helvetica" fontSize="11.0"/> <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/> <paraStyle name="page" fontName="helvetica" fontSize="11.0" leftIndent="0.0"/> <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/> <paraStyle name="answer_bold" fontName="Helvetica-Bold" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="answer1" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="Title" fontName="helvetica" fontSize="20.0" leading="15" spaceBefore="6.0" spaceAfter="6.0" alignment="CENTER"/> <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="comment" fontName="Helvetica" fontSize="14.0" leading="50" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P1" fontName="Helvetica" fontSize="9.0" leading="12" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="terp_tblheader_Details" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_default_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_9_Bold" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_tblheader_General_Centre_simple" fontName="Helvetica" fontSize="10.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="10.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_General_right_simple" fontName="Helvetica" fontSize="10.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_General_right" fontName="Helvetica-Bold" fontSize="10.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="descriptive_text" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/> <paraStyle name="descriptive_text_heading" fontName="helvetica-bold" fontSize="18.0" alignment="RIGHT" leftIndent="0.0" textColor="white"/> </stylesheet> <images/> <story>""" surv_resp_obj = pooler.get_pool(cr.dbname).get('survey.response') rml_obj=report_sxw.rml_parse(cr, uid, surv_resp_obj._name,context) if datas.has_key('form') and datas['form'].has_key('response_ids'): response_id = datas['form']['response_ids'] elif context.has_key('response_id') and context['response_id']: response_id = [int(context['response_id'][0])] else: response_id = surv_resp_obj.search(cr, uid, [('survey_id', 'in', ids)]) surv_resp_line_obj = pooler.get_pool(cr.dbname).get('survey.response.line') surv_obj = pooler.get_pool(cr.dbname).get('survey') for response in surv_resp_obj.browse(cr, uid, response_id): for survey in surv_obj.browse(cr, uid, [response.survey_id.id]): tbl_width = float(_tbl_widths.replace('cm', '')) colwidth = "2.5cm,4.8cm," + str(tbl_width - 15.0) +"cm,3.2cm,4.5cm" resp_create = tools.ustr(time.strftime('%d-%m-%Y %I:%M:%S %p', time.strptime(response.date_create.split('.')[0], '%Y-%m-%d %H:%M:%S'))) rml += """<blockTable colWidths='""" + colwidth + """' style="Table_heading"> <tr> <td><para style="terp_default_9_Bold">Print Date : </para></td> <td><para style="terp_default_9">""" + to_xml(rml_obj.formatLang(time.strftime("%Y-%m-%d %H:%M:%S"),date_time=True)) + """</para></td> <td><para style="terp_default_9"></para></td> <td><para style="terp_default_9_Bold">Answered by : </para></td> <td><para style="terp_default_9">""" + to_xml(response.user_id.login or '') + """</para></td> </tr> <tr> <td><para style="terp_default_9"></para></td> <td><para style="terp_default_9"></para></td> <td><para style="terp_default_9"></para></td> <td><para style="terp_default_9_Bold">Answer Date : </para></td> <td><para style="terp_default_9">""" + to_xml(resp_create) + """</para></td> </tr> </blockTable><para style="P2"></para>""" status = "Not Finished" if response.state == "done": status = "Finished" colwidth = str(tbl_width - 7) + "cm," colwidth += "7cm" rml += """<blockTable colWidths='""" + str(colwidth) + """' style="title_tbl"> <tr> <td><para style="title">""" + to_xml(tools.ustr(survey.title)) + """</para><para style="P2"><font></font></para></td> <td><para style="descriptive_text_heading">Status :- """ + to_xml(tools.ustr(status)) + """</para><para style="P2"><font></font></para></td> </tr> </blockTable>""" if survey.note: rml += """<blockTable colWidths='""" + _tbl_widths + """' style="note_table"> <tr><td><para style="response">""" + to_xml(tools.ustr(survey.note or '')) + """</para><para style="P2"><font></font></para></td></tr> </blockTable>""" for page in survey.page_ids: rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="page_tbl"> <tr><td><para style="page">Page :- """ + to_xml(tools.ustr(page.title or '')) + """</para></td></tr> </blockTable>""" if page.note: rml += """<para style="P2"></para> <blockTable colWidths='""" + str(_tbl_widths) + """' style="note_table"> <tr><td><para style="response">""" + to_xml(tools.ustr(page.note or '')) + """</para></td></tr> </blockTable>""" for que in page.question_ids: rml += """<para style="P2"></para> <blockTable colWidths='""" + str(_tbl_widths) + """' style="Table5"> <tr><td><para style="question">""" + to_xml(to_xml(que.question)) + """</para></td></tr> </blockTable>""" answer = surv_resp_line_obj.browse(cr ,uid, surv_resp_line_obj.search(cr, uid, [('question_id', '=', que.id),('response_id', '=', response.id)])) if que.type in ['descriptive_text']: rml +="""<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr><td> <para style="response">""" + to_xml(tools.ustr(que.descriptive_text)) + """</para></td> </tr> </blockTable>""" elif que.type in ['table']: if len(answer) and answer[0].state == "done": col_heading = pooler.get_pool(cr.dbname).get('survey.tbl.column.heading') cols_widhts = [] tbl_width = float(_tbl_widths.replace('cm', '')) for i in range(0, len(que.column_heading_ids)): cols_widhts.append(tbl_width / float(len(que.column_heading_ids))) colWidths = "cm,".join(map(tools.ustr, cols_widhts)) colWidths = colWidths + 'cm' matrix_ans = [] rml +="""<para style="P2"></para><blockTable colWidths=" """ + str(colWidths) + """ " style="Table41"><tr>""" for col in que.column_heading_ids: if col.title not in matrix_ans: matrix_ans.append(col.title) rml += """<td> <para style="terp_tblheader_Details">""" + to_xml(tools.ustr(col.title)) +"""</para></td>""" rml += """</tr></blockTable>""" i = 0 for row in range(0, que.no_of_rows): if i%2 != 0: style = 'tbl_white' else: style = 'tbl_gainsboro' i +=1 rml += """<blockTable colWidths=" """ + str(colWidths) + """ " style='"""+style+"""'><tr>""" table_data = col_heading.browse(cr, uid, col_heading.search(cr, uid, [('response_table_id', '=', answer[0].id), ('name', '=', row)])) for column in matrix_ans: value = False for col in table_data: if column == col.column_id.title: value = col.value if value: rml += """<td> <para style="terp_default_9">""" + to_xml(tools.ustr(value)) +"""</para></td>""" else: rml += """<td><para style="terp_default_9"><font color ="white"> </font></para></td>""" rml += """</tr></blockTable>""" else: rml +="""<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr><td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in ['multiple_choice_only_one_ans','multiple_choice_multiple_ans']: if len(answer) and answer[0].state == "done": ans_list = [] for ans in answer[0].response_answer_ids: ans_list.append(to_xml(tools.ustr(ans.answer_id.answer))) answer_choice=[] for ans in que['answer_choice_ids']: answer_choice.append(to_xml(tools.ustr((ans.answer)))) def divide_list(lst, n): return [lst[i::n] for i in range(n)] divide_list = divide_list(answer_choice,_display_ans_in_rows) for lst in divide_list: if que.type == 'multiple_choice_multiple_ans': if len(lst) <> 0 and len(lst) <> int(round(float(len(answer_choice)) / _display_ans_in_rows, 0)): lst.append('') if not lst: del divide_list[divide_list.index(lst):] for divide in divide_list: a = _divide_columns_for_matrix * len(divide) b = float(_tbl_widths.replace('cm', '')) - float(a) cols_widhts = [] for div in range(0, len(divide)): cols_widhts.append(float(a / len(divide))) cols_widhts.append(float(b / len(divide))) colWidths = "cm,".join(map(tools.ustr, cols_widhts)) colWidths = colWidths +'cm' rml += """<blockTable colWidths=" """ + colWidths + """ " style="simple_table"><tr>""" for div in range(0, len(divide)): if divide[div] != '': if que.type == 'multiple_choice_multiple_ans': if divide[div] in ans_list: rml += """<td><illustration><fill color="white"/> <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/> <fill color="gray"/> <rect x="0.2cm" y="-0.35cm" width="0.3 cm" height="0.3cm" fill="yes" stroke="no" round="0.1cm"/> </illustration></td> <td><para style="answer">""" + divide[div] + """</para></td>""" else: rml+="""<td><illustration> <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="no" stroke="yes" round="0.1cm"/> </illustration></td> <td><para style="answer">""" + divide[div] + """</para></td>""" else: if divide[div] in ans_list: rml += """<td><illustration><fill color="white"/> <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes" round="0.1cm"/> <fill color="gray"/> <circle x="0.3cm" y="-0.18cm" radius="0.10 cm" fill="yes" stroke="no" round="0.1cm"/> </illustration></td> <td><para style="answer">""" + divide[div] + """</para></td>""" else: rml += """<td> <illustration> <circle x="0.3cm" y="-0.18cm" radius="0.23 cm" fill="no" stroke="yes" round="0.1cm"/> </illustration> </td> <td><para style="answer">""" + divide[div] + """</para></td>""" else: rml += """<td></td><td></td>""" rml += """</tr></blockTable>""" if que.is_comment_require and answer[0].comment: rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"><tr> <td><para style="answer">""" + to_xml(tools.ustr(answer[0].comment)) + """</para></td></tr></blockTable>""" else: rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr><td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in ['multiple_textboxes_diff_type','multiple_textboxes','date','date_and_time','numerical_textboxes','multiple_textboxes_diff_type']: if len(answer) and answer[0].state == "done": cols_widhts = [] cols_widhts.append(float(_tbl_widths.replace('cm',''))/2) cols_widhts.append(float(_tbl_widths.replace('cm',''))/2) colWidths = "cm,".join(map(tools.ustr, cols_widhts)) colWidths = tools.ustr(colWidths) + 'cm' answer_list = {} for ans in answer[0].response_answer_ids: answer_list[ans.answer_id.answer] = ans.answer for que_ans in que['answer_choice_ids']: if que_ans.answer in answer_list: rml += """<blockTable colWidths='""" + str(colWidths) + """' style="simple_table"> <tr> <td> <para style="response">""" + to_xml(tools.ustr(que_ans.answer)) + """</para></td> <td> <para style="response">""" + to_xml(tools.ustr(answer_list[que_ans.answer])) + """</para></td></tr> </blockTable>""" else: rml += """<blockTable colWidths='""" + str(colWidths) + """' style="simple_table"> <tr> <td> <para style="response">""" + to_xml(tools.ustr(que_ans.answer)) + """</para></td> <td> <para style="response"></para></td></tr> </blockTable>""" else: rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in ['single_textbox']: if len(answer) and answer[0].state == "done": rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">""" + to_xml(tools.ustr(answer[0].single_text)) + """</para></td></tr> </blockTable>""" else: rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in ['comment']: if len(answer) and answer[0].state == "done": rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">""" + to_xml(tools.ustr(answer[0].comment)) + """</para></td></tr> </blockTable>""" else: rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in ['matrix_of_choices_only_one_ans','matrix_of_choices_only_multi_ans', 'rating_scale', 'matrix_of_drop_down_menus']: if len(answer) and answer[0].state == "done": if que.type in ['matrix_of_choices_only_one_ans', 'rating_scale'] and que.comment_column: pass cols_widhts = [] if len(que.column_heading_ids): cols_widhts.append(float(_tbl_widths.replace('cm','')) / float(2.0)) for col in que.column_heading_ids: cols_widhts.append(float((float(_tbl_widths.replace('cm','')) / float(2.0)) / len(que.column_heading_ids))) else: cols_widhts.append(float(_tbl_widths.replace('cm',''))) tmp = 0.0 sum = 0.0 i = 0 if que.type in ['matrix_of_choices_only_one_ans','rating_scale'] and que.comment_column: for col in cols_widhts: if i == 0: cols_widhts[i] = cols_widhts[i] / 2.0 tmp = cols_widhts[i] sum += col i += 1 cols_widhts.append(round(tmp, 2)) colWidths = "cm,".join(map(tools.ustr, cols_widhts)) colWidths = colWidths + 'cm' matrix_ans = [(0, ''),] for col in que.column_heading_ids: if col.title not in matrix_ans: matrix_ans.append((col.id, col.title)) len_matrix = len(matrix_ans) if que.type in ['matrix_of_choices_only_one_ans', 'rating_scale'] and que.comment_column: matrix_ans.append((0,que.column_name)) rml += """<blockTable colWidths=" """ + colWidths + """ " style="simple_table"><tr>""" for mat_col in range(0, len(matrix_ans)): rml += """<td><para style="response">""" + to_xml(tools.ustr(matrix_ans[mat_col][1])) + """</para></td>""" rml += """</tr>""" rml += """</blockTable>""" i = 0 for ans in que.answer_choice_ids: if i%2 != 0: style = 'ans_tbl_white' else: style = 'ans_tbl_gainsboro' i += 1 rml += """<blockTable colWidths=" """ + colWidths + """ " style='"""+style+"""'> <tr><td><para style="response">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>""" comment_value = "" for mat_col in range(1, len_matrix): value = """""" for res_ans in answer[0].response_answer_ids: if res_ans.answer_id.id == ans.id and res_ans.column_id.id == matrix_ans[mat_col][0]: comment_value = to_xml(tools.ustr(res_ans.comment_field)) if que.type in ['matrix_of_drop_down_menus']: value = """<para style="response">""" + to_xml(tools.ustr(res_ans.value_choice)) + """</para>""" elif que.type in ['matrix_of_choices_only_one_ans', 'rating_scale']: value = """<illustration><fill color="white"/> <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes"/> <fill color="gray"/> <circle x="0.3cm" y="-0.18cm" radius="0.10 cm" fill="yes" stroke="no"/> </illustration>""" elif que.type in ['matrix_of_choices_only_multi_ans']: value = """<illustration> <fill color="white"/> <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/> <fill color="gray"/> <rect x="0.2cm" y="-0.35cm" width="0.3 cm" height="0.3cm" fill="yes" stroke="no" round="0.1cm"/> </illustration>""" break else: if que.type in ['matrix_of_drop_down_menus']: value = """""" elif que.type in ['matrix_of_choices_only_one_ans','rating_scale']: value = """<illustration><fill color="white"/> <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes" round="0.1cm"/> </illustration>""" elif que.type in ['matrix_of_choices_only_multi_ans']: value = """<illustration><fill color="white"/> <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/> </illustration>""" rml+= """<td>""" + value + """</td>""" if que.type in ['matrix_of_choices_only_one_ans','rating_scale'] and que.comment_column: if comment_value == 'False': comment_value = '' rml += """<td><para style="response">""" + to_xml(tools.ustr(comment_value)) + """</para></td>""" rml += """</tr></blockTable>""" if que.is_comment_require: rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"><tr> <td><para style="answer">""" + to_xml(tools.ustr(answer[0].comment or '')) + """</para></td></tr></blockTable>""" else: rml += """<blockTable colWidths='""" + str(_tbl_widths) + """' style="simple_table"> <tr><td> <para style="response">No Answer</para></td> </tr> </blockTable>""" if datas.has_key('form') and not datas['form']['without_pagebreak']: rml += """<pageBreak/>""" elif not datas.has_key('form'): rml += """<pageBreak/>""" else: rml += """<para style="P2"><font></font></para>""" rml += """</story></document>""" report_type = datas.get('report_type', 'pdf') create_doc = self.generators[report_type] pdf = create_doc(rml, title=self.title) return (pdf, report_type)
def create_xml(self, cr, uid, ids, data, context): registry = openerp.registry(cr.dbname) obj_dept = registry['hr.department'] obj_emp = registry['hr.employee'] depts=[] emp_id={} rpt_obj = registry['hr.holidays'] rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context) cr.execute("SELECT name FROM res_company") res=cr.fetchone()[0] date_xml=[] date_today=time.strftime('%Y-%m-%d %H:%M:%S') date_xml +=['<res name="%s" today="%s" />' % (to_xml(res),date_today)] cr.execute("SELECT id, name, color_name FROM hr_holidays_status ORDER BY id") legend=cr.fetchall() today=datetime.datetime.today() first_date=data['form']['date_from'] som = strToDate(first_date) eom = som+datetime.timedelta(59) day_diff=eom-som name = '' if len(data['form'].get('emp', ())) == 1: name = obj_emp.read(cr, uid, data['form']['emp'][0], ['name'])['name'] if data['form']['holiday_type']!='both': type=data['form']['holiday_type'] if data['form']['holiday_type']=='Confirmed': holiday_type=('confirm') else: holiday_type=('validate') else: type="Confirmed and Approved" holiday_type=('confirm','validate') date_xml.append('<from>%s</from>\n'% (str(rml_obj.formatLang(som.strftime("%Y-%m-%d"),date=True)))) date_xml.append('<to>%s</to>\n' %(str(rml_obj.formatLang(eom.strftime("%Y-%m-%d"),date=True)))) date_xml.append('<type>%s</type>'%(type)) date_xml.append('<name>%s</name>'%(name)) # date_xml=[] for l in range(0,len(legend)): date_xml += ['<legend row="%d" id="%d" name="%s" color="%s" />' % (l+1,legend[l][0],_(legend[l][1]),legend[l][2])] date_xml += ['<date month="%s" year="%d" />' % (ustr(som.strftime('%B')), som.year),'<days>'] cell=1 if day_diff.days>=30: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)] else: if day_diff.days>=(lengthmonth(som.year, som.month)-som.day): date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)] else: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, eom.day+1)] cell=x-som.day+1 day_diff1=day_diff.days-cell+1 width_dict={} month_dict={} i=1 j=1 year=som.year month=som.month month_dict[j]=som.strftime('%B') width_dict[j]=cell while day_diff1>0: if month+i<=12: if day_diff1 > lengthmonth(year,i+month): # Not on 30 else you have problems when entering 01-01-2009 for example som1=datetime.date(year,month+i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(year,i+month)+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x else: som1=datetime.date(year,month+i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x day_diff1=day_diff1-x else: years=year+1 year=years month=0 i=1 if day_diff1>=30: som1=datetime.date(years,i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(years,i)+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x else: som1=datetime.date(years,i,1) i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)] cell=cell+x width_dict[j]=x day_diff1=day_diff1-x date_xml.append('</days>') date_xml.append('<cols>3.5cm%s,0.4cm</cols>\n' % (',0.4cm' * (60))) date_xml = ''.join(date_xml) st='<cols_months>3.5cm' for m in range(1,len(width_dict)+1): st+=',' + str(0.4 *width_dict[m])+'cm' st+=',0.4cm</cols_months>\n' months_xml =['<months number="%d" name="%s"/>' % (x, _(month_dict[x])) for x in range(1,len(month_dict)+1) ] months_xml.append(st) emp_xml='' row_id=1 if data['model'] == 'hr.employee': for items in obj_emp.read(cr, uid, data['form']['emp'], ['id', 'name']): emp_xml += emp_create_xml(self, cr, uid, 0, holiday_type, row_id, items['id'], items['name'], som, eom) row_id = row_id +1 elif data['model']=='ir.ui.menu': for dept in obj_dept.browse(cr, uid, data['form']['depts'], context=context): emp_ids = obj_emp.search(cr, uid, [('department_id', '=', dept.id)], context=context) if emp_ids==[]: continue dept_done=0 for item in obj_emp.read(cr, uid, emp_ids, ['id', 'name']): if dept_done==0: emp_xml += emp_create_xml(self, cr, uid, 1, holiday_type, row_id, dept.id, dept.name, som, eom) row_id = row_id +1 dept_done=1 emp_xml += emp_create_xml(self, cr, uid, 0, holiday_type, row_id, item['id'], item['name'], som, eom) row_id = row_id +1 header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),to_xml(registry['res.users'].browse(cr,uid,uid).company_id.name)) # Computing the xml xml='''<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s %s </report> ''' % (header_xml,months_xml,date_xml, ustr(emp_xml)) return xml
def create(self, cr, uid, ids, datas, context): del_obj = pooler.get_pool(cr.dbname).get('stock.picking.out') user_obj = pooler.get_pool(cr.dbname).get('res.users') rml_obj=report_sxw.rml_parse(cr, uid, del_obj._name,context) company=user_obj.browse(cr,uid,[uid],context)[0].company_id rml ="""<document filename="QC Documents.pdf"> <template pageSize="(595.0,842.0)" title="QC Documents" author="OpenERP S.A.([email protected])" allowSplitting="20"> <pageTemplate> <frame id="first" x1="1.3cm" y1="1.5cm" width="18.4cm" height="26.5cm"/> <stylesheet> <blockTableStyle id="Table4"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="0,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="0,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="0,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="1,0" stop="1,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="1,0" stop="1,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="1,-1" stop="1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="2,0" stop="2,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="2,0" stop="2,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="2,-1" stop="2,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="3,0" stop="3,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="3,0" stop="3,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="3,0" stop="3,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="4,0" stop="4,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="4,0" stop="4,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="4,0" stop="4,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="5,0" stop="5,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="5,0" stop="5,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="5,0" stop="5,-1"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="5,-1" stop="5,-1"/> </blockTableStyle> <blockTableStyle id="Table_Title_String"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <initialize> <paraStyle name="all" alignment="justify"/> </initialize> <paraStyle name="Standard" fontName="Helvetica"/> <paraStyle name="main_footer" fontSize="8.0" alignment="CENTER"/> <paraStyle name="main_header" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_header" fontName="Helvetica-Bold" fontSize="12.0" leading="15" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="Heading" fontName="Helvetica" fontSize="14.0" leading="17" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_Details" fontName="Helvetica" fontSize="14.0" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="content_Details" fontName="Helvetica" fontSize="12.0" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <images/> </stylesheet> <pageGraphics> <!-- Set here the default font to use for all <drawString> tags --> <setFont name="DejaVu Sans" size="8"/> <!-- You Logo - Change X,Y,Width and Height --> <image x="1.3cm" y="27.7cm" height="40.0" >"""+ to_xml(company.logo) +"""</image> <fill color="black"/> <stroke color="black"/> <!-- page header --> <lines>1.3cm 27.7cm 20cm 27.7cm</lines> <drawRightString x="20cm" y="27.8cm">"""+ to_xml(company.rml_header1) +"""</drawRightString> <drawString x="1.3cm" y="27.3cm">"""+ to_xml(company.partner_id.name) +"""</drawString> <place x="1.3cm" y="25.3cm" height="1.8cm" width="15.0cm"> <para style="main_header">"""+ to_xml(company.partner_id.street or '') +"""</para> <para style="main_header">"""+ to_xml(company.partner_id.street2 or '') +"""</para> <para style="main_header">"""+ to_xml(company.partner_id.city or '') +""",""" + to_xml(company.partner_id.state_id.name or '') +"""</para> <para style="main_header">"""+ to_xml(company.partner_id.country_id.name or '') +""" - """+ to_xml(company.partner_id.zip or '') +"""</para> </place> <drawString x="1.3cm" y="25.0cm">Phone:</drawString> <drawRightString x="7cm" y="25.0cm">"""+ to_xml(company.partner_id.phone or '') +"""</drawRightString> <drawString x="1.3cm" y="24.6cm">Mail:</drawString> <drawRightString x="7cm" y="24.6cm">"""+ to_xml(company.partner_id.email or '') +"""</drawRightString> <lines>1.3cm 24.5cm 7cm 24.5cm</lines> <!-- left margin --> <rotate degrees="90"/> <fill color="grey"/> <drawString x="2.65cm" y="-0.4cm">generated by OpenERP.com</drawString> <fill color="black"/> <rotate degrees="-90"/> <!-- page footer --> <lines>1.2cm 2.65cm 19.9cm 2.65cm</lines> <place x="1.3cm" y="0cm" height="2.55cm" width="19.0cm"> <para style="main_footer">"""+ to_xml(company.rml_footer or '') +"""</para> <para style="main_footer">Contact : """+ to_xml(company.name) +"""- Page: <pageNumber/></para> </place> </pageGraphics> </pageTemplate> </template> """ lst = [] for line in del_obj.browse(cr, uid, ids): main_list = self.get_analysis_data(cr, uid, line.move_lines) for sub in main_list: rml += """ <story> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <blockTable colWidths="538.0" style="Table_Title_String"> <tr> <td> <para style="terp_header">Delivery Order : """+ to_xml(line.name or '') +"""</para> <para style="terp_header">Sale Order : """+ to_xml(line.origin or '') +"""</para> <para style="terp_header">QC Number : </para> </td> </tr> </blockTable> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <blockTable colWidths="210.0,90.0,90.0,90.0,55.0" rowHeights="40" style="Table4"> <tr> <td> <para style="terp_tblheader_Details"><b>CHARACTERISTIC</b></para> </td> <td> <para style="terp_tblheader_Details"><b>Actual Value</b></para> </td> <td> <para style="terp_tblheader_Details"><b>Upper Limit</b></para> </td> <td> <para style="terp_tblheader_Details"><b>Lower Limit</b></para> </td> <td> <para style="terp_tblheader_Details"><b>ok?</b></para> </td> </tr> </blockTable> """ for sub_list in sub: rml += """ <blockTable colWidths="210.0,90.0,90.0,90.0,55.0" style="Table4"> <tr> <td> <para style="content_Details">""" + str(sub_list['name']) + """</para> </td> <td> <para style="content_Details">""" + sub_list['actual'] + """</para> </td> <td> <para style="content_Details">""" + str(sub_list['upper']) + """</para> </td> <td> <para style="content_Details">""" +str(sub_list['lower']) + """</para> </td> <td> <para style="content_Details">""" + str(sub_list['ok']) + """</para> </td> </tr> </blockTable> """ rml += """</story> """ rml += """</document> """ report_type = datas.get('report_type', 'pdf') create_doc = self.generators[report_type] self.internal_header=False pdf = create_doc(rml, title=self.title) return (pdf, report_type)
def create(self, cr, uid, ids, datas, context): surv_obj = pooler.get_pool(cr.dbname).get('survey') user_obj = pooler.get_pool(cr.dbname).get('res.users') rml_obj=report_sxw.rml_parse(cr, uid, surv_obj._name,context) company=user_obj.browse(cr,uid,[uid],context)[0].company_id rml ="""<document filename="Survey Analysis Report.pdf"> <template pageSize="(595.0,842.0)" title="Survey Analysis" author="OpenERP S.A.([email protected])" allowSplitting="20"> <pageTemplate> <frame id="first" x1="1.3cm" y1="1.5cm" width="18.4cm" height="26.5cm"/> <pageGraphics> <fill color="black"/> <stroke color="black"/> <setFont name="DejaVu Sans" size="8"/> <drawString x="1.3cm" y="28.3cm"> """+to_xml(rml_obj.formatLang(time.strftime("%Y-%m-%d %H:%M:%S"),date_time=True))+"""</drawString> <setFont name="DejaVu Sans Bold" size="10"/> <drawString x="9.8cm" y="28.3cm">"""+ to_xml(company.name) +"""</drawString> <stroke color="#000000"/> <lines>1.3cm 28.1cm 20cm 28.1cm</lines> </pageGraphics> </pageTemplate> </template> <stylesheet> <blockTableStyle id="Table1"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6"/> </blockTableStyle> <blockTableStyle id="Table2"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table3"> <blockAlignment value="LEFT"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="1,0" stop="2,-1"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table4"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/> </blockTableStyle> <blockTableStyle id="Table5"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/> </blockTableStyle> <blockTableStyle id="Table_heading"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBEFORE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEABOVE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="Table_head_2"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBEFORE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEABOVE" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> </blockTableStyle> <initialize> <paraStyle name="all" alignment="justify"/> </initialize> <paraStyle name="answer_right" alignment="RIGHT" fontName="Helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="Standard1" fontName="Helvetica-Bold" alignment="RIGHT" fontSize="09.0"/> <paraStyle name="Standard" alignment="LEFT" fontName="Helvetica-Bold" fontSize="11.0"/> <paraStyle name="header1" fontName="Helvetica" fontSize="11.0"/> <paraStyle name="response" fontName="Helvetica-Oblique" fontSize="9.5"/> <paraStyle name="response-bold" fontName="Helvetica-Bold" fontSize="9" alignment="RIGHT" /> <paraStyle name="page" fontName="Helvetica" fontSize="11.0" leftIndent="0.0"/> <paraStyle name="question" fontName="Helvetica-BoldOblique" fontSize="10.0" leftIndent="3.0"/> <paraStyle name="answer_bold" fontName="Helvetica-Bold" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="answer" fontName="Helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="title" fontName="Helvetica" fontSize="20.0" leading="15" spaceBefore="6.0" spaceAfter="6.0" alignment="CENTER"/> <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_default_Centre_8" fontName="Helvetica" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_Center_heading" fontName="Helvetica-Bold" fontSize="9.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/> </stylesheet> <images/> """ if datas.has_key('form') and datas['form']['survey_ids']: ids = datas['form']['survey_ids'] for survey in surv_obj.browse(cr, uid, ids): rml += """<story> <para style="title">Answers Summary</para> <para style="Standard"><font></font></para> <para style="P2"> <font color="white"> </font> </para> <blockTable colWidths="280.0,100.0,120.0" style="Table_heading"> <tr> <td> <para style="terp_tblheader_General_Centre">Survey Title </para> </td> <td> <para style="terp_tblheader_General_Centre">Total Started Survey </para> </td> <td> <para style="terp_tblheader_General_Centre">Total Completed Survey </para> </td> </tr> </blockTable> <blockTable colWidths="280.0,100.0,120.0" style="Table_head_2"> <tr> <td> <para style="terp_default_Centre_8">""" + to_xml(tools.ustr(survey.title)) + """</para> </td> <td> <para style="terp_default_Centre_8">""" + str(survey.tot_start_survey) + """</para> </td> <td> <para style="terp_default_Centre_8">""" + str(survey.tot_comp_survey) + """</para> </td> </tr> </blockTable> <para style="P2"> <font color="white"> </font> </para>""" for page in survey.page_ids: rml += """ <blockTable colWidths="500" style="Table4"> <tr> <td><para style="page">Page :- """ + to_xml(tools.ustr(page.title)) + """</para></td> </tr> </blockTable>""" for que in page.question_ids: rml +="""<blockTable colWidths="500" style="Table5"> <tr> <td><para style="question">""" + to_xml(tools.ustr(que.question)) + """</para></td> </tr> </blockTable>""" cols_widhts = [] if que.type in ['matrix_of_choices_only_one_ans','matrix_of_choices_only_multi_ans']: cols_widhts.append(200) for col in range(0, len(que.column_heading_ids) + 1): cols_widhts.append(float(300 / (len(que.column_heading_ids) + 1))) colWidths = ",".join(map(tools.ustr, cols_widhts)) matrix_ans = [(0,'')] for col in que.column_heading_ids: if col.title not in matrix_ans: matrix_ans.append((col.id,col.title)) rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>""" for mat_col in range(0, len(matrix_ans)): rml+="""<td><para style="response">""" + to_xml(tools.ustr(matrix_ans[mat_col][1])) + """</para></td>""" rml += """<td><para style="response-bold">Answer Count</para></td> </tr>""" last_col = cols_widhts[-1] for ans in que.answer_choice_ids: rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>""" cr.execute("select count(id) from survey_response_answer sra where sra.answer_id = %s", (ans.id,)) tot_res = cr.fetchone()[0] cr.execute("select count(id) ,sra.column_id from survey_response_answer sra where sra.answer_id=%s group by sra.column_id", (ans.id,)) calc_res = cr.dictfetchall() for mat_col in range(1, len(matrix_ans)): percantage = 0.0 cal_count = 0 for cal in calc_res: if cal['column_id'] == matrix_ans[mat_col][0]: cal_count = cal['count'] if tot_res: percantage = round(float(cal_count)*100 / tot_res,2) if percantage: rml += """<td color="#FFF435"><para style="answer_bold">""" + tools.ustr(percantage) +"% (" + tools.ustr(cal_count) + """)</para></td>""" else: rml += """<td color="#FFF435"><para style="answer">""" + tools.ustr(percantage) +"% (" + tools.ustr(cal_count) + """)</para></td>""" rml += """<td><para style="answer_right">""" + tools.ustr(tot_res) + """</para></td> </tr>""" rml += """</blockTable>""" if que.is_comment_require: cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''",(que.id,)) tot_res = cr.fetchone()[0] rml += """<blockTable colWidths=" """+ str(500 - last_col) +"," + str(last_col) + """ " style="Table1"><tr><td><para style="answer_right">""" + to_xml(tools.ustr(que.comment_label)) + """</para></td> <td><para style="answer">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>""" elif que.type in['multiple_choice_only_one_ans', 'multiple_choice_multiple_ans', 'multiple_textboxes','date_and_time','date','multiple_textboxes_diff_type']: rml += """<blockTable colWidths="240.0,210,50.0" style="Table1">""" rml += """ <tr> <td> <para style="Standard"> </para></td> <td> <para style="terp_default_Center_heading">Answer Percentage</para></td> <td> <para style="response-bold">Answer Count</para></td> </tr>""" for ans in que.answer_choice_ids: progress = ans.average * 7 / 100 rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td> <td> <illustration> <stroke color="lightslategray"/> <rect x="0.1cm" y="-0.45cm" width="7.2 cm" height="0.5cm" fill="no" stroke="yes" round="0.1cm"/> """ if progress: rml += """<fill color="lightsteelblue"/> <rect x="0.2cm" y="-0.35cm" width='""" + tools.ustr(str(float(progress)) +'cm') + """' height="0.3cm" fill="yes" stroke="no" round="0.1cm"/>""" rml += """ <fill color="black"/> <setFont name="Helvetica" size="9"/> <drawString x="3.2cm" y="-0.30cm">""" + tools.ustr(ans.average) + """%</drawString></illustration> </td> <td><para style="answer_right">""" + tools.ustr(ans.response) + """</para></td></tr>""" rml += """</blockTable>""" if que.is_comment_require: # if que.make_comment_field: # cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''", (que.id,)) # tot_res = cr.fetchone()[0] # tot_avg = 0.00 # if que.tot_resp: # tot_avg = round(float(tot_res * 100)/ que.tot_resp,2) # rml+="""<blockTable colWidths="280.0,120,100.0" style="Table1"><tr><td><para style="answer">""" +to_xml(tools.ustr(que.comment_label)) + """</para></td> # <td><para style="answer">""" + str(tot_avg) + """%</para></td> # <td><para style="answer">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>""" # else: cr.execute("select count(id) from survey_response_line where question_id = %s and comment != ''", (que.id,)) tot_res = cr.fetchone()[0] rml += """<blockTable colWidths="450.0,50.0" style="Table1"><tr><td><para style="answer_right">""" + to_xml(tools.ustr(que.comment_label)) + """</para></td> <td><para style="answer_right">""" + tools.ustr(tot_res) + """</para></td></tr></blockTable>""" elif que.type in['single_textbox']: cr.execute("select count(id) from survey_response_line where question_id = %s and single_text!=''",(que.id,)) rml += """<blockTable colWidths="400.0,100.0" style="Table1"> <tr> <td> <para style="Standard"> </para></td> <td> <para style="response-bold">Answer Count</para></td> </tr> <tr><td><para style="answer"></para></td> <td><para style="answer_right">""" + tools.ustr(cr.fetchone()[0]) + """ </para></td></tr> </blockTable>""" elif que.type in['comment']: cr.execute("select count(id) from survey_response_line where question_id = %s and comment !=''", (que.id,)) rml += """<blockTable colWidths="400.0,100.0" style="Table1"> <tr> <td> <para style="Standard"> </para></td> <td> <para style="response-bold">Answer Count</para></td> </tr> <tr><td><para style="answer"></para></td> <td><para style="answer_right">""" + tools.ustr(cr.fetchone()[0]) + """ </para></td></tr> </blockTable>""" elif que.type in['rating_scale']: cols_widhts.append(200) for col in range(0,len(que.column_heading_ids) + 2): cols_widhts.append(float(300 / (len(que.column_heading_ids) + 2))) colWidths = ",".join(map(tools.ustr, cols_widhts)) matrix_ans = [(0,'')] for col in que.column_heading_ids: if col.title not in matrix_ans: matrix_ans.append((col.id,col.title)) rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr>""" for mat_col in range(0,len(matrix_ans)): rml += """<td><para style="response">""" + to_xml(tools.ustr(matrix_ans[mat_col][1])) + """</para></td>""" rml += """<td><para style="response-bold">Rating Average</para></td> <td><para style="response-bold">Answer Count</para></td> </tr>""" for ans in que.answer_choice_ids: rml += """<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>""" res_count = 0 rating_weight_sum = 0 for mat_col in range(1, len(matrix_ans)): cr.execute("select count(sra.answer_id) from survey_response_line sr, survey_response_answer sra\ where sr.id = sra.response_id and sra.answer_id = %s and sra.column_id ='%s'", (ans.id,matrix_ans[mat_col][0])) tot_res = cr.fetchone()[0] cr.execute("select count(sra.answer_id),sqc.rating_weight from survey_response_line sr, survey_response_answer sra ,\ survey_question_column_heading sqc where sr.id = sra.response_id and \ sqc.question_id = sr.question_id and sra.answer_id = %s and sqc.title ='%s'\ + group by sra.answer_id,sqc.rating_weight", (ans.id,matrix_ans[mat_col][1])) col_weight = cr.fetchone() if not col_weight: col_weight= (0,0) elif not col_weight[1]: col_weight = (col_weight[0],0) res_count = col_weight[0] if tot_res and res_count: rating_weight_sum += int(col_weight[1]) * tot_res tot_per = round((float(tot_res) * 100) / int(res_count), 2) else: tot_per = 0.0 if tot_res: rml += """<td><para style="answer_bold">""" + tools.ustr(tot_per) + "%(" + tools.ustr(tot_res) + """)</para></td>""" else: rml += """<td><para style="answer">""" + tools.ustr(tot_per)+"%(" + tools.ustr(tot_res) + """)</para></td>""" percantage = 0.00 if res_count: percantage = round((float(rating_weight_sum)/res_count), 2) rml += """<td><para style="answer_right">""" + tools.ustr(percantage) + """</para></td> <td><para style="answer_right">""" + tools.ustr(res_count) + """</para></td></tr>""" rml += """</blockTable>""" elif que.type in['matrix_of_drop_down_menus']: for column in que.column_heading_ids: rml += """<blockTable colWidths="500" style="Table1"><tr> <td><para style="answer">""" + to_xml(tools.ustr(column.title)) + """</para></td></tr></blockTable>""" menu_choices = column.menu_choice.split('\n') cols_widhts = [] cols_widhts.append(200) for col in range(0, len(menu_choices) + 1): cols_widhts.append(float(300 / (len(menu_choices) + 1))) colWidths = ",".join(map(tools.ustr, cols_widhts)) rml += """<blockTable colWidths=" """ + colWidths + """ " style="Table1"><tr> <td><para style="response"></para></td>""" for menu in menu_choices: rml += """<td><para style="response">""" + to_xml(tools.ustr(menu)) + """</para></td>""" rml += """<td><para style="response-bold">Answer Count</para></td></tr>""" cr.execute("select count(id), sra.answer_id from survey_response_answer sra \ where sra.column_id='%s' group by sra.answer_id ", (column.id,)) res_count = cr.dictfetchall() cr.execute("select count(sra.id),sra.value_choice, sra.answer_id, sra.column_id from survey_response_answer sra \ where sra.column_id='%s' group by sra.value_choice ,sra.answer_id, sra.column_id", (column.id,)) calc_percantage = cr.dictfetchall() for ans in que.answer_choice_ids: rml += """<tr><td><para style="answer_right">""" + to_xml(tools.ustr(ans.answer)) + """</para></td>""" for mat_col in range(0, len(menu_choices)): calc = 0 response = 0 for res in res_count: if res['answer_id'] == ans.id: response = res['count'] for per in calc_percantage: if ans.id == per['answer_id'] and menu_choices[mat_col] == per['value_choice']: calc = per['count'] percantage = 0.00 if calc and response: percantage = round((float(calc)* 100) / response,2) if calc: rml += """<td><para style="answer_bold">""" +tools.ustr(percantage)+"% (" + tools.ustr(calc) + """)</para></td>""" else: rml += """<td><para style="answer">""" +tools.ustr(percantage)+"% (" + tools.ustr(calc) + """)</para></td>""" response = 0 for res in res_count: if res['answer_id'] == ans.id: response = res['count'] rml += """<td><para style="answer_right">""" + tools.ustr(response) + """</para></td></tr>""" rml += """</blockTable>""" elif que.type in['numerical_textboxes']: rml += """<blockTable colWidths="240.0,20,100.0,70,70.0" style="Table1"> <tr> <td> <para style="Standard"> </para></td> <td> <para style="Standard"> </para></td> <td> <para style="response">Answer Average</para></td> <td> <para style="response">Answer Total</para></td> <td> <para style="response-bold">Answer Count</para></td> </tr>""" for ans in que.answer_choice_ids: cr.execute("select answer from survey_response_answer where answer_id=%s group by answer", (ans.id,)) tot_res = cr.dictfetchall() total = 0 for tot in tot_res: total += int(tot['answer']) per = 0.00 if len(tot_res): per = round((float(total) / len(tot_res)),2) rml+="""<tr><td><para style="answer">""" + to_xml(tools.ustr(ans.answer)) + """</para></td> <td> <para style="Standard"> </para></td> <td> <para style="answer">""" + tools.ustr(per) +"""</para></td> <td><para style="answer">""" + tools.ustr(total) + """</para></td> <td><para style="answer_right">""" + tools.ustr(len(tot_res)) + """</para></td></tr>""" rml+="""</blockTable>""" rml +="""<blockTable colWidths="300,100,100.0" style="Table3"> <tr> <td><para style="Standard1"></para></td> <td><para style="Standard1">Answered Question</para></td> <td><para style="Standard1">""" + tools.ustr(que.tot_resp) + """</para></td> </tr> <tr> <td><para style="Standard1"></para></td> <td><para style="Standard1">Skipped Question</para></td> <td><para style="Standard1">""" + tools.ustr(survey.tot_start_survey - que.tot_resp) + """</para></td> </tr> </blockTable>""" rml += """</story>""" rml += """</document>""" report_type = datas.get('report_type', 'pdf') create_doc = self.generators[report_type] self.internal_header=True pdf = create_doc(rml, title=self.title) return (pdf, report_type)
def create_xml(self, cr, uid, ids, datas, context=None): number = (datas.get("form", False) and datas["form"]["number"]) or 1 registry = openerp.registry(cr.dbname) product_pool = registry.get("product.product") product_uom_pool = registry.get("product.uom") workcenter_pool = registry.get("mrp.workcenter") user_pool = registry.get("res.users") bom_pool = registry.get("mrp.bom") pricelist_pool = registry.get("product.pricelist") rml_obj = report_sxw.rml_parse(cr, uid, product_pool._name, context) rml_obj.localcontext.update({"lang": context.get("lang", False)}) company_currency = user_pool.browse(cr, uid, uid).company_id.currency_id company_currency_symbol = company_currency.symbol or company_currency.name def process_bom(bom, currency_id, factor=1): xml = "<row>" sum = 0 sum_strd = 0 prod = product_pool.browse(cr, uid, bom["product_id"]) prod_name = to_xml(bom["name"]) prod_qtty = factor * bom["product_qty"] product_uom = product_uom_pool.browse(cr, uid, bom["product_uom"], context=context) product_uom_name = to_xml(product_uom.name) main_sp_price, main_sp_name, main_strd_price = "", "", "" sellers, sellers_price = "", "" if prod.seller_id: main_sp_name = "- <b>" + to_xml(prod.seller_id.name) + "</b>\r\n" pricelist = prod.seller_id.property_product_pricelist_purchase price = pricelist_pool.price_get( cr, uid, [pricelist.id], prod.id, number * prod_qtty or 1.0, prod.seller_id.id, {"uom": prod.uom_po_id.id, "date": time.strftime("%Y-%m-%d")}, )[pricelist.id] main_sp_price = """<b>""" + rml_obj.formatLang(price) + " " + (company_currency_symbol) + """</b>\r\n""" sum += prod_qtty * price std_price = product_uom_pool._compute_price( cr, uid, prod.uom_id.id, prod.standard_price, to_uom_id=product_uom.id ) main_strd_price = str(std_price) + "\r\n" sum_strd = prod_qtty * std_price for seller_id in prod.seller_ids: if seller_id.name.id == prod.seller_id.id: continue sellers += "- <i>" + to_xml(seller_id.name.name) + "</i>\r\n" pricelist = seller_id.name.property_product_pricelist_purchase price = pricelist_pool.price_get( cr, uid, [pricelist.id], prod.id, number * prod_qtty or 1.0, seller_id.name.id, {"uom": prod.uom_po_id.id, "date": time.strftime("%Y-%m-%d")}, )[pricelist.id] sellers_price += ( """<i>""" + rml_obj.formatLang(price) + " " + (company_currency_symbol) + """</i>\r\n""" ) xml += ( """<col para='yes'> """ + prod_name + """ </col> <col para='yes'> """ + main_sp_name + sellers + """ </col> <col f='yes'>""" + rml_obj.formatLang(prod_qtty) + " " + product_uom_name + """</col> <col f='yes'>""" + rml_obj.formatLang(float(main_strd_price)) + " " + (company_currency_symbol) + """</col> <col f='yes'>""" + main_sp_price + sellers_price + """</col>'""" ) xml += "</row>" return xml, sum, sum_strd def process_workcenter(wrk): workcenter = workcenter_pool.browse(cr, uid, wrk["workcenter_id"]) cost_cycle = wrk["cycle"] * workcenter.costs_cycle cost_hour = wrk["hour"] * workcenter.costs_hour total = cost_cycle + cost_hour xml = "<row>" xml += "<col para='yes'>" + to_xml(workcenter.name) + "</col>" xml += "<col/>" xml += """<col f='yes'>""" + rml_obj.formatLang(cost_cycle) + " " + (company_currency_symbol) + """</col>""" xml += """<col f='yes'>""" + rml_obj.formatLang(cost_hour) + " " + (company_currency_symbol) + """</col>""" xml += ( """<col f='yes'>""" + rml_obj.formatLang(cost_hour + cost_cycle) + " " + (company_currency_symbol) + """</col>""" ) xml += "</row>" return xml, total xml = "" config_start = ( """ <config> <date>""" + to_xml(rml_obj.formatLang(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), date_time=True)) + """</date> <company>%s</company> <PageSize>210.00mm,297.00mm</PageSize> <PageWidth>595.27</PageWidth> <PageHeight>841.88</PageHeight> <tableSize>55.00mm,58.00mm,29.00mm,29.00mm,29.00mm</tableSize> """ % to_xml(user_pool.browse(cr, uid, uid).company_id.name) ) config_stop = """ <report-footer>Generated by Odoo</report-footer> </config> """ workcenter_header = """ <lines style='header'> <row> <col>%s</col> <col t='yes'/> <col t='yes'>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row> </lines> """ % ( _("Work Center name"), _("Cycles Cost"), _("Hourly Cost"), _("Work Cost"), ) prod_header = """ <row> <col>%s</col> <col>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row> """ % ( _("Components"), _("Components suppliers"), _("Quantity"), _("Cost Price per Unit of Measure"), _("Supplier Price per Unit of Measure"), ) purchase_price_digits = rml_obj.get_digits(dp="Product Price") for product in product_pool.browse(cr, uid, ids, context=context): product_uom_name = to_xml(product.uom_id.name) bom_id = bom_pool._bom_find(cr, uid, product_id=product.id, context=context) title = "<title>%s</title>" % (_("Cost Structure")) title += "<title>%s</title>" % (to_xml(product.name)) xml += "<lines style='header'>" + title + prod_header + "</lines>" if not bom_id: total_strd = number * product.standard_price total = number * product_pool.price_get(cr, uid, [product.id], "standard_price")[product.id] xml += """<lines style='lines'><row> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> </row></lines>""" xml += ( """<lines style='total'> <row> <col> """ + _("Total Cost of %s %s") % (str(number), product_uom_name) + """: </col> <col/> <col f='yes'/> <col t='yes'>""" + rml_obj.formatLang(total_strd, digits=purchase_price_digits) + " " + (company_currency_symbol) + """</col> <col t='yes'>""" + rml_obj.formatLang(total, digits=purchase_price_digits) + " " + (company_currency_symbol) + """</col> </row></lines>'""" ) else: bom = bom_pool.browse(cr, uid, bom_id, context=context) factor = number * product.uom_id.factor / bom.product_uom.factor sub_boms = bom_pool._bom_explode(cr, uid, bom, product, factor / bom.product_qty, context=context) total = 0 total_strd = 0 parent_bom = { "product_qty": bom.product_qty, "name": bom.product_id.name, "product_uom": bom.product_uom.id, "product_id": bom.product_id.id, } xml_tmp = "" for sub_bom in (sub_boms and sub_boms[0]) or [parent_bom]: txt, sum, sum_strd = process_bom(sub_bom, company_currency.id) xml_tmp += txt total += sum total_strd += sum_strd xml += "<lines style='lines'>" + xml_tmp + "</lines>" xml += ( """<lines style='sub_total'> <row> <col> """ + _("Components Cost of %s %s") % (str(number), product_uom_name) + """: </col> <col/> <col t='yes'/> <col t='yes'>""" + rml_obj.formatLang(total_strd, digits=purchase_price_digits) + " " + (company_currency_symbol) + """</col> <col t='yes'></col> </row></lines>'""" ) total2 = 0 xml_tmp = "" for wrk in sub_boms and sub_boms[1]: txt, sum = process_workcenter(wrk) xml_tmp += txt total2 += sum if xml_tmp: xml += workcenter_header xml += "<lines style='lines'>" + xml_tmp + "</lines>" xml += ( """<lines style='sub_total'> <row> <col> """ + _("Work Cost of %s %s") % (str(number), product_uom_name) + """: </col> <col/> <col/> <col/> <col t='yes'>""" + rml_obj.formatLang(total2, digits=purchase_price_digits) + " " + (company_currency_symbol) + """</col> </row></lines>'""" ) xml += ( """<lines style='total'> <row> <col> """ + _("Total Cost of %s %s") % (str(number), product_uom_name) + """: </col> <col/> <col t='yes'/> <col t='yes'>""" + rml_obj.formatLang(total_strd + total2, digits=purchase_price_digits) + " " + (company_currency_symbol) + """</col> <col t='yes'></col> </row></lines>'""" ) xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + "</report>" return xml
def create_xml(self, cr, uid, ids, datas, context=None): obj_emp = pooler.get_pool(cr.dbname).get('hr.employee') if context is None: context = {} month = datetime(datas['form']['year'], datas['form']['month'], 1) emp_ids = datas['active_ids'] user_xml = ['<month>%s</month>' % _(month2name[month.month]), '<year>%s</year>' % month.year] if emp_ids: for emp in obj_emp.read(cr, uid, emp_ids, ['name']): stop, days_xml = False, [] total_wh = 0.0 user_repr = ''' <user> <name>%s</name> %%s </user> ''' % (ustr(toxml(emp['name']))) today, tomor = month, month + one_day while today.month == month.month: #### Work hour calculation sql = ''' select action, att.name from hr_employee as emp inner join hr_attendance as att on emp.id = att.employee_id where att.name between %s and %s and emp.id = %s order by att.name ''' cr.execute(sql, (today.strftime('%Y-%m-%d %H:%M:%S'), tomor.strftime('%Y-%m-%d %H:%M:%S'), emp['id'])) attendences = cr.dictfetchall() wh = 0.0 # Fake sign ins/outs at week ends, to take attendances across week ends into account if attendences and attendences[0]['action'] == 'sign_out': attendences.insert(0, {'name': today.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_in'}) if attendences and attendences[-1]['action'] == 'sign_in': attendences.append({'name': tomor.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_out'}) # sum up the attendances' durations ldt = None for att in attendences: dt = datetime.strptime(att['name'], '%Y-%m-%d %H:%M:%S') if ldt and att['action'] == 'sign_out': if dt.date() > ldt.date(): dt = ldt wh += (float((dt - ldt).seconds)/60/60) else: ldt = dt # Week xml representation total_wh += wh wh = hour2str(wh) today_xml = '<day num="%s"><wh>%s</wh></day>' % ((today - month).days+1, (wh)) dy=(today - month).days+1 days_xml.append(today_xml) today, tomor = tomor, tomor + one_day total_wh = hour2str(total_wh) today_xml = '<day num="Total"><wh>%s</wh></day>' % (total_wh) days_xml.append(today_xml) user_xml.append(user_repr % '\n'.join(days_xml)) rpt_obj = pooler.get_pool(cr.dbname).get('hr.employee') rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context) header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),to_xml(pooler.get_pool(cr.dbname).get('res.users').browse(cr,uid,uid).company_id.name)) first_date = str(month) som = datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S') eom = som + timedelta(int(dy)-1) day_diff=eom-som date_xml=[] cell=1 date_xml.append('<days>') if day_diff.days>=30: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)] else: if day_diff.days>=(lengthmonth(som.year, som.month)-som.day): date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)] else: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, eom.day+1)] cell=x-som.day+1 day_diff1=day_diff.days-cell+1 width_dict={} month_dict={} i=1 j=1 year=som.year month=som.month month_dict[j]=som.strftime('%B') width_dict[j]=cell while day_diff1>0: if month+i<=12: if day_diff1 > lengthmonth(year,i+month): # Not on 30 else you have problems when entering 01-01-2009 for example som1=datetime.date(year,month+i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(year,i+month)+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x else: som1=datetime.date(year,month+i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x day_diff1=day_diff1-x else: years=year+1 year=years month=0 i=1 if day_diff1>=30: som1=datetime.date(years,i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(years,i)+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x else: som1=datetime.date(years,i,1) i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)] cell=cell+x width_dict[j]=x day_diff1=day_diff1-x date_xml += ['<dayy name="Total" cell="Total"/>'] date_xml.append('</days>') date_xml.append('<cols>3.5cm%s,1.2cm</cols>\n' % (',0.74cm' * (int(dy)))) xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s <title>%s</title> %s %s </report> ''' % (header_xml,_('Attendances by Month'),'\n'.join(user_xml),date_xml) return xml
def create(self, cr, uid, ids, datas, context): del_obj = pooler.get_pool(cr.dbname).get('stock.picking.out') user_obj = pooler.get_pool(cr.dbname).get('res.users') rml_obj = report_sxw.rml_parse(cr, uid, del_obj._name, context) company = user_obj.browse(cr, uid, [uid], context)[0].company_id rml = """<document filename="QC Documents.pdf"> <template pageSize="(595.0,842.0)" title="QC Documents" author="OpenERP S.A.([email protected])" allowSplitting="20"> <pageTemplate> <frame id="first" x1="1.3cm" y1="1.5cm" width="18.4cm" height="26.5cm"/> <stylesheet> <blockTableStyle id="Table4"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="0,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="0,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="0,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="1,0" stop="1,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="1,0" stop="1,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="1,-1" stop="1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="2,0" stop="2,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="2,0" stop="2,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="2,-1" stop="2,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="3,0" stop="3,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="3,0" stop="3,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="3,0" stop="3,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="4,0" stop="4,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="4,0" stop="4,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="4,0" stop="4,-1"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="5,0" stop="5,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="5,0" stop="5,0"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="5,0" stop="5,-1"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="5,-1" stop="5,-1"/> </blockTableStyle> <blockTableStyle id="Table_Title_String"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <initialize> <paraStyle name="all" alignment="justify"/> </initialize> <paraStyle name="Standard" fontName="Helvetica"/> <paraStyle name="main_footer" fontSize="8.0" alignment="CENTER"/> <paraStyle name="main_header" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_header" fontName="Helvetica-Bold" fontSize="12.0" leading="15" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="Heading" fontName="Helvetica" fontSize="14.0" leading="17" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_Details" fontName="Helvetica" fontSize="14.0" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="content_Details" fontName="Helvetica" fontSize="12.0" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <images/> </stylesheet> <pageGraphics> <!-- Set here the default font to use for all <drawString> tags --> <setFont name="DejaVu Sans" size="8"/> <!-- You Logo - Change X,Y,Width and Height --> <image x="1.3cm" y="27.7cm" height="40.0" >""" + to_xml( company.logo) + """</image> <fill color="black"/> <stroke color="black"/> <!-- page header --> <lines>1.3cm 27.7cm 20cm 27.7cm</lines> <drawRightString x="20cm" y="27.8cm">""" + to_xml( company.rml_header1) + """</drawRightString> <drawString x="1.3cm" y="27.3cm">""" + to_xml( company.partner_id.name) + """</drawString> <place x="1.3cm" y="25.3cm" height="1.8cm" width="15.0cm"> <para style="main_header">""" + to_xml( company.partner_id.street or '') + """</para> <para style="main_header">""" + to_xml( company.partner_id.street2 or '') + """</para> <para style="main_header">""" + to_xml( company.partner_id.city or '') + """,""" + to_xml( company.partner_id.state_id.name or '') + """</para> <para style="main_header">""" + to_xml( company.partner_id.country_id.name or '') + """ - """ + to_xml( company.partner_id.zip or '') + """</para> </place> <drawString x="1.3cm" y="25.0cm">Phone:</drawString> <drawRightString x="7cm" y="25.0cm">""" + to_xml( company.partner_id.phone or '') + """</drawRightString> <drawString x="1.3cm" y="24.6cm">Mail:</drawString> <drawRightString x="7cm" y="24.6cm">""" + to_xml( company.partner_id.email or '') + """</drawRightString> <lines>1.3cm 24.5cm 7cm 24.5cm</lines> <!-- left margin --> <rotate degrees="90"/> <fill color="grey"/> <drawString x="2.65cm" y="-0.4cm">generated by OpenERP.com</drawString> <fill color="black"/> <rotate degrees="-90"/> <!-- page footer --> <lines>1.2cm 2.65cm 19.9cm 2.65cm</lines> <place x="1.3cm" y="0cm" height="2.55cm" width="19.0cm"> <para style="main_footer">""" + to_xml( company.rml_footer or '') + """</para> <para style="main_footer">Contact : """ + to_xml( company.name ) + """- Page: <pageNumber/></para> </place> </pageGraphics> </pageTemplate> </template> """ lst = [] for line in del_obj.browse(cr, uid, ids): main_list = self.get_analysis_data(cr, uid, line.move_lines) for sub in main_list: rml += """ <story> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <blockTable colWidths="538.0" style="Table_Title_String"> <tr> <td> <para style="terp_header">Delivery Order : """ + to_xml( line.name or '') + """</para> <para style="terp_header">Sale Order : """ + to_xml( line.origin or '') + """</para> <para style="terp_header">QC Number : </para> </td> </tr> </blockTable> <para style="Standard"> <font color="white"> </font> </para> <para style="Standard"> <font color="white"> </font> </para> <blockTable colWidths="210.0,90.0,90.0,90.0,55.0" rowHeights="40" style="Table4"> <tr> <td> <para style="terp_tblheader_Details"><b>CHARACTERISTIC</b></para> </td> <td> <para style="terp_tblheader_Details"><b>Actual Value</b></para> </td> <td> <para style="terp_tblheader_Details"><b>Upper Limit</b></para> </td> <td> <para style="terp_tblheader_Details"><b>Lower Limit</b></para> </td> <td> <para style="terp_tblheader_Details"><b>ok?</b></para> </td> </tr> </blockTable> """ for sub_list in sub: rml += """ <blockTable colWidths="210.0,90.0,90.0,90.0,55.0" style="Table4"> <tr> <td> <para style="content_Details">""" + str( sub_list['name']) + """</para> </td> <td> <para style="content_Details">""" + sub_list[ 'actual'] + """</para> </td> <td> <para style="content_Details">""" + str( sub_list['upper']) + """</para> </td> <td> <para style="content_Details">""" + str( sub_list['lower']) + """</para> </td> <td> <para style="content_Details">""" + str( sub_list['ok']) + """</para> </td> </tr> </blockTable> """ rml += """</story> """ rml += """</document> """ report_type = datas.get('report_type', 'pdf') create_doc = self.generators[report_type] self.internal_header = False pdf = create_doc(rml, title=self.title) return (pdf, report_type)
def create_xml(self, cr, uid, ids, data, context): registry = openerp.registry(cr.dbname) obj_emp = registry['hr.employee'] depts = [] emp_id = {} rpt_obj = registry['hr_attendance.record.report'] rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context) cr.execute("SELECT name FROM res_company") res = cr.fetchone()[0] date_xml = [] date_today = time.strftime('%Y-%m-%d %H:%M:%S') date_xml += [ '<res name="%s" today="%s" />' % (to_xml(res), date_today) ] legend = { 'Present': 'green', 'Weekends': 'lightgrey', 'Absent': 'red', 'Leave': 'violet', 'Public Holiday': 'blue' } today = datetime.datetime.today() today_year = today.strftime('%Y-%m-%d %H:%M:%S')[0:4] #### Check for Filter in Wizard to get Start and end date ##### if data['form']['filter_by_date'] == True: first_date = datetime.datetime.strptime( data['form']['date_from'], '%Y-%m-%d') + datetime.timedelta() last_date = datetime.datetime.strptime( data['form']['date_to'], '%Y-%m-%d') + datetime.timedelta() else: month_selected = data['form']['monthly_status'] first_date = datetime.datetime(int(today_year), int(month_selected), 1) number_of_days = lengthmonth(int(today_year), int(month_selected)) last_date = datetime.datetime(int(today_year), int(month_selected), number_of_days) day_diff = last_date - first_date name = '' if len(data['form'].get('emp_id', ())) == 1: name = obj_emp.read(cr, uid, data['form']['emp_id'][0], ['name'])['name'] date_xml.append('<from>%s</from>\n' % (str( rml_obj.formatLang(first_date.strftime("%Y-%m-%d"), date=True)))) date_xml.append('<to>%s</to>\n' % (str( rml_obj.formatLang(last_date.strftime("%Y-%m-%d"), date=True)))) date_xml.append('<name>%s</name>' % (name)) # date_xml=[] for l in range(0, len(legend)): date_xml += [ '<legend row="%d" id="%d" name="%s" color="%s" />' % (l + 1, l + 1, legend.keys()[l], legend.values()[l]) ] date_xml += [ '<date month="%s" year="%d" />' % (ustr(first_date.strftime('%B')), first_date.year), '<days>' ] cell = 1 if day_diff.days >= 31: date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(first_date.replace(day=x).strftime('%a')), x - first_date.day + 1) for x in range(first_date.day, day_diff.days + 1) ] else: #date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(first_date.replace(day=x).strftime('%a')), x-first_date.day+1) for x in range(first_date.day, last_date.day+1)] if day_diff.days >= (lengthmonth(first_date.year, first_date.month) - first_date.day): date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(first_date.replace(day=x).strftime('%a')), x - first_date.day + 1) for x in range( first_date.day, lengthmonth(first_date.year, first_date.month) + 1) ] else: date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(first_date.replace(day=x).strftime('%a')), x - first_date.day + 1) for x in range(first_date.day, last_date.day + 1) ] cell = x - first_date.day + 1 day_diff1 = day_diff.days - cell + 1 width_dict = {} month_dict = {} i = 1 j = 1 year = first_date.year month = first_date.month month_dict[j] = first_date.strftime('%B') width_dict[j] = cell while day_diff1 > 0: if month + i <= 12: # If month + i <=12 if day_diff1 > lengthmonth( year, i + month ): # Not on 30 else you have problems when entering 01-01-2009 for example som1 = datetime.date(year, month + i, 1) date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')), cell + x) for x in range(1, lengthmonth(year, i + month) + 1) ] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x else: som1 = datetime.date(year, month + i, 1) date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')), cell + x) for x in range(1, last_date.day + 1) ] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x day_diff1 = day_diff1 - x date_xml.append('</days>') date_xml.append('<cols>3.5cm%s,1.0cm</cols>\n' % (',0.7cm' * (day_diff.days + 1))) date_xml = ''.join(date_xml) st = '<cols_months>3.5cm' for m in range(1, len(width_dict) + 1): st += ',' + str(0.7 * width_dict[m]) + 'cm' st += ',1.0cm</cols_months>\n' months_xml = [ '<months number="%d" name="%s"/>' % (x, _(month_dict[x])) for x in range(1, len(month_dict) + 1) ] months_xml.append(st) emp_xml = '' row_id = 1 if data['model'] == 'hr.employee': for items in obj_emp.read(cr, uid, data['form']['emp_id'], ['id', 'name']): emp_xml += emp_create_xml(self, cr, uid, 0, row_id, items['id'], items['name'], first_date, last_date) row_id = row_id + 1 header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), to_xml(registry['res.users'].browse(cr, uid, uid).company_id.name)) # Computing the xml xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s %s </report> ''' % (header_xml, months_xml, date_xml, ustr(emp_xml)) return xml
def default_get(self, cr, uid, fields, context=None): res = super(account_invoice_collection, self).default_get(cr, uid, fields, context=context) invoice_ids = context.get('active_ids', False) rml_parser = report_sxw.rml_parse(cr, uid, 'reconciliation_widget_aml', context=context) if invoice_ids and context.get('active_model', False) == 'account.invoice': invoices = self.pool.get('account.invoice').browse(cr, uid, invoice_ids, context=context) cust = [] total_unpaid = 0.0 text = "%s \n" % (invoices and invoices[0] and invoices[0].partner_id and invoices[0].partner_id.name) date_dict = {} for inv in invoices: key = inv.date_invoice if date_dict.get(key): date_dict[key]['total'] += inv.residual else: date_dict[key] = { 'date_invoice': inv.date_invoice, 'total': inv.residual, 'currency_id': inv.currency_id } for k, v in sorted(date_dict.items()): text += "%s %s\n" % (v['date_invoice'], rml_parser.formatLang( v['total'], currency_obj=v['currency_id'])) # cust.append(inv.partner_id and inv.partner_id.id) total_unpaid += v['total'] or 0.0 # text += "%s %s\n"%(inv.date_invoice,rml_parser.formatLang(inv.residual, currency_obj=inv.currency_id)) text += "\nSubTotal : %s\n" % (rml_parser.formatLang( total_unpaid, currency_obj=inv.currency_id)) cb_model, journal_id = self.pool.get( 'ir.model.data').get_object_reference(cr, uid, 'account_cash_back', 'cash_back_journal') unreconciled_payment = [('partner_id', '=', inv.partner_id and inv.partner_id.id), ('reconcile_id', '=', False), ('account_id.type', '=', 'receivable'), ('credit', '>', 0.0), ('journal_id', '!=', journal_id)] aml_ids = self.pool.get('account.move.line').search( cr, uid, unreconciled_payment) unreconciled = 0.0 if aml_ids: amls = self.pool.get('account.move.line').browse( cr, uid, aml_ids) for aml in amls: if aml.amount_residual > 0.0: unreconciled += aml.amount_residual # unreconciled+= aml.amount_residual text += "Lebih bayar : %s\n" % (rml_parser.formatLang( abs(unreconciled), currency_obj=inv.currency_id)) cashback_amt = 0.0 cbl_ids = self.pool.get('account.cashback.line').search( cr, uid, [('name', '=', inv.partner_id.id), ('state', '=', 'approved')]) cbl = self.pool.get('account.cashback.line').browse( cr, uid, cbl_ids, context=context) for cashback in cbl: cashback_amt += cashback.cash_back_amt unreconciled_payment = [('partner_id', '=', inv.partner_id and inv.partner_id.id), ('reconcile_id', '=', False), ('account_id.type', '=', 'receivable'), ('credit', '>', 0.0), ('journal_id', '=', journal_id)] aml_ids = self.pool.get('account.move.line').search( cr, uid, unreconciled_payment) if aml_ids: amls = self.pool.get('account.move.line').browse( cr, uid, aml_ids) for aml in amls: if aml.amount_residual > 0.0: cashback_amt += aml.amount_residual text += "Cashback : %s" % (rml_parser.formatLang( abs(cashback_amt), currency_obj=inv.currency_id)) text += "\nTotal : %s\n" % (rml_parser.formatLang( (total_unpaid - abs(unreconciled) - abs(cashback_amt)), currency_obj=inv.currency_id)) text += "\nPembayaran dapat melalui : \n\nBANK BCA \nNO rekening : 270 390 3088 \nAtas Nama: Sicepat Ekspres Indonesia\n\nBANK MANDIRI \nNO rekening : 121 000 655 7171 \nAtas Nama : Sicepat Ekspres Indonesia\n\nBANK BNI \nNO rekening : 4964 66952\nAtas Nama : Sicepat Ekspres Indonesia\n\nBANK BRI \nNO rekening : 0338 01 001027 30 7\nAtas Nama : Sicepat Ekspres Indonesia" text += "\n\nHarap isi berita acara nama OLSHOP dan tanggal pengiriman di berita acara.\nContoh: 'SiCepatShop 19Feb15'" elif invoice_ids and context.get('active_model', False) == 'account.move.line': invoices = self.pool.get('account.move.line').browse( cr, uid, invoice_ids, context=context) cust = [] total_unpaid = 0.0 text = "%s \n" % (invoices and invoices[0] and invoices[0].partner_id and invoices[0].partner_id.name) import locale import re date_dict = {} for inv in invoices: key = inv.date if date_dict.get(key): date_dict[key]['total'] += inv.amount_residual else: date_dict[key] = { 'date': inv.date, 'total': inv.amount_residual, 'currency_id': inv.company_id.currency_id } for k, v in sorted(date_dict.items()): text += "%s %s\n" % (v['date'], rml_parser.formatLang( v['total'], currency_obj=v['currency_id'])) # cust.append(inv.partner_id and inv.partner_id.id) total_unpaid += v['total'] or 0.0 # text += "%s %s\n"%(inv.date_invoice,rml_parser.formatLang(inv.residual, currency_obj=inv.currency_id)) text += "\nSubTotal : %s\n" % (rml_parser.formatLang( total_unpaid, currency_obj=inv.company_id.currency_id)) # for inv in invoices: # if inv.invoice and inv.invoice.cashback_ids and inv.invoice.cashback_ids != [] : # continue # cust.append(inv.partner_id and inv.partner_id.id) # total_unpaid += inv.amount_residual or 0.0 # # print "=================",inv.amount_residual,total_unpaid # result = re.findall("(\d\d)\-(.*?)\-(\w+)",inv.name) # substring=False # if result and result[0]: # substring=result[0][0]+"-"+result[0][1]+"-"+result[0][2] # subst_date = False # try: # try: # try: # locale.setlocale(locale.LC_TIME,"id_ID.UTF-8") # subst_date = datetime.strptime(substring,'%d-%b-%y') # except: # locale.setlocale(locale.LC_TIME,"en_US.UTF-8") # subst_date = datetime.strptime(substring,'%d-%b-%y') # except: # locale.setlocale(locale.LC_TIME,"en_US.UTF-8") # subst_date = datetime.strptime(substring,'%d-%m-%Y') # locale.setlocale(locale.LC_TIME,"en_US.UTF-8") # except: # subst_date=False # inv_date = datetime.strptime(inv.date,'%Y-%m-%d') # if subst_date and subst_date != inv_date: # inv_date = subst_date # inv_date=datetime.strftime(inv_date,'%Y-%m-%d') # text += "%s %s\n"%(inv_date,rml_parser.formatLang(inv.amount_residual, currency_obj=inv.currency_id or inv.company_id.currency_id)) # text+="\nSubTotal : %s\n"%(rml_parser.formatLang(total_unpaid, currency_obj=inv.currency_id or inv.company_id.currency_id)) unreconciled_payment = [('partner_id', '=', inv.partner_id and inv.partner_id.id), ('reconcile_id', '=', False), ('account_id.type', '=', 'receivable'), ('credit', '>', 0.0)] aml_ids = self.pool.get('account.move.line').search( cr, uid, unreconciled_payment) unreconciled = 0.0 if aml_ids: amls = self.pool.get('account.move.line').browse( cr, uid, aml_ids) for aml in amls: if aml.amount_residual > 0.0: unreconciled += aml.amount_residual text += "Lebih bayar : %s\n" % (rml_parser.formatLang( abs(unreconciled), currency_obj=inv.company_id.currency_id)) cashback_amt = 0.0 cbl_ids = self.pool.get('account.cashback.line').search( cr, uid, [('name', '=', inv.partner_id.id), ('state', '=', 'approved')]) cbl = self.pool.get('account.cashback.line').browse( cr, uid, cbl_ids, context=context) for cashback in cbl: cashback_amt += cashback.cash_back_amt text += "Cashback : %s" % (rml_parser.formatLang( abs(cashback_amt), currency_obj=inv.company_id.currency_id)) text += "\nTotal : %s\n" % (rml_parser.formatLang( (total_unpaid - abs(unreconciled) - abs(cashback_amt)), currency_obj=inv.company_id.currency_id)) text += "\nPembayaran dapat melalui : \n\nBANK BCA \nNO rekening : 270 390 3088 \nAtas Nama: Sicepat Ekspres Indonesia\n\nBANK MANDIRI \nNO rekening : 121 000 655 7171 \nAtas Nama : Sicepat Ekspres Indonesia\n\nBANK BNI \nNO rekening : 4964 66952\nAtas Nama : Sicepat Ekspres Indonesia\n\nBANK BRI \nNO rekening : 0338 01 001027 30 7\nAtas Nama : Sicepat Ekspres Indonesia" text += "\n\nHarap isi berita acara nama OLSHOP dan tanggal pengiriman di berita acara.\nContoh: 'SiCepatShop 19Feb15'" res.update({ 'name': text, }) return res
def make_counter_part_lines(self, cr, uid, st_line, line_ids, count=False, context=None): if context is None: context = {} mv_line_pool = self.pool.get('account.move.line') currency_obj = self.pool.get('res.currency') company_currency = st_line.journal_id.company_id.currency_id statement_currency = st_line.journal_id.currency or company_currency rml_parser = report_sxw.rml_parse(cr, uid, 'statement_line_counterpart_widget', context=context) #partially reconciled lines can be displayed only once reconcile_partial_ids = [] if count: nb_lines = 0 for line in mv_line_pool.browse(cr, uid, line_ids, context=context): if line.reconcile_partial_id and line.reconcile_partial_id.id in reconcile_partial_ids: continue nb_lines += 1 if line.reconcile_partial_id: reconcile_partial_ids.append(line.reconcile_partial_id.id) return nb_lines else: ret = [] for line in mv_line_pool.browse(cr, uid, line_ids, context=context): if line.reconcile_partial_id and line.reconcile_partial_id.id in reconcile_partial_ids: continue amount_currency_str = "" if line.currency_id and line.amount_currency: amount_currency_str = rml_parser.formatLang(line.amount_currency, currency_obj=line.currency_id) ret_line = { 'id': line.id, 'name': line.move_id.name, 'ref': line.move_id.ref, 'account_code': line.account_id.code, 'account_name': line.account_id.name, 'account_type': line.account_id.type, 'date_maturity': line.date_maturity, 'date': line.date, 'period_name': line.period_id.name, 'journal_name': line.journal_id.name, 'amount_currency_str': amount_currency_str, 'partner_id': line.partner_id.id, 'partner_name': line.partner_id.name, 'has_no_partner': not bool(st_line.partner_id.id), } st_line_currency = st_line.currency_id or statement_currency if st_line.currency_id and line.currency_id and line.currency_id.id == st_line.currency_id.id: if line.amount_residual_currency < 0: ret_line['debit'] = 0 ret_line['credit'] = -line.amount_residual_currency else: ret_line['debit'] = line.amount_residual_currency if line.credit != 0 else 0 ret_line['credit'] = line.amount_residual_currency if line.debit != 0 else 0 ret_line['amount_currency_str'] = rml_parser.formatLang(line.amount_residual, currency_obj=company_currency) else: if line.amount_residual < 0: ret_line['debit'] = 0 ret_line['credit'] = -line.amount_residual else: ret_line['debit'] = line.amount_residual if line.credit != 0 else 0 ret_line['credit'] = line.amount_residual if line.debit != 0 else 0 ctx = context.copy() ctx.update({'date': st_line.date}) ret_line['debit'] = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, ret_line['debit'], context=ctx) ret_line['credit'] = currency_obj.compute(cr, uid, st_line_currency.id, company_currency.id, ret_line['credit'], context=ctx) ret_line['debit_str'] = rml_parser.formatLang(ret_line['debit'], currency_obj=st_line_currency) ret_line['credit_str'] = rml_parser.formatLang(ret_line['credit'], currency_obj=st_line_currency) ret.append(ret_line) if line.reconcile_partial_id: reconcile_partial_ids.append(line.reconcile_partial_id.id) return ret
def create_xml(self,cr,uid,ids,datas,context={}): def _thousand_separator(decimal,amount): if not amount: amount = 0.0 if type(amount) is float : amount = str(decimal%amount) else : amount = str(amount) if (amount == '0'): return ' ' orig = amount new = re.sub("^(-?\d+)(\d{3})", "\g<1>.\g<2>", amount) if orig == new: return new else: return _thousand_separator(decimal,new) pool = openerp.registry(cr.dbname) order_obj = pool.get('sale.order') wh_obj = pool.get('stock.warehouse') session_obj = pool.get('pos.session') user_obj = pool.get('res.users') users = user_obj.browse(cr,uid,uid) warehouse_ids = datas['form']['warehouse_ids'] or wh_obj.search(cr, uid, []) company = users.company_id rml_parser = report_sxw.rml_parse(cr, uid, 'edukits_total_retail', context=context) rml = """ <document filename="test.pdf"> <template pageSize="(21.0cm,29.7cm)" title="Total Retail Report" author="SGEEDE" allowSplitting="20"> <pageTemplate id="first"> <frame id="first" x1="50.0" y1="0.0" width="500" height="830"/> </pageTemplate> </template> <stylesheet> <blockTableStyle id="Table1"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="parent_table"> <blockAlignment value="LEFT"/> <blockLeftPadding start="0,0" length="0.1cm"/> <blockRightPadding start="0,0" length="0.1cm"/> <blockTopPadding start="0,0" length="0.15cm"/> <blockBottomPadding start="0,0" length="0.15cm"/> </blockTableStyle> <blockTableStyle id="Table2"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="Table3"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table3_Normal"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <blockTopPadding start="0,0" length="-0.15cm"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,1" stop="0,1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="0,0"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="Table3_PARENT"> <blockAlignment value="CENTER"/> <blockValign value="TOP"/> </blockTableStyle> """ for warehouse in wh_obj.browse(cr,uid,warehouse_ids): if warehouse.color: rml += """ <blockTableStyle id="Table3""" + to_xml(str(warehouse.color.name)) + """"> <blockBackground colorName="#"""+ to_xml(str(warehouse.color.color)) + """" start="0,0" stop="0,-1"/> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <blockTopPadding start="0,0" length="0.1cm"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,1" stop="0,1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="0,0"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="0,0" stop="-1,-1"/> </blockTableStyle> """ if not warehouse.color: rml += """ <blockTableStyle id="Table3False"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <blockTopPadding start="0,0" length="0.1cm"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,1" stop="0,1"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="0,0"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="0,0" stop="-1,-1"/> </blockTableStyle> """ rml += """ <blockTableStyle id="Table3_LINE"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="2,0" stop="2,3"/> </blockTableStyle> <blockTableStyle id="Table3_LINE2"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table3_LINE2W"> <blockBackground colorName="white"/> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table1_line"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="2,0"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="2,0"/> </blockTableStyle> <blockTableStyle id="Table1_lines"> <blockBackground colorName="white"/> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="2,0"/> <lineStyle kind="LINEABOVE" colorName="#000000" start="0,0" stop="2,0"/> <lineStyle kind="LINEBEFORE" colorName="#000000" start="0,0" stop="2,0"/> <lineStyle kind="LINEAFTER" colorName="#000000" start="0,0" stop="2,0"/> </blockTableStyle> <initialize> <paraStyle name="all" alignment="justify"/> </initialize> <paraStyle name="P1" fontName="Helvetica" fontSize="9.0" leading="11" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P2" fontName="Helvetica-Bold" fontSize="14.0" leading="17" alignment="RIGHT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P3" fontName="Times-Roman" fontSize="11.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P4" fontName="Times-Roman" fontSize="11.0" leading="10" alignment="RIGHT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P5" fontName="Times-Roman" fontSize="11.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P6" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="6.0"/> <paraStyle name="P7" fontName="Helvetica" fontSize="9.0" leading="11" alignment="CENTER" spaceBefore="0.0" spaceAfter="6.0"/> <paraStyle name="P8" fontName="Helvetica" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="6.0"/> <paraStyle name="P9" fontName="Times-Roman" fontSize="11.0" leading="14" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P10" fontName="Times-Roman" fontSize="11.0" leading="14" alignment="RIGHT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P11" fontName="Times-Roman" fontSize="11.0" leading="14" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P12" fontName="Helvetica" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="6.0"/> <paraStyle name="P13" fontName="Helvetica" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P14" fontName="Helvetica-Bold" fontSize="12.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="P15" textColor="black" fontName="Helvetica" fontSize="10.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="P15_W" textColor="white" fontName="Helvetica" fontSize="10.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="P15_RIGHT" textColor="black" fontName="Helvetica" fontSize="10.0" leading="11" alignment="RIGHT" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="P15_CENTER" textColor="black" fontName="Helvetica-Bold" fontSize="12.0" leading="11" alignment="CENTER" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="P15_CENTER_2" textColor="black" fontName="Helvetica-Bold" fontSize="14.0" leading="11" alignment="CENTER" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="P16" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P17" fontName="Times-Roman" fontSize="8.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="P19" rightIndent="0.0" leftIndent="0.0" fontName="Times-Roman" fontSize="10.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P20" rightIndent="0.0" leftIndent="0.0" fontName="Helvetica" fontSize="12.0" leading="11" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="Standard" fontName="Times-Roman"/> <paraStyle name="Text body" fontName="Times-Roman" spaceBefore="0.0" spaceAfter="6.0"/> <paraStyle name="List" fontName="Times-Roman" spaceBefore="0.0" spaceAfter="6.0"/> <paraStyle name="Table Contents" fontName="Times-Roman" spaceBefore="0.0" spaceAfter="6.0"/> <paraStyle name="Table Heading" fontName="Times-Roman" alignment="CENTER" spaceBefore="0.0" spaceAfter="6.0"/> <paraStyle name="Caption" fontName="Times-Roman" fontSize="10.0" leading="13" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="Index" fontName="Times-Roman"/> <paraStyle name="Heading" fontName="Helvetica" fontSize="15.0" leading="19" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="Footer" fontName="Times-Roman"/> <paraStyle name="Horizontal Line" fontName="Times-Roman" fontSize="6.0" leading="8" spaceBefore="0.0" spaceAfter="14.0"/> <paraStyle name="terp_header" fontName="Helvetica-Bold" fontSize="15.0" leading="19" alignment="LEFT" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="Heading 9" fontName="Helvetica-Bold" fontSize="75%" leading="NaN" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_General" fontName="Helvetica-Bold" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_Details" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_default_8" fontName="Helvetica" fontSize="9.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_Bold_8" fontName="Helvetica-Bold" fontSize="8.0" leading="10" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="8.0" leading="10" alignment="CENTER" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_General_Right" fontName="Helvetica-Bold" fontSize="8.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_Details_Centre" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="CENTER" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_Details_Right" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_default_Right_8" fontName="Helvetica" fontSize="8.0" leading="10" alignment="RIGHT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_Centre_8" fontName="Helvetica" fontSize="8.0" leading="10" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_header_Right" fontName="Helvetica-Bold" fontSize="15.0" leading="19" alignment="LEFT" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="terp_header_Centre" fontName="Helvetica-Bold" fontSize="15.0" leading="19" alignment="CENTER" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="terp_header_Centre2" fontName="Helvetica-Bold" fontSize="12.0" leading="19" alignment="CENTER" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="terp_header_Centre3" fontName="Helvetica-Bold" fontSize="12.0" leading="19" alignment="LEFT" spaceBefore="12.0" spaceAfter="6.0"/> <paraStyle name="terp_default_address" fontName="Helvetica" fontSize="10.0" leading="13" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_12" fontName="Helvetica" fontSize="12.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_Bold_9" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_Bold_9_Right" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="RIGHT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_Centre_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="CENTER" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_Right_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="RIGHT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="Heading 1" fontName="Times-Bold" fontSize="24.0" leading="29" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="Heading 2" fontName="Times-Bold" fontSize="20.0" leading="29" spaceBefore="0.0" spaceAfter="0.0"/> <images/> </stylesheet> <story> """ no_total = 1 rml += """ <blockTable colWidths="250,250" style="Table3_PARENT"> """ # Day transaction for batamcentre center = False currency_amount = 0 currency_symbol ='' bank_ids = [] date_end = datetime.strptime(datas['form']['date_end'],"%Y-%m-%d") for warehousebtc in wh_obj.browse(cr,uid,warehouse_ids): currency_amount = warehousebtc.currency_id.rate_silent currency_symbol = warehousebtc.currency_id.symbol location_id = warehousebtc.lot_stock_id date_start = datetime.strptime(datas['form']['date_end']+ ' 00:00:00',"%Y-%m-%d %H:%M:%S") date_stop = datetime.strptime(datas['form']['date_end']+ ' 17:59:59',"%Y-%m-%d %H:%M:%S") if warehousebtc.is_split: center = True sessionbtc_ids = session_obj.search(cr,uid,[('stock_location_rel','=',location_id.id),('stop_at','!=',False)]) session_ids = [] results = [] for sessions in session_obj.browse(cr,uid,sessionbtc_ids): stop_temp=datetime.strptime(sessions.stop_at,"%Y-%m-%d %H:%M:%S") tz_count = 0 hour_offset = "" minute_offset = "" for tz_offset in users.tz_offset: tz_count +=1 if tz_count <= 3: hour_offset += tz_offset elif tz_count <= 5: minute_offset +=tz_offset stop_at= stop_temp + relativedelta(hours=int(hour_offset)) if (stop_at >= date_start) and (stop_at <= date_stop): session_ids.append(sessions.id) if len(warehouse_ids) == 1: rml += """ <tr> <td> """ elif no_total % 2 == 0: rml += """<td>""" else: rml += """ <tr> <td> """ if warehousebtc.color: rml += """ <blockTable colWidths="210" style="Table3"> """ if not warehousebtc.color: rml += """ <blockTable colWidths="210" style="Table3_Normal"> """ rml += """ <tr> </tr> <tr> <td> <blockTable rowHeights="38" colWidths="198" style="Table3""" + to_xml(str(warehousebtc.color.name)) + """"> <tr> <td> <para style="P15_CENTER_2">"""+ to_xml(str(warehousebtc.name)) + """</para> </td> </tr> </blockTable> <blockTable colWidths="198" style="Table1_lines"> <tr> <td> <para style="P15">TGL: """+ to_xml(str(format(date_end,'%d-%B-%y')))+"""</para> </td> </tr> </blockTable> <blockTable rowHeights="17" colWidths="198" style="Table3""" + to_xml(str(warehousebtc.color.name)) + """"> <tr> <td background="pink"> <para style="P15_CENTER">SETORAN</para> </td> </tr> </blockTable> <blockTable colWidths="198" style="Table1_lines"> <tr> <td> """ total_card = 0.0 if not session_ids: rml +=""" <para style="P15">-</para> """ total_amount = 0.0 for session in session_obj.browse(cr,uid,session_ids): for bank in session.statement_ids: if bank.journal_id.type == 'bank': total_card +=bank.balance_end if session.cashier_deposit_ids: for cashier in session.cashier_deposit_ids: total_amount += cashier.amount_total rml += """ <para style="P15">""" + rml_parser.formatLang(total_amount+0, currency_obj=company.currency_id) + """</para> """ if session_ids: sessions = session_obj.browse(cr,uid,session_ids[0]) rml += """ </td> </tr> </blockTable> """ rml += """ <blockTable rowHeights="17" colWidths="198" style="Table3""" + to_xml(str(warehousebtc.color.name)) + """"> <tr> <td background="pink"> <para style="P15_CENTER">PENGELUARAN</para> </td> </tr> </blockTable> <blockTable colWidths="198" style="Table1_lines"> <tr> <td background="pink"> <para style="P15_W">Table</para> </td> </tr> </blockTable> <blockTable colWidths="198" style="Table1_lines"> <tr> <td background="pink"> <para style="P15_W">Table</para> </td> </tr> </blockTable> <blockTable colWidths="80,118" style="Table1_lines"> <tr> <td> <para style="P15">MAITRI</para> </td> <td> <para style="P15_RIGHT"></para> <para style="P15_RIGHT">""" + rml_parser.formatLang(total_amount+0, currency_obj=company.currency_id) +"""</para> </td> </tr> </blockTable> <blockTable colWidths="80,118" style="Table1_lines"> <tr> <td> <para style="P15">KURS :""" + rml_parser.formatLang(currency_amount,) +"""</para> </td> <td> <para style="P15_RIGHT">""" + rml_parser.formatLang(total_amount*currency_amount, currency_obj=warehousebtc.currency_id) +"""</para> </td> </tr> </blockTable> <blockTable colWidths="80,5,110" style="Table3_LINE2"> <tr> <td> <para style="P15"></para> </td> <td> <para style="P15"></para> </td> <td> <para style="P15_CENTER"></para> </td> </tr> </blockTable> </td> </tr> </blockTable> <spacer length="0.5cm"/>""" rml += """</td>""" if len(warehouse_ids) == 1: rml += """<td></td>""" rml += """ </tr> """ elif ( (no_total % 2 == 1 ) and (len(warehouse_ids) == no_total)): rml += """<td></td>""" rml += """ </tr> """ elif no_total % 2 == 0: rml += """ </tr> """ else: if len(warehouse_ids) == no_total: rml += """ </tr> """ no_total += 1 # Normal transaction for warehouse in wh_obj.browse(cr,uid,warehouse_ids): currency_amount = warehouse.currency_id.rate_silent location_id = warehouse.lot_stock_id.id results = [] total_bank = 0.0 if warehouse.is_split: date_start_day = datetime.strptime(datas['form']['date_end']+ ' 00:00:00',"%Y-%m-%d %H:%M:%S") date_stop_day = datetime.strptime(datas['form']['date_end']+ ' 17:59:59',"%Y-%m-%d %H:%M:%S") date_start = datetime.strptime(datas['form']['date_end']+ ' 18:00:00',"%Y-%m-%d %H:%M:%S") date_stop = datetime.strptime(datas['form']['date_end']+ ' 23:59:59',"%Y-%m-%d %H:%M:%S") sessions_ids = session_obj.search(cr,uid,[('stock_location_rel','=',location_id),('stop_at','!=',False)]) session_ids = [] session_day_ids = [] for sessions in session_obj.browse(cr,uid,sessions_ids): stop_temp=datetime.strptime(sessions.stop_at,"%Y-%m-%d %H:%M:%S") tz_count = 0 hour_offset = "" minute_offset = "" for tz_offset in users.tz_offset: tz_count +=1 if tz_count <= 3: hour_offset += tz_offset elif tz_count <= 5: minute_offset +=tz_offset stop_at= stop_temp + relativedelta(hours=int(hour_offset)) if (stop_at >= date_start) and (stop_at <= date_stop): session_ids.append(sessions.id) if (stop_at >= date_start_day) and (stop_at <= date_stop_day): session_day_ids.append(sessions.id) if not warehouse.is_split: session_ids = session_obj.search(cr,uid,[('stop_at','>=',datas['form']['date_end']+ ' 00:00:00'),('stop_at','<=',datas['form']['date_end']+ ' 23:59:59'),('stock_location_rel','=',location_id)]) if len(warehouse_ids) == 1: rml += """ <tr> <td> """ elif no_total % 2 == 0: rml += """<td>""" else: rml += """ <tr> <td> """ if warehouse.color: rml += """ <blockTable colWidths="210" style="Table3"> """ if not warehouse.color: rml += """ <blockTable colWidths="210" style="Table3_Normal"> """ rml += """ <tr> </tr> <tr> <td> <blockTable rowHeights="38" colWidths="198" style="Table3""" + to_xml(str(warehouse.color.name)) + """"> <tr> <td> <para style="P15_CENTER_2">"""+ to_xml(str(warehouse.name)) + """</para> </td> </tr> </blockTable> <blockTable colWidths="198" style="Table1_lines"> <tr> <td> <para style="P15">TGL: """+ to_xml(str(format(date_end,'%d-%B-%y')))+"""</para> </td> </tr> </blockTable> <blockTable rowHeights="17" colWidths="198" style="Table3""" + to_xml(str(warehouse.color.name)) + """"> <tr> <td background="pink"> <para style="P15_CENTER">SETORAN</para> </td> </tr> </blockTable> <blockTable colWidths="198" style="Table1_lines"> <tr> <td> """ total_card = 0.0 # if not session_ids: # rml +=""" # <para style="P15">-</para> # """ total_amount = 0.0 for session in session_obj.browse(cr,uid,session_ids): for bank in session.statement_ids: if bank.journal_id.type == 'bank': total_card +=bank.balance_end if session.cashier_deposit_ids: for cashier in session.cashier_deposit_ids: total_amount += cashier.amount_total rml += """ <para style="P15">""" + rml_parser.formatLang(total_amount+0, currency_obj=company.currency_id) + """</para> """ # if warehouse.is_split: if session_ids: sessions = session_obj.browse(cr,uid,session_ids[0]) if warehouse.is_split: rml += """ </td> </tr> </blockTable> <blockTable rowHeights="17" colWidths="198" style="Table3""" + to_xml(str(warehouse.color.name)) + """"> <tr> <td background="pink"> <para style="P15_CENTER">CC and DC (Siang)</para> </td> </tr> </blockTable> <blockTable colWidths="100,98" style="Table1_lines"> <tr> <td> """ if not session_day_ids: rml +=""" <para style="P15">-</para> """ session_list_day = [] bank_day_ids = [] for session in session_obj.browse(cr,uid,session_day_ids): session_list_day.append(session.id) if len(session_list_day) == 1: cr.execute(""" SELECT sum(abs.balance_end), aj.name from account_bank_statement abs inner join account_journal aj on abs.journal_id = aj.id where pos_session_id = %s and aj.type != 'cash' group by aj.name; """ % (tuple(session_list_day)[0],)) bank_ids = cr.fetchall() if len(session_list_day) > 1: cr.execute(""" SELECT sum(abs.balance_end), aj.name from account_bank_statement abs inner join account_journal aj on abs.journal_id = aj.id where pos_session_id in %s and aj.type != 'cash' group by aj.name; """ % (tuple(session_list_day),)) bank_ids = cr.fetchall() if bank_ids: for edukits_bank in bank_ids: rml +=""" <para style="P15">""" + to_xml(str(edukits_bank[1])) + """</para> """ rml +=""" </td> <td> """ if not session_day_ids: rml +=""" <para style="P15">-</para> """ if bank_ids: for edukits_bank in bank_ids: total_bank_amount = 0 if edukits_bank[0]: total_bank += edukits_bank[0] total_bank_amount = edukits_bank[0] rml +=""" <para style="P15">""" + rml_parser.formatLang(total_bank_amount,currency_obj=company.currency_id) + """</para> """ #normal transaction rml += """ </td> </tr> </blockTable> <blockTable rowHeights="17" colWidths="198" style="Table3""" + to_xml(str(warehouse.color.name)) + """"> <tr> <td background="pink"> <para style="P15_CENTER">CC and DC</para> </td> </tr> </blockTable> <blockTable colWidths="100,98" style="Table1_lines"> <tr> <td> """ if not session_ids: rml +=""" <para style="P15">-</para> """ session_list = [] bank_ids = [] for session in session_obj.browse(cr,uid,session_ids): session_list.append(session.id) # for bank in session.statement_ids: # if bank.journal_id.type == 'bank': # rml +=""" # <para style="P15">""" + to_xml(str(bank.journal_id.name)) + """</para> # """ if len(session_list) == 1: cr.execute(""" SELECT sum(abs.balance_end), aj.name from account_bank_statement abs inner join account_journal aj on abs.journal_id = aj.id where pos_session_id = %s and aj.type != 'cash' group by aj.name; """ % (tuple(session_list)[0],)) bank_ids = cr.fetchall() if len(session_list) > 1: cr.execute(""" SELECT sum(abs.balance_end), aj.name from account_bank_statement abs inner join account_journal aj on abs.journal_id = aj.id where pos_session_id in %s and aj.type != 'cash' group by aj.name; """ % (tuple(session_list),)) bank_ids = cr.fetchall() if bank_ids: for edukits_bank in bank_ids: rml +=""" <para style="P15">""" + to_xml(str(edukits_bank[1])) + """</para> """ rml +=""" </td> <td> """ if not session_ids: rml +=""" <para style="P15">-</para> """ if bank_ids: for edukits_bank in bank_ids: total_bank_amount = 0 if edukits_bank[0]: total_bank_amount = edukits_bank[0] total_bank += edukits_bank[0] rml +=""" <para style="P15">""" + rml_parser.formatLang(total_bank_amount+0,currency_obj=company.currency_id) + """</para> """ rml +=""" </td> </tr> </blockTable> <blockTable rowHeights="17" colWidths="198" style="Table3""" + to_xml(str(warehouse.color.name)) + """"> <tr> <td background="pink"> <para style="P15_CENTER">PENGELUARAN</para> </td> </tr> </blockTable> <blockTable colWidths="198" style="Table1_lines"> <tr> <td background="pink"> <para style="P15_W">Table</para> </td> </tr> </blockTable> <blockTable colWidths="198" style="Table1_lines"> <tr> <td background="pink"> <para style="P15_W">Table</para> </td> </tr> </blockTable> <blockTable colWidths="80,118" style="Table1_lines"> <tr> <td> <para style="P15">MAITRI</para> </td> <td> <para style="P15_RIGHT"></para> <para style="P15_RIGHT">""" + rml_parser.formatLang(total_amount + total_bank+0, currency_obj=company.currency_id) +"""</para> </td> </tr> </blockTable> <blockTable colWidths="80,118" style="Table1_lines"> <tr> <td> <para style="P15">KURS :""" + rml_parser.formatLang(currency_amount,) +"""</para> </td> <td> <para style="P15_RIGHT">""" + rml_parser.formatLang(total_amount*currency_amount, currency_obj=warehouse.currency_id) +"""</para> </td> </tr> </blockTable> <blockTable colWidths="80,5,110" style="Table3_LINE2"> <tr> <td> <para style="P15"></para> </td> <td> <para style="P15"></para> </td> <td> <para style="P15_CENTER"></para> </td> </tr> </blockTable> </td> </tr> </blockTable> <spacer length="0.5cm"/>""" rml += """ </td> """ if center: if len(warehouse_ids) == 1: rml += """<td></td>""" rml += """ </tr> """ elif ( (no_total % 2 == 1 ) and (len(warehouse_ids)+1 == no_total)): rml += """<td></td>""" rml += """ </tr> """ elif no_total % 2 == 0: rml += """ </tr> """ else: if len(warehouse_ids)+1 == no_total: rml += """ </tr> """ else: if len(warehouse_ids) == 1: rml += """<td></td>""" rml += """ </tr> """ elif ( (no_total % 2 == 1 ) and (len(warehouse_ids) == no_total)): rml += """<td></td>""" rml += """ </tr> """ elif no_total % 2 == 0: rml += """ </tr> """ else: if len(warehouse_ids) == no_total: rml += """ </tr> """ no_total += 1 rml += """ </blockTable> </story> </document>""" date_cur = time.strftime('%Y-%m-%d %H:%M:%S') return rml
def create_xml(self, cr, uid, ids, datas, context=None): registry = openerp.registry(cr.dbname) obj_emp = registry['hr.employee'] emp_ids = datas['active_ids'] start_date = datetime.strptime(datas['form']['init_date'], '%Y-%m-%d') end_date = datetime.strptime(datas['form']['end_date'], '%Y-%m-%d') first_monday = start_date - relativedelta(days=start_date.date().weekday()) last_monday = end_date + relativedelta(days=7 - end_date.date().weekday()) if last_monday < first_monday: first_monday, last_monday = last_monday, first_monday rpt_obj = obj_emp rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context) header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),registry['res.users'].browse(cr,uid,uid).company_id.name) user_xml = [] for employee_id in emp_ids: emp = obj_emp.read(cr, uid, [employee_id], ['id', 'name'])[0] monday, n_monday = first_monday, first_monday + one_week stop, week_xml = False, [] user_repr = ''' <user> <name>%s</name> %%s </user> ''' % tools.ustr(toxml(emp['name'])) while monday != last_monday: #### Work hour calculation sql = ''' select action, att.name from hr_employee as emp inner join hr_attendance as att on emp.id = att.employee_id where att.name between %s and %s and emp.id = %s order by att.name ''' for idx in range(7): cr.execute(sql, (monday.strftime('%Y-%m-%d %H:%M:%S'), (monday + relativedelta(days=idx+1)).strftime('%Y-%m-%d %H:%M:%S'), employee_id)) attendances = cr.dictfetchall() week_wh = {} # Fake sign ins/outs at week ends, to take attendances across week ends into account # XXX this is wrong for the first sign-in ever and the last sign out to this date if attendances and attendances[0]['action'] == 'sign_out': attendances.insert(0, {'name': monday.strftime('%Y-%m-%d %H:%M:%S'), 'action': 'sign_in'}) if attendances and attendances[-1]['action'] == 'sign_in': attendances.append({'name': n_monday.strftime('%Y-%m-%d %H:%M:%S'), 'action': 'sign_out'}) # sum up the attendances' durations ldt = None for att in attendances: dt = datetime.strptime(att['name'], '%Y-%m-%d %H:%M:%S') if ldt and att['action'] == 'sign_out': week_wh[ldt.date().weekday()] = week_wh.get(ldt.date().weekday(), 0) + (float((dt - ldt).seconds)/3600) else: ldt = dt # Week xml representation week_repr = ['<week>', '<weekstart>%s</weekstart>' % monday.strftime('%Y-%m-%d'), '<weekend>%s</weekend>' % (n_monday - relativedelta(days=1)).strftime('%Y-%m-%d')] for idx in range(7): week_repr.append('<%s>' % num2day[idx]) if idx in week_wh: week_repr.append('<workhours>%sh%02d</workhours>' % to_hour(week_wh[idx])) week_repr.append('</%s>' % num2day[idx]) week_repr.append('<total>') week_repr.append('<worked>%sh%02d</worked>' % to_hour(reduce(lambda x,y:x+y, week_wh.values(), 0))) week_repr.append('</total>') week_repr.append('</week>') week_xml.append('\n'.join(week_repr)) monday, n_monday = n_monday, n_monday + one_week user_xml.append(user_repr % '\n'.join(week_xml)) xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s <title>%s</title> %s </report> ''' % (header_xml,_('Attendances by Week'),'\n'.join(user_xml)) xml = tools.ustr(xml).encode('utf8') return self.post_process_xml_data(cr, uid, xml, context)
def create_xml(self, cr, uid, ids, data, context): registry = openerp.registry(cr.dbname) obj_dept = registry['hr.department'] obj_emp = registry['hr.employee'] depts=[] emp_id={} rpt_obj = registry['hr.holidays'] rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context) cr.execute("SELECT name FROM res_company") res=cr.fetchone()[0] date_xml=[] date_today=time.strftime('%Y-%m-%d %H:%M:%S') date_xml +=['<res name="%s" today="%s" />' % (res,date_today)] cr.execute("SELECT id, name, color_name FROM hr_holidays_status ORDER BY id") legend=cr.fetchall() today=datetime.datetime.today() first_date=data['form']['date_from'] som = strToDate(first_date) eom = som+datetime.timedelta(59) day_diff=eom-som name = '' if len(data['form'].get('emp', ())) == 1: name = obj_emp.read(cr, uid, data['form']['emp'][0], ['name'])['name'] if data['form']['holiday_type']!='both': type=data['form']['holiday_type'] if data['form']['holiday_type']=='Confirmed': holiday_type=('confirm') else: holiday_type=('validate') else: type="Confirmed and Approved" holiday_type=('confirm','validate') date_xml.append('<from>%s</from>\n'% (str(rml_obj.formatLang(som.strftime("%Y-%m-%d"),date=True)))) date_xml.append('<to>%s</to>\n' %(str(rml_obj.formatLang(eom.strftime("%Y-%m-%d"),date=True)))) date_xml.append('<type>%s</type>'%(type)) date_xml.append('<name>%s</name>'%(name)) # date_xml=[] for l in range(0,len(legend)): date_xml += ['<legend row="%d" id="%d" name="%s" color="%s" />' % (l+1,legend[l][0],_(legend[l][1]),legend[l][2])] date_xml += ['<date month="%s" year="%d" />' % (som.strftime('%B'), som.year),'<days>'] cell=1 if day_diff.days>=30: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)] else: if day_diff.days>=(lengthmonth(som.year, som.month)-som.day): date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, lengthmonth(som.year, som.month)+1)] else: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')),x-som.day+1) for x in range(som.day, eom.day+1)] cell=x-som.day+1 day_diff1=day_diff.days-cell+1 width_dict={} month_dict={} i=1 j=1 year=som.year month=som.month month_dict[j]=som.strftime('%B') width_dict[j]=cell while day_diff1>0: if month+i<=12: if day_diff1 > lengthmonth(year,i+month): # Not on 30 else you have problems when entering 01-01-2009 for example som1=datetime.date(year,month+i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(year,i+month)+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x else: som1=datetime.date(year,month+i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x day_diff1=day_diff1-x else: years=year+1 year=years month=0 i=1 if day_diff1>=30: som1=datetime.date(years,i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(years,i)+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x else: som1=datetime.date(years,i,1) i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, eom.day+1)] cell=cell+x width_dict[j]=x day_diff1=day_diff1-x date_xml.append('</days>') date_xml.append('<cols>3.5cm%s,0.4cm</cols>\n' % (',0.4cm' * (60))) date_xml = ''.join(date_xml) st='<cols_months>3.5cm' for m in range(1,len(width_dict)+1): st+=',' + str(0.4 *width_dict[m])+'cm' st+=',0.4cm</cols_months>\n' months_xml =['<months number="%d" name="%s"/>' % (x, _(month_dict[x])) for x in range(1,len(month_dict)+1) ] months_xml.append(st) emp_xml='' row_id=1 if data['model']=='hr.employee': for id in data['form']['emp']: items = obj_emp.read(cr, uid, id, ['id','name']) emp_xml += emp_create_xml(self, cr, uid, 0, holiday_type, row_id, items['id'], items['name'], som, eom) row_id = row_id +1 elif data['model']=='ir.ui.menu': for id in data['form']['depts']: dept = obj_dept.browse(cr, uid, id, context=context) cr.execute("""SELECT id FROM hr_employee \ WHERE department_id = %s""", (id,)) emp_ids = [x[0] for x in cr.fetchall()] if emp_ids==[]: continue dept_done=0 for item in obj_emp.read(cr, uid, emp_ids, ['id', 'name']): if dept_done==0: emp_xml += emp_create_xml(self, cr, uid, 1, holiday_type, row_id, dept.id, dept.name, som, eom) row_id = row_id +1 dept_done=1 emp_xml += emp_create_xml(self, cr, uid, 0, holiday_type, row_id, item['id'], item['name'], som, eom) row_id = row_id +1 header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),to_xml(registry['res.users'].browse(cr,uid,uid).company_id.name)) # Computing the xml xml='''<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s %s </report> ''' % (header_xml,months_xml,date_xml, ustr(emp_xml)) return xml
def create(self, cr, uid, ids, datas, context): _divide_columns_for_matrix = 0.7 _display_ans_in_rows = 5 _pageSize = ('29.7cm', '21.1cm') if datas.has_key('form') and datas['form'].get('orientation', '') == 'vertical': if datas['form'].get('paper_size', '') == 'letter': _pageSize = ('21.6cm', '27.9cm') elif datas['form'].get('paper_size', '') == 'legal': _pageSize = ('21.6cm', '35.6cm') elif datas['form'].get('paper_size', '') == 'a4': _pageSize = ('21.1cm', '29.7cm') elif datas.has_key('form') and datas['form'].get( 'orientation', False) == 'horizontal': if datas['form'].get('paper_size', '') == 'letter': _pageSize = ('27.9cm', '21.6cm') elif datas['form'].get('paper_size', '') == 'legal': _pageSize = ('35.6cm', '21.6cm') elif datas['form'].get('paper_size') == 'a4': _pageSize = ('29.7cm', '21.1cm') _frame_width = tools.ustr(_pageSize[0]) _frame_height = tools.ustr( float(_pageSize[1].replace('cm', '')) - float(1.90)) + 'cm' _tbl_widths = tools.ustr( float(_pageSize[0].replace('cm', '')) - float(2.10)) + 'cm' rml = """<document filename="Survey Answer Report.pdf"> <template pageSize="(""" + _pageSize[0] + """,""" + _pageSize[ 1] + """)" title='Survey Answer' author="OpenERP S.A.([email protected])" allowSplitting="20" > <pageTemplate id="first"> <frame id="first" x1="0.0cm" y1="1.0cm" width='""" + _frame_width + """' height='""" + _frame_height + """'/> <pageGraphics> <lineMode width="1.0"/> <lines>1.0cm """ + tools.ustr( float(_pageSize[1].replace('cm', '')) - float(1.00)) + 'cm' + """ """ + tools.ustr( float(_pageSize[0].replace('cm', '')) - float(1.00)) + 'cm' + """ """ + tools.ustr( float(_pageSize[1].replace('cm', '')) - float(1.00)) + 'cm' + """</lines> <lines>1.0cm """ + tools.ustr( float(_pageSize[1].replace('cm', '')) - float(1.00) ) + 'cm' + """ 1.0cm 1.00cm</lines> <lines>""" + tools.ustr( float(_pageSize[0].replace('cm', '')) - float(1.00)) + 'cm' + """ """ + tools.ustr( float(_pageSize[1].replace('cm', '')) - float(1.00)) + 'cm' + """ """ + tools.ustr( float(_pageSize[0].replace('cm', '')) - float(1.00)) + 'cm' + """ 1.00cm</lines> <lines>1.0cm 1.00cm """ + tools.ustr( float(_pageSize[0].replace('cm', '')) - float(1.00) ) + 'cm' + """ 1.00cm</lines>""" if datas.has_key('form') and datas['form']['page_number']: rml += """ <fill color="gray"/> <setFont name="Helvetica" size="10"/> <<drawRightString x='""" + tools.ustr( float(_pageSize[0].replace('cm', '')) - float(1.00)) + 'cm' + """' y="0.6cm">""" + _( 'Page : ') + """<pageNumber/> </drawRightString>""" rml += """</pageGraphics> </pageTemplate> </template> <stylesheet> <blockTableStyle id="tbl_white"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="tbl_gainsboro"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/> <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="ans_tbl_white"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="ans_tbl_gainsboro"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <blockBackground colorName="gainsboro" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="simple_table"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6"/> </blockTableStyle> <blockTableStyle id="note_table"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table2"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table3"> <blockAlignment value="LEFT"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="1,0" stop="2,-1"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="Table4"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/> </blockTableStyle> <blockTableStyle id="Table5"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#8f8f8f" start="0,-1" stop="1,-1"/> </blockTableStyle> <blockTableStyle id="Table41"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="Table51"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#e6e6e6" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEBEFORE" colorName="#777777" start="0,0" stop="-1,-1"/> <lineStyle kind="LINEAFTER" colorName="#777777" start="0,0" stop="-1,-1"/> </blockTableStyle> <blockTableStyle id="Table_heading"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> </blockTableStyle> <blockTableStyle id="title_tbl"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/> <blockBackground colorName="black" start="0,0" stop="-1,-1"/> <blockTextColor colorName="white" start="0,0" stop="0,0"/> </blockTableStyle> <blockTableStyle id="page_tbl"> <blockAlignment value="LEFT"/> <blockValign value="TOP"/> <lineStyle kind="LINEBELOW" colorName="#000000" start="0,-1" stop="1,-1"/> <blockBackground colorName="gray" start="0,0" stop="-1,-1"/> <blockTextColor colorName="white" start="0,0" stop="0,0"/> </blockTableStyle> <initialize> <paraStyle name="all" alignment="justify"/> </initialize> <paraStyle name="title" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/> <paraStyle name="answer_right" alignment="RIGHT" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="Standard1" fontName="helvetica-bold" alignment="RIGHT" fontSize="09.0"/> <paraStyle name="Standard" alignment="LEFT" fontName="Helvetica-Bold" fontSize="11.0"/> <paraStyle name="header1" fontName="Helvetica" fontSize="11.0"/> <paraStyle name="response" fontName="Helvetica-oblique" fontSize="9.5"/> <paraStyle name="page" fontName="helvetica" fontSize="11.0" leftIndent="0.0"/> <paraStyle name="question" fontName="helvetica-boldoblique" fontSize="10.0" leftIndent="3.0"/> <paraStyle name="answer_bold" fontName="Helvetica-Bold" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="answer" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="answer1" fontName="helvetica" fontSize="09.0" leftIndent="2.0"/> <paraStyle name="Title" fontName="helvetica" fontSize="20.0" leading="15" spaceBefore="6.0" spaceAfter="6.0" alignment="CENTER"/> <paraStyle name="P2" fontName="Helvetica" fontSize="14.0" leading="15" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="comment" fontName="Helvetica" fontSize="14.0" leading="50" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="P1" fontName="Helvetica" fontSize="9.0" leading="12" spaceBefore="0.0" spaceAfter="1.0"/> <paraStyle name="terp_tblheader_Details" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_default_9" fontName="Helvetica" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_default_9_Bold" fontName="Helvetica-Bold" fontSize="9.0" leading="11" alignment="LEFT" spaceBefore="0.0" spaceAfter="0.0"/> <paraStyle name="terp_tblheader_General_Centre_simple" fontName="Helvetica" fontSize="10.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_General_Centre" fontName="Helvetica-Bold" fontSize="10.0" leading="10" alignment="LEFT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_General_right_simple" fontName="Helvetica" fontSize="10.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="terp_tblheader_General_right" fontName="Helvetica-Bold" fontSize="10.0" leading="10" alignment="RIGHT" spaceBefore="6.0" spaceAfter="6.0"/> <paraStyle name="descriptive_text" fontName="helvetica-bold" fontSize="18.0" leftIndent="0.0" textColor="white"/> <paraStyle name="descriptive_text_heading" fontName="helvetica-bold" fontSize="18.0" alignment="RIGHT" leftIndent="0.0" textColor="white"/> </stylesheet> <images/> <story>""" surv_resp_obj = pooler.get_pool(cr.dbname).get('survey.response') rml_obj = report_sxw.rml_parse(cr, uid, surv_resp_obj._name, context) if datas.has_key('form') and datas['form'].has_key('response_ids'): response_id = datas['form']['response_ids'] elif context.has_key('response_id') and context['response_id']: response_id = [int(context['response_id'][0])] else: response_id = surv_resp_obj.search(cr, uid, [('survey_id', 'in', ids)]) surv_resp_line_obj = pooler.get_pool( cr.dbname).get('survey.response.line') surv_obj = pooler.get_pool(cr.dbname).get('survey') for response in surv_resp_obj.browse(cr, uid, response_id): for survey in surv_obj.browse(cr, uid, [response.survey_id.id]): tbl_width = float(_tbl_widths.replace('cm', '')) colwidth = "2.5cm,4.8cm," + str(tbl_width - 15.0) + "cm,3.2cm,4.5cm" resp_create = tools.ustr( time.strftime( '%d-%m-%Y %I:%M:%S %p', time.strptime( response.date_create.split('.')[0], '%Y-%m-%d %H:%M:%S'))) rml += """<blockTable colWidths='""" + colwidth + """' style="Table_heading"> <tr> <td><para style="terp_default_9_Bold">""" + _( 'Print Date : ') + """</para></td> <td><para style="terp_default_9">""" + to_xml( rml_obj.formatLang( time.strftime("%Y-%m-%d %H:%M:%S"), date_time=True)) + """</para></td> <td><para style="terp_default_9"></para></td> <td><para style="terp_default_9_Bold">""" + _( 'Answered by : ') + """</para></td> <td><para style="terp_default_9">""" + to_xml( response.user_id.login or '') + """</para></td> </tr> <tr> <td><para style="terp_default_9"></para></td> <td><para style="terp_default_9"></para></td> <td><para style="terp_default_9"></para></td> <td><para style="terp_default_9_Bold">""" + _( 'Answer Date : ') + """</para></td> <td><para style="terp_default_9">""" + to_xml( resp_create) + """</para></td> </tr> </blockTable><para style="P2"></para>""" status = _("Not Finished") if response.state == "done": status = _("Finished") colwidth = str(tbl_width - 7) + "cm," colwidth += "7cm" rml += """<blockTable colWidths='""" + str( colwidth) + """' style="title_tbl"> <tr> <td><para style="title">""" + to_xml( tools.ustr(survey.title) ) + """</para><para style="P2"><font></font></para></td> <td><para style="descriptive_text_heading">""" + _( 'Status :- ' ) + to_xml( tools.ustr(status) ) + """</para><para style="P2"><font></font></para></td> </tr> </blockTable>""" if survey.note: rml += """<blockTable colWidths='""" + _tbl_widths + """' style="note_table"> <tr><td><para style="response">""" + to_xml( tools.ustr(survey.note or '') ) + """</para><para style="P2"><font></font></para></td></tr> </blockTable>""" for page in survey.page_ids: rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="page_tbl"> <tr><td><para style="page">""" + _( 'Page :- ') + to_xml(tools.ustr( page.title or '')) + """</para></td></tr> </blockTable>""" if page.note: rml += """<para style="P2"></para> <blockTable colWidths='""" + str( _tbl_widths) + """' style="note_table"> <tr><td><para style="response">""" + to_xml( tools.ustr(page.note or '')) + """</para></td></tr> </blockTable>""" for que in page.question_ids: rml += """<para style="P2"></para> <blockTable colWidths='""" + str( _tbl_widths) + """' style="Table5"> <tr><td><para style="question">""" + to_xml( to_xml(que.question)) + """</para></td></tr> </blockTable>""" answer = surv_resp_line_obj.browse( cr, uid, surv_resp_line_obj.search( cr, uid, [('question_id', '=', que.id), ('response_id', '=', response.id)])) if que.type in ['descriptive_text']: rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr><td> <para style="response">""" + to_xml( tools.ustr(que.descriptive_text) ) + """</para></td> </tr> </blockTable>""" elif que.type in ['table']: if len(answer) and answer[0].state == "done": col_heading = pooler.get_pool( cr.dbname).get('survey.tbl.column.heading') cols_widhts = [] tbl_width = float(_tbl_widths.replace( 'cm', '')) for i in range(0, len(que.column_heading_ids)): cols_widhts.append( tbl_width / float(len(que.column_heading_ids))) colWidths = "cm,".join( map(tools.ustr, cols_widhts)) colWidths = colWidths + 'cm' matrix_ans = [] rml += """<para style="P2"></para><blockTable colWidths=" """ + str( colWidths) + """ " style="Table41"><tr>""" for col in que.column_heading_ids: if col.title not in matrix_ans: matrix_ans.append(col.title) rml += """<td> <para style="terp_tblheader_Details">""" + to_xml( tools.ustr(col.title) ) + """</para></td>""" rml += """</tr></blockTable>""" i = 0 for row in range(0, que.no_of_rows): if i % 2 != 0: style = 'tbl_white' else: style = 'tbl_gainsboro' i += 1 rml += """<blockTable colWidths=" """ + str( colWidths ) + """ " style='""" + style + """'><tr>""" table_data = col_heading.browse( cr, uid, col_heading.search( cr, uid, [('response_table_id', '=', answer[0].id), ('name', '=', row)])) for column in matrix_ans: value = False for col in table_data: if column == col.column_id.title: value = col.value if value: rml += """<td> <para style="terp_default_9">""" + to_xml( tools.ustr(value) ) + """</para></td>""" else: rml += """<td><para style="terp_default_9"><font color ="white"> </font></para></td>""" rml += """</tr></blockTable>""" else: rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr><td> <para style="response">""" + _( 'No Answer') + """</para></td> </tr> </blockTable>""" elif que.type in [ 'multiple_choice_only_one_ans', 'multiple_choice_multiple_ans' ]: if len(answer) and answer[0].state == "done": ans_list = [] for ans in answer[0].response_answer_ids: ans_list.append( to_xml(tools.ustr( ans.answer_id.answer))) answer_choice = [] for ans in que['answer_choice_ids']: answer_choice.append( to_xml(tools.ustr((ans.answer)))) def divide_list(lst, n): return [lst[i::n] for i in range(n)] divide_list = divide_list( answer_choice, _display_ans_in_rows) for lst in divide_list: if que.type == 'multiple_choice_multiple_ans': if len(lst) <> 0 and len(lst) <> int( round( float(len(answer_choice)) / _display_ans_in_rows, 0)): lst.append('') if not lst: del divide_list[divide_list.index(lst ):] for divide in divide_list: a = _divide_columns_for_matrix * len( divide) b = float(_tbl_widths.replace( 'cm', '')) - float(a) cols_widhts = [] for div in range(0, len(divide)): cols_widhts.append( float(a / len(divide))) cols_widhts.append( float(b / len(divide))) colWidths = "cm,".join( map(tools.ustr, cols_widhts)) colWidths = colWidths + 'cm' rml += """<blockTable colWidths=" """ + colWidths + """ " style="simple_table"><tr>""" for div in range(0, len(divide)): if divide[div] != '': if que.type == 'multiple_choice_multiple_ans': if divide[div] in ans_list: rml += """<td><illustration><fill color="white"/> <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/> <fill color="gray"/> <rect x="0.2cm" y="-0.35cm" width="0.3 cm" height="0.3cm" fill="yes" stroke="no" round="0.1cm"/> </illustration></td> <td><para style="answer">""" + divide[ div] + """</para></td>""" else: rml += """<td><illustration> <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="no" stroke="yes" round="0.1cm"/> </illustration></td> <td><para style="answer">""" + divide[ div] + """</para></td>""" else: if divide[div] in ans_list: rml += """<td><illustration><fill color="white"/> <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes" round="0.1cm"/> <fill color="gray"/> <circle x="0.3cm" y="-0.18cm" radius="0.10 cm" fill="yes" stroke="no" round="0.1cm"/> </illustration></td> <td><para style="answer">""" + divide[ div] + """</para></td>""" else: rml += """<td> <illustration> <circle x="0.3cm" y="-0.18cm" radius="0.23 cm" fill="no" stroke="yes" round="0.1cm"/> </illustration> </td> <td><para style="answer">""" + divide[ div] + """</para></td>""" else: rml += """<td></td><td></td>""" rml += """</tr></blockTable>""" if que.is_comment_require and answer[0].comment: rml += """<blockTable colWidths='""" + str( _tbl_widths ) + """' style="simple_table"><tr> <td><para style="answer">""" + to_xml( tools.ustr(answer[0].comment) ) + """</para></td></tr></blockTable>""" else: rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr><td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in [ 'multiple_textboxes_diff_type', 'multiple_textboxes', 'date', 'date_and_time', 'numerical_textboxes', 'multiple_textboxes_diff_type' ]: if len(answer) and answer[0].state == "done": cols_widhts = [] cols_widhts.append( float(_tbl_widths.replace('cm', '')) / 2) cols_widhts.append( float(_tbl_widths.replace('cm', '')) / 2) colWidths = "cm,".join( map(tools.ustr, cols_widhts)) colWidths = tools.ustr(colWidths) + 'cm' answer_list = {} for ans in answer[0].response_answer_ids: answer_list[ ans.answer_id.answer] = ans.answer for que_ans in que['answer_choice_ids']: if que_ans.answer in answer_list: rml += """<blockTable colWidths='""" + str( colWidths ) + """' style="simple_table"> <tr> <td> <para style="response">""" + to_xml( tools.ustr(que_ans.answer) ) + """</para></td> <td> <para style="response">""" + to_xml( tools.ustr( answer_list[que_ans.answer]) ) + """</para></td></tr> </blockTable>""" else: rml += """<blockTable colWidths='""" + str( colWidths ) + """' style="simple_table"> <tr> <td> <para style="response">""" + to_xml( tools.ustr(que_ans.answer) ) + """</para></td> <td> <para style="response"></para></td></tr> </blockTable>""" else: rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in ['single_textbox']: if len(answer) and answer[0].state == "done": rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">""" + to_xml( tools.ustr(answer[0].single_text) ) + """</para></td></tr> </blockTable>""" else: rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in ['comment']: if len(answer) and answer[0].state == "done": rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">""" + to_xml( tools.ustr(answer[0].comment) ) + """</para></td></tr> </blockTable>""" else: rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr> <td> <para style="response">No Answer</para></td> </tr> </blockTable>""" elif que.type in [ 'matrix_of_choices_only_one_ans', 'matrix_of_choices_only_multi_ans', 'rating_scale', 'matrix_of_drop_down_menus' ]: if len(answer) and answer[0].state == "done": if que.type in [ 'matrix_of_choices_only_one_ans', 'rating_scale' ] and que.comment_column: pass cols_widhts = [] if len(que.column_heading_ids): cols_widhts.append( float(_tbl_widths.replace('cm', '')) / float(2.0)) for col in que.column_heading_ids: cols_widhts.append( float((float( _tbl_widths.replace('cm', '')) / float(2.0)) / len(que.column_heading_ids))) else: cols_widhts.append( float(_tbl_widths.replace('cm', ''))) tmp = 0.0 sum = 0.0 i = 0 if que.type in [ 'matrix_of_choices_only_one_ans', 'rating_scale' ] and que.comment_column: for col in cols_widhts: if i == 0: cols_widhts[ i] = cols_widhts[i] / 2.0 tmp = cols_widhts[i] sum += col i += 1 cols_widhts.append(round(tmp, 2)) colWidths = "cm,".join( map(tools.ustr, cols_widhts)) colWidths = colWidths + 'cm' matrix_ans = [ (0, ''), ] for col in que.column_heading_ids: if col.title not in matrix_ans: matrix_ans.append((col.id, col.title)) len_matrix = len(matrix_ans) if que.type in [ 'matrix_of_choices_only_one_ans', 'rating_scale' ] and que.comment_column: matrix_ans.append((0, que.column_name)) rml += """<blockTable colWidths=" """ + colWidths + """ " style="simple_table"><tr>""" for mat_col in range(0, len(matrix_ans)): rml += """<td><para style="response">""" + to_xml( tools.ustr(matrix_ans[mat_col] [1])) + """</para></td>""" rml += """</tr>""" rml += """</blockTable>""" i = 0 for ans in que.answer_choice_ids: if i % 2 != 0: style = 'ans_tbl_white' else: style = 'ans_tbl_gainsboro' i += 1 rml += """<blockTable colWidths=" """ + colWidths + """ " style='""" + style + """'> <tr><td><para style="response">""" + to_xml( tools.ustr( ans.answer)) + """</para></td>""" comment_value = "" for mat_col in range(1, len_matrix): value = """""" for res_ans in answer[ 0].response_answer_ids: if res_ans.answer_id.id == ans.id and res_ans.column_id.id == matrix_ans[ mat_col][0]: comment_value = to_xml( tools.ustr( res_ans.comment_field)) if que.type in [ 'matrix_of_drop_down_menus' ]: value = """<para style="response">""" + to_xml( tools.ustr( res_ans. value_choice) ) + """</para>""" elif que.type in [ 'matrix_of_choices_only_one_ans', 'rating_scale' ]: value = """<illustration><fill color="white"/> <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes"/> <fill color="gray"/> <circle x="0.3cm" y="-0.18cm" radius="0.10 cm" fill="yes" stroke="no"/> </illustration>""" elif que.type in [ 'matrix_of_choices_only_multi_ans' ]: value = """<illustration> <fill color="white"/> <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/> <fill color="gray"/> <rect x="0.2cm" y="-0.35cm" width="0.3 cm" height="0.3cm" fill="yes" stroke="no" round="0.1cm"/> </illustration>""" break else: if que.type in [ 'matrix_of_drop_down_menus' ]: value = """""" elif que.type in [ 'matrix_of_choices_only_one_ans', 'rating_scale' ]: value = """<illustration><fill color="white"/> <circle x="0.3cm" y="-0.18cm" radius="0.22 cm" fill="yes" stroke="yes" round="0.1cm"/> </illustration>""" elif que.type in [ 'matrix_of_choices_only_multi_ans' ]: value = """<illustration><fill color="white"/> <rect x="0.1cm" y="-0.45cm" width="0.5 cm" height="0.5cm" fill="yes" stroke="yes" round="0.1cm"/> </illustration>""" rml += """<td>""" + value + """</td>""" if que.type in [ 'matrix_of_choices_only_one_ans', 'rating_scale' ] and que.comment_column: if comment_value == 'False': comment_value = '' rml += """<td><para style="response">""" + to_xml( tools.ustr(comment_value) ) + """</para></td>""" rml += """</tr></blockTable>""" if que.is_comment_require: rml += """<blockTable colWidths='""" + str( _tbl_widths ) + """' style="simple_table"><tr> <td><para style="answer">""" + to_xml( tools.ustr(answer[0].comment or '') ) + """</para></td></tr></blockTable>""" else: rml += """<blockTable colWidths='""" + str( _tbl_widths) + """' style="simple_table"> <tr><td> <para style="response">No Answer</para></td> </tr> </blockTable>""" if datas.has_key( 'form') and not datas['form']['without_pagebreak']: rml += """<pageBreak/>""" elif not datas.has_key('form'): rml += """<pageBreak/>""" else: rml += """<para style="P2"><font></font></para>""" rml += """</story></document>""" report_type = datas.get('report_type', 'pdf') create_doc = self.generators[report_type] pdf = create_doc(rml, title=self.title) return (pdf, report_type)
def write_bc(self, cr, uid, ids, context): # siapkan format penulisan L,R or C def dikiri(length, kata): txtFormat = '' txtFormat = '{:<%d}' % length return txtFormat.format(kata) def dikanan(length, kata): txtFormat = '' txtFormat = '{:>%d}' % length return txtFormat.format(kata) def ditengah(length, kata, separator): if not separator: separator = " " txtFormat = '' txtFormat = '{:%s^%d}' % (separator, length) return txtFormat.format(kata) def diDiv(length, kata): kata = kata.split("\n") dived = [] for kt in kata: x0 = 0 x = len(kt) L = [] st = [] fs = [] while x > 0: st.append(x0 * length) x0 += 1 fs.append(x0 * length) x -= length for x, y in zip(st, fs): L.append(kt[x:y]) dived += L return dived def cekElem(arrDict): # input : arrDict = {'a':arrayA,'b':arrayB,'c':arrayC} # output : length array will same acording to the bigest length, append by " " kosong = arrDict['kosong'] arrDict.pop('kosong') L = 0 if len(arrDict.keys()) > 1: L = max(len(k) for k in arrDict.values()) for div in arrDict.keys(): while len(arrDict[div]) < L: arrDict[div].append(dikiri(kosong[div] - 1, " ")) return arrDict, L # PAPER LENGTH 95 chrs # grs separator 95chrs length separator = "-----------------------------------------------------------------------------------------------" for data in self.browse( cr, uid, ids, ): result = "" comp = data.company_id.name.upper() alamatC = ' '.join([ str(data.company_id.street or ''), str(data.company_id.street2 or ''), str(data.company_id.city or ''), str(data.company_id.state_id and data.company_id.state_id.name or ''), str(data.company_id.zip or ''), str(data.company_id.country_id and data.company_id.country_id.name or '') ]) phoneC = ' '.join([ data.company_id.phone and str("phone %s" % data.company_id.phone) or '', data.company_id.fax and str(", fax %s" % data.company_id.fax) or '' ]) if data.company_id.partner_id.npwp: phoneC = " ".join([phoneC, data.company_id.partner_id.npwp]) # Company header mainHeader = [ dikiri(95, comp), dikiri(95, alamatC), dikiri(95, phoneC), separator ] partner = data.partner_id.name almatkpd = ' '.join([ str(data.partner_id.street or ''), str(data.partner_id.street2 or ''), str(data.partner_id.city or '') ]) phkpd = ' '.join([ data.partner_id.phone or '', data.partner_id.fax and str(" fax %s" % data.partner_id.fax) or '' ]) # main title titles = [] hdL = [12, 22, 18, 40] tabs = 54 titles.append(ditengah(tabs, "PURCHASE ORDER", " ")) titles.append(" ".join([ dikiri(hdL[0], "No.Order :"), dikiri(hdL[1], "Order Date :"), dikiri(hdL[2], "Prepared By :"), dikiri(hdL[3], partner[:hdL[3]]) ])) titles.append(" ".join([ dikiri(hdL[0], data.name), dikiri(hdL[1], data.date_order), dikiri(hdL[2], data.validator.name), dikiri(hdL[3], almatkpd[:hdL[3]]) ])) if almatkpd[hdL[3]:]: titles.append(" ".join( [dikanan(tabs, " "), dikiri(hdL[3], almatkpd[hdL[3]:])])) titles.append(" ".join( [dikanan(tabs, " "), dikiri(tabs, phkpd[:hdL[3]])])) if phkpd[hdL[3]:]: titles.append(" ".join( [dikanan(tabs, " "), dikiri(tabs, phkpd[37:])])) # lines lines = [] # panjang karakter max tiap kolom, to joined by single space lgt = [22, 7, 8, 14, 18, 21] lineH = [ "Description", "Tax", "Disc (%)", "Qty", "Unit Price", "Net Price" ] # format header lines.append(separator) lines.append(' '.join([ dikiri(lgt[0], lineH[0]), dikiri(lgt[1], lineH[1]), dikiri(lgt[2], lineH[2]), dikanan(lgt[3], lineH[3]), dikanan(lgt[4], lineH[4]), dikanan(lgt[5], lineH[5]) ])) lines.append(separator) rp = str(data.currency_id.symbol) rml_parser = report_sxw.rml_parse(cr, uid, '', context=context) for line in data.order_line: taxes = [] for tx in line.taxes_id: amt = tx.amount or 0.0 if tx.type == 'percent': taxes.append(" ".join([str(amt * 100), "%"])) elif tx.type == 'fixed': taxes.append(" ".join([rp, str(amt)])) else: taxes.append(tx.name) taxes = ",".join(taxes) names = diDiv(lgt[0], line.name) # names = names.split("\n") # import pdb;pdb.set_trace() amt_price_unit = rml_parser.formatLang( line.price_unit, currency_obj=data.currency_id).replace(u'\xa0', u' ') amt_price_stot = rml_parser.formatLang( line.price_subtotal, currency_obj=data.currency_id).replace(u'\xa0', u' ') lines.append(' '.join([ dikiri(lgt[0], names[0]), dikiri(lgt[1], taxes[:lgt[1]]), dikiri(lgt[2], str(line.taxes_str)), dikanan( lgt[3], " ".join( [str(line.product_qty), line.product_uom.name])), dikanan(lgt[4], amt_price_unit), dikanan(lgt[5], amt_price_stot) ])) if len(names) > 1: names.remove(names[0]) for nm in names: lines.append(dikiri(lgt[0], nm)) # konstruk div for 3 cols footerkiri = [] Lf = {'1': tabs, '2': 3, '3': 19, '4': 17} if data.notes2: note = '\n'.join(["Terms & Condition :", data.notes2]) footerkiri += [dikiri(Lf['1'], x) for x in diDiv(tabs, note)] footerkanan1 = [ dikiri(Lf['3'], x) for x in [ "-------------------", "Total Without Taxes", "Taxes", "-------------------", "Total" ] ] amt_amount_untax = rml_parser.formatLang( data.amount_untaxed, currency_obj=data.currency_id).replace(u'\xa0', u' ') amt_amount_tax = rml_parser.formatLang( data.amount_tax, currency_obj=data.currency_id).replace(u'\xa0', u' ') amt_amount_tot = rml_parser.formatLang( data.amount_total, currency_obj=data.currency_id).replace(u'\xa0', u' ') footerkanan2 = [ dikanan(Lf['4'], x) for x in [ "-----------------", amt_amount_untax, amt_amount_tax, "-----------------", amt_amount_tot ] ] kosong = [] elem = {} elem.update({ '1': footerkiri, '2': kosong, '3': footerkanan1, '4': footerkanan2, 'kosong': Lf }) elem, L = cekElem(elem) L = max(len(k) for k in elem.values()) i = 0 footer = [] while i < L: all = [] for y in zip(x for x in elem.values()): all.append(y[0][i]) S = " ".join(all) footer.append(S) i += 1 # print("\n".join(footer)) ttd = [ separator, ditengah(tabs / 2, " Supplier ", " ") + ditengah(tabs / 2, " Hormat Kami, ", " "), "\n\n" + ditengah(tabs / 2, "( ________________ )", " ") + ditengah(tabs / 2, "( ________________ )", " ") ] result = '\n'.join(mainHeader + titles + lines + footer + ttd) self.write(cr, uid, data.id, {'barcode_data': result}) return True
def get_move_lines_counterparts(self, cr, uid, id, excluded_ids=[], str="", offset=0, limit=None, count=False, additional_domain=[], context=None): """ Find the move lines that could be used to reconcile a statement line and returns the counterpart that could be created to reconcile them If count is true, only returns the count. :param integer id: the id of the statement line :param integers list excluded_ids: ids of move lines that should not be fetched :param string str: string to filter lines :param integer offset: offset of the request :param integer limit: number of lines to fetch :param boolean count: just return the number of records :param tuples list domain: additional domain restrictions """ if context is None: context = {} rml_parser = report_sxw.rml_parse(cr, uid, 'statement_line_counterpart_widget', context=context) st_line = self.browse(cr, uid, id, context=context) company_currency = st_line.journal_id.company_id.currency_id statement_currency = st_line.journal_id.currency or company_currency mv_line_pool = self.pool.get('account.move.line') currency_obj = self.pool.get('res.currency') domain = additional_domain + [ ('partner_id', '=', st_line.partner_id.id), ('reconcile_id', '=', False), ('state','=','valid'), '|',('account_id.type', '=', 'receivable'), ('account_id.type', '=', 'payable'), #Let the front-end warn the user if he tries to mix payable and receivable in the same reconciliation ] if excluded_ids: domain.append(('id', 'not in', excluded_ids)) if str: domain += ['|', ('move_id.name', 'ilike', str), ('move_id.ref', 'ilike', str)] #partially reconciled lines can be displayed only once reconcile_partial_ids = [] ids = mv_line_pool.search(cr, uid, domain, offset=offset, limit=limit, order="date_maturity asc, id asc", context=context) if count: nb_lines = 0 for line in mv_line_pool.browse(cr, uid, ids, context=context): if line.reconcile_partial_id and line.reconcile_partial_id.id in reconcile_partial_ids: continue nb_lines += 1 if line.reconcile_partial_id: reconcile_partial_ids.append(line.reconcile_partial_id.id) return nb_lines else: ret = [] for line in mv_line_pool.browse(cr, uid, ids, context=context): if line.reconcile_partial_id and line.reconcile_partial_id.id in reconcile_partial_ids: continue amount_currency_str = "" if line.currency_id and line.amount_currency: amount_currency_str = rml_parser.formatLang(line.amount_currency, currency_obj=line.currency_id) ret_line = { 'id': line.id, 'name': line.move_id.name, 'ref': line.move_id.ref, 'account_code': line.account_id.code, 'account_name': line.account_id.name, 'account_type': line.account_id.type, 'date_maturity': line.date_maturity, 'date': line.date, 'period_name': line.period_id.name, 'journal_name': line.journal_id.name, 'amount_currency_str': amount_currency_str, } if statement_currency.id != company_currency.id and line.currency_id and line.currency_id.id == statement_currency.id: if line.amount_residual_currency < 0: ret_line['debit'] = 0 ret_line['credit'] = -line.amount_residual_currency else: ret_line['debit'] = line.amount_residual_currency if line.credit != 0 else 0 ret_line['credit'] = line.amount_residual_currency if line.debit != 0 else 0 ret_line['amount_currency_str'] = rml_parser.formatLang(line.amount_residual, currency_obj=company_currency) else: if line.amount_residual < 0: ret_line['debit'] = 0 ret_line['credit'] = -line.amount_residual else: ret_line['debit'] = line.amount_residual if line.credit != 0 else 0 ret_line['credit'] = line.amount_residual if line.debit != 0 else 0 ctx = context.copy() ctx.update({'date': st_line.date}) ret_line['debit'] = currency_obj.compute(cr, uid, statement_currency.id, company_currency.id, ret_line['debit'], context=ctx) ret_line['credit'] = currency_obj.compute(cr, uid, statement_currency.id, company_currency.id, ret_line['credit'], context=ctx) ret_line['debit_str'] = rml_parser.formatLang(ret_line['debit'], currency_obj=statement_currency) ret_line['credit_str'] = rml_parser.formatLang(ret_line['credit'], currency_obj=statement_currency) ret.append(ret_line) if line.reconcile_partial_id: reconcile_partial_ids.append(line.reconcile_partial_id.id) return ret
def _create_table(self, uid, ids, fields, fields_order, results, context, title=''): pageSize=[297.0, 210.0] new_doc = etree.Element("report") config = etree.SubElement(new_doc, 'config') def _append_node(name, text): n = etree.SubElement(config, name) n.text = text #_append_node('date', time.strftime('%d/%m/%Y')) _append_node('date', time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y')))) _append_node('PageSize', '%.2fmm,%.2fmm' % tuple(pageSize)) _append_node('PageWidth', '%.2f' % (pageSize[0] * 2.8346,)) _append_node('PageHeight', '%.2f' %(pageSize[1] * 2.8346,)) _append_node('report-header', title) registry = openerp.registry(self.cr.dbname) _append_node('company', registry['res.users'].browse(self.cr,uid,uid).company_id.name) rpt_obj = registry['res.users'] rml_obj=report_sxw.rml_parse(self.cr, uid, rpt_obj._name,context) _append_node('header-date', str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M"))) l = [] t = 0 strmax = (pageSize[0]-40) * 2.8346 temp = [] tsum = [] for i in range(0, len(fields_order)): temp.append(0) tsum.append(0) ince = -1 for f in fields_order: s = 0 ince += 1 if fields[f]['type'] in ('date','time','datetime','float','integer'): s = 60 strmax -= s if fields[f]['type'] in ('float','integer'): temp[ince] = 1 else: t += fields[f].get('size', 80) / 28 + 1 l.append(s) for pos in range(len(l)): if not l[pos]: s = fields[fields_order[pos]].get('size', 80) / 28 + 1 l[pos] = strmax * s / t _append_node('tableSize', ','.join(map(str,l)) ) header = etree.SubElement(new_doc, 'header') for f in fields_order: field = etree.SubElement(header, 'field') field.text = tools.ustr(fields[f]['string'] or '') lines = etree.SubElement(new_doc, 'lines') for line in results: node_line = etree.SubElement(lines, 'row') count = -1 for f in fields_order: float_flag = 0 count += 1 if fields[f]['type']=='many2one' and line[f]: if not line.get('__group'): line[f] = line[f][1] if fields[f]['type']=='selection' and line[f]: for key, value in fields[f]['selection']: if key == line[f]: line[f] = value break if fields[f]['type'] in ('one2many','many2many') and line[f]: line[f] = '( '+tools.ustr(len(line[f])) + ' )' if fields[f]['type'] == 'float' and line[f]: precision=(('digits' in fields[f]) and fields[f]['digits'][1]) or 2 prec ='%.' + str(precision) +'f' line[f]=prec%(line[f]) float_flag = 1 if fields[f]['type'] == 'date' and line[f]: new_d1 = line[f] if not line.get('__group'): format = str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y')) d1 = datetime.strptime(line[f],'%Y-%m-%d') new_d1 = d1.strftime(format) line[f] = new_d1 if fields[f]['type'] == 'time' and line[f]: new_d1 = line[f] if not line.get('__group'): format = str(locale.nl_langinfo(locale.T_FMT)) d1 = datetime.strptime(line[f], '%H:%M:%S') new_d1 = d1.strftime(format) line[f] = new_d1 if fields[f]['type'] == 'datetime' and line[f]: new_d1 = line[f] if not line.get('__group'): format = str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))+' '+str(locale.nl_langinfo(locale.T_FMT)) d1 = datetime.strptime(line[f], '%Y-%m-%d %H:%M:%S') new_d1 = d1.strftime(format) line[f] = new_d1 if line.get('__group'): col = etree.SubElement(node_line, 'col', para='group', tree='no') else: col = etree.SubElement(node_line, 'col', para='yes', tree='no') # Prevent empty labels in groups if f == line.get('__grouped_by') and line.get('__group') and not line[f] and not float_flag and not temp[count]: col.text = line[f] = 'Undefined' col.set('tree', 'undefined') if line[f] is not None: col.text = tools.ustr(line[f] or '') if float_flag: col.set('tree','float') if line.get('__no_leaf') and temp[count] == 1 and f != 'id' and not line['__context']['group_by']: tsum[count] = float(tsum[count]) + float(line[f]) if not line.get('__group') and f != 'id' and temp[count] == 1: tsum[count] = float(tsum[count]) + float(line[f]) else: col.text = '/' node_line = etree.SubElement(lines, 'row') for f in range(0, len(fields_order)): col = etree.SubElement(node_line, 'col', para='group', tree='no') col.set('tree', 'float') if tsum[f] is not None: if tsum[f] != 0.0: digits = fields[fields_order[f]].get('digits', (16, 2)) prec = '%%.%sf' % (digits[1], ) total = prec % (tsum[f], ) txt = str(total or '') else: txt = str(tsum[f] or '') else: txt = '/' if f == 0: txt ='Total' col.set('tree','no') col.text = tools.ustr(txt or '') transform = etree.XSLT( etree.parse(os.path.join(tools.config['root_path'], 'addons/base/report/custom_new.xsl'))) rml = etree.tostring(transform(new_doc)) self.obj = render.rml(rml, title=self.title) self.obj.render() return True
def create_xml(self, cr, uid, ids, datas, context=None): obj_emp = pooler.get_pool(cr.dbname).get('hr.employee') emp_ids = datas['active_ids'] start_date = datetime.strptime(datas['form']['init_date'], '%Y-%m-%d') end_date = datetime.strptime(datas['form']['end_date'], '%Y-%m-%d') first_monday = start_date - relativedelta( days=start_date.date().weekday()) last_monday = end_date + relativedelta(days=7 - end_date.date().weekday()) if last_monday < first_monday: first_monday, last_monday = last_monday, first_monday rpt_obj = pooler.get_pool(cr.dbname).get('hr.employee') rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context) header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), pooler.get_pool( cr.dbname).get('res.users').browse(cr, uid, uid).company_id.name) user_xml = [] for employee_id in emp_ids: emp = obj_emp.read(cr, uid, [employee_id], ['id', 'name'])[0] monday, n_monday = first_monday, first_monday + one_week stop, week_xml = False, [] user_repr = ''' <user> <name>%s</name> %%s </user> ''' % tools.ustr(toxml(emp['name'])) while monday != last_monday: #### Work hour calculation sql = ''' select action, att.name from hr_employee as emp inner join hr_attendance as att on emp.id = att.employee_id where att.name between %s and %s and emp.id = %s order by att.name ''' for idx in range(7): cr.execute(sql, (monday.strftime('%Y-%m-%d %H:%M:%S'), (monday + relativedelta(days=idx + 1) ).strftime('%Y-%m-%d %H:%M:%S'), employee_id)) attendances = cr.dictfetchall() week_wh = {} # Fake sign ins/outs at week ends, to take attendances across week ends into account # XXX this is wrong for the first sign-in ever and the last sign out to this date if attendances and attendances[0]['action'] == 'sign_out': attendances.insert( 0, { 'name': monday.strftime('%Y-%m-%d %H:%M:%S'), 'action': 'sign_in' }) if attendances and attendances[-1]['action'] == 'sign_in': attendances.append({ 'name': n_monday.strftime('%Y-%m-%d %H:%M:%S'), 'action': 'sign_out' }) # sum up the attendances' durations ldt = None for att in attendances: dt = datetime.strptime(att['name'], '%Y-%m-%d %H:%M:%S') if ldt and att['action'] == 'sign_out': week_wh[ldt.date().weekday()] = week_wh.get( ldt.date().weekday(), 0) + (float( (dt - ldt).seconds) / 3600) else: ldt = dt # Week xml representation week_repr = [ '<week>', '<weekstart>%s</weekstart>' % monday.strftime('%Y-%m-%d'), '<weekend>%s</weekend>' % (n_monday - relativedelta(days=1)).strftime('%Y-%m-%d') ] for idx in range(7): week_repr.append('<%s>' % num2day[idx]) if idx in week_wh: week_repr.append('<workhours>%sh%02d</workhours>' % to_hour(week_wh[idx])) week_repr.append('</%s>' % num2day[idx]) week_repr.append('<total>') week_repr.append( '<worked>%sh%02d</worked>' % to_hour(reduce(lambda x, y: x + y, week_wh.values(), 0))) week_repr.append('</total>') week_repr.append('</week>') week_xml.append('\n'.join(week_repr)) monday, n_monday = n_monday, n_monday + one_week user_xml.append(user_repr % '\n'.join(week_xml)) xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s <title>%s</title> %s </report> ''' % (header_xml, _('Attendances by Week'), '\n'.join(user_xml)) xml = tools.ustr(xml).encode('utf8') return self.post_process_xml_data(cr, uid, xml, context)
def create_xml(self, cr, uid, ids, data, context): registry = openerp.registry(cr.dbname) # Get the user id from the selected employee record emp_id = data['form']['employee_id'] emp_obj = registry['hr.employee'] user_id = emp_obj.browse(cr, uid, emp_id).user_id.id empl_name = emp_obj.browse(cr, uid, emp_id).name # Computing the dates (start of month: som, and end of month: eom) som = datetime.date(data['form']['year'], data['form']['month'], 1) eom = som + datetime.timedelta(lengthmonth(som.year, som.month)) date_xml = [ '<date month="%s" year="%d" />' % (self.get_month_name( cr, uid, som.month, context=context), som.year), '<days>' ] date_xml += [ '<day number="%d" name="%s" weekday="%d" />' % (x, self.get_weekday_name( cr, uid, som.replace(day=x).weekday() + 1, context=context), som.replace(day=x).weekday() + 1) for x in range(1, lengthmonth(som.year, som.month) + 1) ] date_xml.append('</days>') date_xml.append('<cols>2.5cm%s,2cm</cols>\n' % (',0.7cm' * lengthmonth(som.year, som.month))) # Sum attendence by account, then by day accounts = {} header_xml = '' if user_id: # Computing the attendence by analytical account cr.execute( "select line.date, (unit_amount / unit.factor) as amount, account_id, account.name "\ "from account_analytic_line as line, hr_analytic_timesheet as hr, "\ "account_analytic_account as account, product_uom as unit "\ "where hr.line_id=line.id and line.account_id=account.id "\ "and product_uom_id = unit.id "\ "and line.user_id=%s and line.date >= %s and line.date < %s " "order by line.date", (user_id, som.strftime('%Y-%m-%d'), eom.strftime('%Y-%m-%d'))) for presence in cr.dictfetchall(): day = int(presence['date'][-2:]) account = accounts.setdefault( (presence['account_id'], presence['name']), {}) account[day] = account.get(day, 0.0) + presence['amount'] xml = ''' <time-element date="%s"> <amount>%.2f</amount> </time-element> ''' rpt_obj = registry['hr.employee'] rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context) if user_id: header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % ( str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), to_xml(registry['res.users'].browse(cr, uid, user_id).company_id.name)) account_xml = [] for account, telems in accounts.iteritems(): aid, aname = account aname = registry['account.analytic.account'].name_get( cr, uid, [aid], context) aname = aname[0][1] account_xml.append('<account id="%d" name="%s">' % (aid, toxml(aname))) account_xml.append('\n'.join( [xml % (day, amount) for day, amount in telems.iteritems()])) account_xml.append('</account>') # Computing the xml xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s <employee>%s</employee> %s </report> ''' % (header_xml, ustr( toxml(empl_name)), '\n'.join(date_xml) + '\n'.join(account_xml)) return xml
def create_xml(self, cr, uid, ids, datas, context=None): obj_emp = pooler.get_pool(cr.dbname).get('hr.employee') if context is None: context = {} month = datetime(datas['form']['year'], datas['form']['month'], 1) emp_ids = datas['active_ids'] user_xml = [ '<month>%s</month>' % _(month2name[month.month]), '<year>%s</year>' % month.year ] if emp_ids: for emp in obj_emp.read(cr, uid, emp_ids, ['name']): stop, days_xml = False, [] total_wh = 0.0 user_repr = ''' <user> <name>%s</name> %%s </user> ''' % (ustr(toxml(emp['name']))) today, tomor = month, month + one_day while today.month == month.month: #### Work hour calculation sql = ''' select action, att.name from hr_employee as emp inner join hr_attendance as att on emp.id = att.employee_id where att.name between %s and %s and emp.id = %s order by att.name ''' cr.execute( sql, (today.strftime('%Y-%m-%d %H:%M:%S'), tomor.strftime('%Y-%m-%d %H:%M:%S'), emp['id'])) attendences = cr.dictfetchall() wh = 0.0 # Fake sign ins/outs at week ends, to take attendances across week ends into account if attendences and attendences[0]['action'] == 'sign_out': attendences.insert( 0, { 'name': today.strftime('%Y-%m-%d %H:%M:%S'), 'action': 'sign_in' }) if attendences and attendences[-1]['action'] == 'sign_in': attendences.append({ 'name': tomor.strftime('%Y-%m-%d %H:%M:%S'), 'action': 'sign_out' }) # sum up the attendances' durations ldt = None for att in attendences: dt = datetime.strptime(att['name'], '%Y-%m-%d %H:%M:%S') if ldt and att['action'] == 'sign_out': if dt.date() > ldt.date(): dt = ldt wh += (float((dt - ldt).seconds) / 60 / 60) else: ldt = dt # Week xml representation total_wh += wh wh = hour2str(wh) today_xml = '<day num="%s"><wh>%s</wh></day>' % ( (today - month).days + 1, (wh)) dy = (today - month).days + 1 days_xml.append(today_xml) today, tomor = tomor, tomor + one_day total_wh = hour2str(total_wh) today_xml = '<day num="Total"><wh>%s</wh></day>' % (total_wh) days_xml.append(today_xml) user_xml.append(user_repr % '\n'.join(days_xml)) rpt_obj = pooler.get_pool(cr.dbname).get('hr.employee') rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context) header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), to_xml( pooler.get_pool(cr.dbname).get('res.users').browse( cr, uid, uid).company_id.name)) first_date = str(month) som = datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S') eom = som + timedelta(int(dy) - 1) day_diff = eom - som date_xml = [] cell = 1 date_xml.append('<days>') if day_diff.days >= 30: date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')), x - som.day + 1) for x in range(som.day, lengthmonth(som.year, som.month) + 1) ] else: if day_diff.days >= (lengthmonth(som.year, som.month) - som.day): date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')), x - som.day + 1) for x in range(som.day, lengthmonth(som.year, som.month) + 1) ] else: date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som.replace(day=x).strftime('%a')), x - som.day + 1) for x in range(som.day, eom.day + 1) ] cell = x - som.day + 1 day_diff1 = day_diff.days - cell + 1 width_dict = {} month_dict = {} i = 1 j = 1 year = som.year month = som.month month_dict[j] = som.strftime('%B') width_dict[j] = cell while day_diff1 > 0: if month + i <= 12: if day_diff1 > lengthmonth( year, i + month ): # Not on 30 else you have problems when entering 01-01-2009 for example som1 = datetime.date(year, month + i, 1) date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')), cell + x) for x in range(1, lengthmonth(year, i + month) + 1) ] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x else: som1 = datetime.date(year, month + i, 1) date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')), cell + x) for x in range(1, eom.day + 1) ] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x day_diff1 = day_diff1 - x else: years = year + 1 year = years month = 0 i = 1 if day_diff1 >= 30: som1 = datetime.date(years, i, 1) date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')), cell + x) for x in range(1, lengthmonth(years, i) + 1) ] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x else: som1 = datetime.date(years, i, 1) i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')), cell + x) for x in range(1, eom.day + 1) ] cell = cell + x width_dict[j] = x day_diff1 = day_diff1 - x date_xml += ['<dayy name="Total" cell="Total"/>'] date_xml.append('</days>') date_xml.append('<cols>3.5cm%s,1.2cm</cols>\n' % (',0.74cm' * (int(dy)))) xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s <title>%s</title> %s %s </report> ''' % (header_xml, _('Attendances by Month'), '\n'.join(user_xml), date_xml) return xml
def create_xml(self, cr, uid, ids, data, context): # Get the user id from the selected employee record emp_id = data['form']['employee_id'] emp_obj = pooler.get_pool(cr.dbname).get('hr.employee') user_id = emp_obj.browse(cr, uid, emp_id).user_id.id empl_name = emp_obj.browse(cr, uid, emp_id).name # Computing the dates (start of month: som, and end of month: eom) som = datetime.date(data['form']['year'], data['form']['month'], 1) eom = som + datetime.timedelta(lengthmonth(som.year, som.month)) date_xml = ['<date month="%s" year="%d" />' % (self.get_month_name(cr, uid, som.month, context=context), som.year), '<days>'] date_xml += ['<day number="%d" name="%s" weekday="%d" />' % (x, self.get_weekday_name(cr, uid, som.replace(day=x).weekday()+1, context=context), som.replace(day=x).weekday()+1) for x in range(1, lengthmonth(som.year, som.month)+1)] date_xml.append('</days>') date_xml.append('<cols>2.5cm%s,2cm</cols>\n' % (',0.7cm' * lengthmonth(som.year, som.month))) # Sum attendence by account, then by day accounts = {} header_xml = '' if user_id: # Computing the attendence by analytical account cr.execute( "select line.date, (unit_amount / unit.factor) as amount, account_id, account.name "\ "from account_analytic_line as line, hr_analytic_timesheet as hr, "\ "account_analytic_account as account, product_uom as unit "\ "where hr.line_id=line.id and line.account_id=account.id "\ "and product_uom_id = unit.id "\ "and line.user_id=%s and line.date >= %s and line.date < %s " "order by line.date", (user_id, som.strftime('%Y-%m-%d'), eom.strftime('%Y-%m-%d'))) for presence in cr.dictfetchall(): day = int(presence['date'][-2:]) account = accounts.setdefault((presence['account_id'], presence['name']), {}) account[day] = account.get(day, 0.0) + presence['amount'] xml = ''' <time-element date="%s"> <amount>%.2f</amount> </time-element> ''' rpt_obj = pooler.get_pool(cr.dbname).get('hr.employee') rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name,context) if user_id: header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),to_xml(pooler.get_pool(cr.dbname).get('res.users').browse(cr,uid,user_id).company_id.name)) account_xml = [] for account, telems in accounts.iteritems(): aid, aname = account aname = pooler.get_pool(cr.dbname).get('account.analytic.account').name_get(cr, uid, [aid], context) aname = aname[0][1] account_xml.append('<account id="%d" name="%s">' % (aid, toxml(aname))) account_xml.append('\n'.join([xml % (day, amount) for day, amount in telems.iteritems()])) account_xml.append('</account>') # Computing the xml xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s <employee>%s</employee> %s </report> ''' % (header_xml, ustr(toxml(empl_name)), '\n'.join(date_xml) + '\n'.join(account_xml)) return xml
def create_xml(self, cr, uid, ids, datas, context=None): obj_student = pooler.get_pool(cr.dbname).get('student.student') attendance_sheet_obj = pooler.get_pool (cr.dbname).get('attendance.sheet') if context is None: context = {} month = datetime(datas['form']['year'], datas['form']['month'], 1) # stu_ids = context.get('active_ids', []) stu_ids = datas['form']['stud_ids'] user_xml = [ '<month>%s</month>' % month2name[month.month], '<year>%s</year>' % month.year ] if stu_ids: for student in obj_student.read(cr, uid, stu_ids, ['name', 'standard_id']): days_xml = False, [] user_repr = ''' <user> <name>%s</name> %%s </user> ''' % (ustr(toxml(student['name']))) today, tomor = month, month + one_day while today.month == month.month: day = today.day attendance_sheet_domain = [('standard_id', '=', student['standard_id'][0]), ('month_id', '=', today.month)] attendance_sheet_search_ids =\ attendance_sheet_obj.search(cr, uid, attendance_sheet_domain, context=context) if not attendance_sheet_search_ids: var = 'A' else: for attendance_sheet_data in \ attendance_sheet_obj. \ browse(cr, uid, attendance_sheet_search_ids, context=context): for line in attendance_sheet_data.attendance_ids: if line.name == student['name']: if day == 1: att = line.one elif day == 2: att = line.two elif day == 3: att = line.three elif day == 4: att = line.four elif day == 5: att = line.five elif day == 6: att = line.six elif day == 7: att = line.seven elif day == 8: att = line.eight elif day == 9: att = line.nine elif day == 10: att = line.ten elif day == 11: att = line.one_1 elif day == 12: att = line.one_2 elif day == 13: att = line.one_3 elif day == 14: att = line.one_4 elif day == 15: att = line.one_5 elif day == 16: att = line.one_6 elif day == 17: att = line.one_7 elif day == 18: att = line.one_8 elif day == 19: att = line.one_9 elif day == 20: att = line.one_0 elif day == 21: att = line.two_1 elif day == 22: att = line.two_2 elif day == 23: att = line.two_3 elif day == 24: att = line.two_4 elif day == 25: att = line.two_5 elif day == 26: att = line.two_6 elif day == 27: att = line.two_7 elif day == 28: att = line.two_8 elif day == 29: att = line.two_9 elif day == 30: att = line.two_0 else: att = line.three_1 if att is True: var = 'P' else: var = 'A' # Week xml representation # wh = hour2str(wh) today_xml = '<day num="%s"><wh>%s</wh></day>' %\ ((today - month).days + 1, var) dy = (today - month).days + 1 days_xml.append(today_xml) today, tomor = tomor, tomor + one_day user_xml.append(user_repr % '\n'.join(days_xml)) rpt_obj = pooler.get_pool(cr.dbname).get('student.student') rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context) header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), pooler.get_pool( cr.dbname).get('res.users').browse(cr, uid, uid).company_id.name) first_date = str(month) som = datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S') eom = som + timedelta(int(dy) - 1) day_diff = eom - som date_xml = [] # cell = 1 date_xml.append('<days>') if day_diff.days >= 30: date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, som.replace(day=x).strftime('%a'), x - som.day + 1) for x in range(som.day, lengthmonth(som.year, som.month) + 1) ] else: if day_diff.days >= (lengthmonth(som.year, som.month) - som.day): date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, som.replace(day=x).strftime('%a'), x - som.day + 1) for x in range(som.day, lengthmonth(som.year, som.month) + 1) ] else: date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, som.replace(day=x).strftime('%a'), x - som.day + 1) for x in range(som.day, eom.day + 1) ] cell = x - som.day + 1 day_diff1 = day_diff.days - cell + 1 width_dict = {} month_dict = {} i = 1 j = 1 year = som.year month = som.month month_dict[j] = som.strftime('%B') width_dict[j] = cell while day_diff1 > 0: if month + i <= 12: if day_diff1 > lengthmonth(year, i + month): # Not on 30 else you have problems when entering 01-01-2009 # for example som1 = datetime.date(year, month + i, 1) date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, som1.replace(day=x).strftime('%a'), cell + x) for x in range(1, lengthmonth(year, i + month) + 1) ] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x else: som1 = datetime.date(year, month + i, 1) date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, som1.replace(day=x).strftime('%a'), cell + x) for x in range(1, eom.day + 1) ] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x day_diff1 = day_diff1 - x else: years = year + 1 year = years month = 0 i = 1 if day_diff1 >= 30: som1 = datetime.date(years, i, 1) date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, som1.replace(day=x).strftime('%a'), cell + x) for x in range(1, lengthmonth(years, i) + 1) ] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x else: som1 = datetime.date(years, i, 1) i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') date_xml += [ '<dayy number="%d" name="%s" cell="%d"/>' % (x, som1.replace(day=x).strftime('%a'), cell + x) for x in range(1, eom.day + 1) ] cell = cell + x width_dict[j] = x day_diff1 = day_diff1 - x date_xml.append('</days>') date_xml.append('<cols>3.5cm%s</cols>\n' % (',0.74cm' * (int(dy)))) xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s </report> ''' % (header_xml, '\n'.join(user_xml), date_xml) return xml
def create_xml(self, cr, uid, ids, datas, context=None): number = (datas.get('form', False) and datas['form']['number']) or 1 registry = openerp.registry(cr.dbname) product_pool = registry.get('product.product') product_uom_pool = registry.get('product.uom') workcenter_pool = registry.get('mrp.workcenter') user_pool = registry.get('res.users') bom_pool = registry.get('mrp.bom') pricelist_pool = registry.get('product.pricelist') rml_obj = report_sxw.rml_parse(cr, uid, product_pool._name, context) rml_obj.localcontext.update({'lang': context.get('lang', False)}) company_currency = user_pool.browse(cr, uid, uid).company_id.currency_id company_currency_symbol = company_currency.symbol or company_currency.name def process_bom(bom, currency_id, factor=1): xml = '<row>' sum = 0 sum_strd = 0 prod = product_pool.browse(cr, uid, bom['product_id']) prod_name = to_xml(bom['name']) prod_qtty = factor * bom['product_qty'] product_uom = product_uom_pool.browse(cr, uid, bom['product_uom'], context=context) product_uom_name = to_xml(product_uom.name) main_sp_price, main_sp_name, main_strd_price = '', '', '' sellers, sellers_price = '', '' if prod.seller_id: main_sp_name = '- <b>' + to_xml( prod.seller_id.name) + '</b>\r\n' pricelist = prod.seller_id.property_product_pricelist_purchase price = pricelist_pool.price_get( cr, uid, [pricelist.id], prod.id, number * prod_qtty or 1.0, prod.seller_id.id, { 'uom': prod.uom_po_id.id, 'date': time.strftime('%Y-%m-%d'), })[pricelist.id] main_sp_price = """<b>""" + rml_obj.formatLang(price) + ' ' + ( company_currency_symbol) + """</b>\r\n""" sum += prod_qtty * price std_price = product_uom_pool._compute_price( cr, uid, prod.uom_id.id, prod.standard_price, to_uom_id=product_uom.id) main_strd_price = str(std_price) + '\r\n' sum_strd = prod_qtty * std_price for seller_id in prod.seller_ids: if seller_id.name.id == prod.seller_id.id: continue sellers += '- <i>' + to_xml(seller_id.name.name) + '</i>\r\n' pricelist = seller_id.name.property_product_pricelist_purchase price = pricelist_pool.price_get( cr, uid, [pricelist.id], prod.id, number * prod_qtty or 1.0, seller_id.name.id, { 'uom': prod.uom_po_id.id, 'date': time.strftime('%Y-%m-%d'), })[pricelist.id] sellers_price += """<i>""" + rml_obj.formatLang( price) + ' ' + (company_currency_symbol) + """</i>\r\n""" xml += """<col para='yes'> """ + prod_name + """ </col> <col para='yes'> """ + main_sp_name + sellers + """ </col> <col f='yes'>""" + rml_obj.formatLang( prod_qtty) + ' ' + product_uom_name + """</col> <col f='yes'>""" + rml_obj.formatLang( float(main_strd_price)) + ' ' + ( company_currency_symbol) + """</col> <col f='yes'>""" + main_sp_price + sellers_price + """</col>'""" xml += '</row>' return xml, sum, sum_strd def process_workcenter(wrk): workcenter = workcenter_pool.browse(cr, uid, wrk['workcenter_id']) cost_cycle = wrk['cycle'] * workcenter.costs_cycle cost_hour = wrk['hour'] * workcenter.costs_hour total = cost_cycle + cost_hour xml = '<row>' xml += "<col para='yes'>" + to_xml(workcenter.name) + '</col>' xml += "<col/>" xml += """<col f='yes'>""" + rml_obj.formatLang( cost_cycle) + ' ' + (company_currency_symbol) + """</col>""" xml += """<col f='yes'>""" + rml_obj.formatLang( cost_hour) + ' ' + (company_currency_symbol) + """</col>""" xml += """<col f='yes'>""" + rml_obj.formatLang( cost_hour + cost_cycle) + ' ' + (company_currency_symbol) + """</col>""" xml += '</row>' return xml, total xml = '' config_start = """ <config> <date>""" + to_xml( rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), date_time=True)) + """</date> <company>%s</company> <PageSize>210.00mm,297.00mm</PageSize> <PageWidth>595.27</PageWidth> <PageHeight>841.88</PageHeight> <tableSize>55.00mm,58.00mm,29.00mm,29.00mm,29.00mm</tableSize> """ % to_xml(user_pool.browse(cr, uid, uid).company_id.name) config_stop = """ <report-footer>Generated by Odoo</report-footer> </config> """ workcenter_header = """ <lines style='header'> <row> <col>%s</col> <col t='yes'/> <col t='yes'>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row> </lines> """ % (_('Work Center name'), _('Cycles Cost'), _('Hourly Cost'), _('Work Cost')) prod_header = """ <row> <col>%s</col> <col>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row> """ % (_('Components'), _('Components suppliers'), _('Quantity'), _('Cost Price per Unit of Measure'), _('Supplier Price per Unit of Measure')) purchase_price_digits = rml_obj.get_digits(dp='Product Price') for product in product_pool.browse(cr, uid, ids, context=context): product_uom_name = to_xml(product.uom_id.name) bom_id = bom_pool._bom_find(cr, uid, product_id=product.id, context=context) title = "<title>%s</title>" % (_("Cost Structure")) title += "<title>%s</title>" % (to_xml(product.name)) xml += "<lines style='header'>" + title + prod_header + "</lines>" if not bom_id: total_strd = number * product.standard_price total = number * product_pool.price_get( cr, uid, [product.id], 'standard_price')[product.id] xml += """<lines style='lines'><row> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> </row></lines>""" xml += """<lines style='total'> <row> <col> """ + _('Total Cost of %s %s') % ( str(number), product_uom_name) + """: </col> <col/> <col f='yes'/> <col t='yes'>""" + rml_obj.formatLang( total_strd, digits=purchase_price_digits) + ' ' + ( company_currency_symbol) + """</col> <col t='yes'>""" + rml_obj.formatLang( total, digits=purchase_price_digits) + ' ' + ( company_currency_symbol) + """</col> </row></lines>'""" else: bom = bom_pool.browse(cr, uid, bom_id, context=context) factor = number * product.uom_id.factor / bom.product_uom.factor sub_boms = bom_pool._bom_explode(cr, uid, bom, product, factor / bom.product_qty, context=context) total = 0 total_strd = 0 parent_bom = { 'product_qty': bom.product_qty, 'name': bom.product_id.name, 'product_uom': bom.product_uom.id, 'product_id': bom.product_id.id } xml_tmp = '' for sub_bom in (sub_boms and sub_boms[0]) or [parent_bom]: txt, sum, sum_strd = process_bom(sub_bom, company_currency.id) xml_tmp += txt total += sum total_strd += sum_strd xml += "<lines style='lines'>" + xml_tmp + '</lines>' xml += """<lines style='sub_total'> <row> <col> """ + _('Components Cost of %s %s') % ( str(number), product_uom_name) + """: </col> <col/> <col t='yes'/> <col t='yes'>""" + rml_obj.formatLang( total_strd, digits=purchase_price_digits) + ' ' + ( company_currency_symbol) + """</col> <col t='yes'></col> </row></lines>'""" total2 = 0 xml_tmp = '' for wrk in (sub_boms and sub_boms[1]): txt, sum = process_workcenter(wrk) xml_tmp += txt total2 += sum if xml_tmp: xml += workcenter_header xml += "<lines style='lines'>" + xml_tmp + '</lines>' xml += """<lines style='sub_total'> <row> <col> """ + _('Work Cost of %s %s') % ( str(number), product_uom_name) + """: </col> <col/> <col/> <col/> <col t='yes'>""" + rml_obj.formatLang( total2, digits=purchase_price_digits) + ' ' + ( company_currency_symbol) + """</col> </row></lines>'""" xml += """<lines style='total'> <row> <col> """ + _('Total Cost of %s %s') % ( str(number), product_uom_name) + """: </col> <col/> <col t='yes'/> <col t='yes'>""" + rml_obj.formatLang( total_strd + total2, digits=purchase_price_digits) + ' ' + ( company_currency_symbol) + """</col> <col t='yes'></col> </row></lines>'""" xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>' return xml
def create_xml(self, cr, uid, ids, datas, context=None): number = (datas.get('form', False) and datas['form']['number']) or 1 registry = openerp.registry(cr.dbname) product_pool = registry.get('product.product') product_uom_pool = registry.get('product.uom') workcenter_pool = registry.get('mrp.workcenter') user_pool = registry.get('res.users') bom_pool = registry.get('mrp.bom') pricelist_pool = registry.get('product.pricelist') rml_obj=report_sxw.rml_parse(cr, uid, product_pool._name,context) rml_obj.localcontext.update({'lang':context.get('lang',False)}) company_currency = user_pool.browse(cr, uid, uid).company_id.currency_id company_currency_symbol = company_currency.symbol or company_currency.name def process_bom(bom, currency_id, factor=1): xml = '<row>' sum = 0 sum_strd = 0 prod = product_pool.browse(cr, uid, bom['product_id']) prod_name = to_xml(bom['name']) prod_qtty = factor * bom['product_qty'] product_uom = product_uom_pool.browse(cr, uid, bom['product_uom'], context=context) product_uom_name = to_xml(product_uom.name) main_sp_price, main_sp_name , main_strd_price = '','','' sellers, sellers_price = '','' if prod.seller_id: main_sp_name = '- <b>'+ to_xml(prod.seller_id.name) +'</b>\r\n' pricelist = prod.seller_id.property_product_pricelist_purchase price = pricelist_pool.price_get(cr,uid,[pricelist.id], prod.id, number*prod_qtty or 1.0, prod.seller_id.id, { 'uom': prod.uom_po_id.id, 'date': time.strftime('%Y-%m-%d'), })[pricelist.id] main_sp_price = """<b>"""+rml_obj.formatLang(price)+' '+ (company_currency_symbol)+"""</b>\r\n""" sum += prod_qtty*price std_price = product_uom_pool._compute_price(cr, uid, prod.uom_id.id, prod.standard_price, to_uom_id=product_uom.id) main_strd_price = str(std_price) + '\r\n' sum_strd = prod_qtty*std_price for seller_id in prod.seller_ids: if seller_id.name.id == prod.seller_id.id: continue sellers += '- <i>'+ to_xml(seller_id.name.name) +'</i>\r\n' pricelist = seller_id.name.property_product_pricelist_purchase price = pricelist_pool.price_get(cr,uid,[pricelist.id], prod.id, number*prod_qtty or 1.0, seller_id.name.id, { 'uom': prod.uom_po_id.id, 'date': time.strftime('%Y-%m-%d'), })[pricelist.id] sellers_price += """<i>"""+rml_obj.formatLang(price) +' '+ (company_currency_symbol) +"""</i>\r\n""" xml += """<col para='yes'> """+ prod_name +""" </col> <col para='yes'> """+ main_sp_name + sellers + """ </col> <col f='yes'>"""+ rml_obj.formatLang(prod_qtty) +' '+ product_uom_name +"""</col> <col f='yes'>"""+ rml_obj.formatLang(float(main_strd_price)) +' '+ (company_currency_symbol) +"""</col> <col f='yes'>""" + main_sp_price + sellers_price + """</col>'""" xml += '</row>' return xml, sum, sum_strd def process_workcenter(wrk): workcenter = workcenter_pool.browse(cr, uid, wrk['workcenter_id']) cost_cycle = wrk['cycle']*workcenter.costs_cycle cost_hour = wrk['hour']*workcenter.costs_hour total = cost_cycle + cost_hour xml = '<row>' xml += "<col para='yes'>" + to_xml(workcenter.name) + '</col>' xml += "<col/>" xml += """<col f='yes'>"""+rml_obj.formatLang(cost_cycle)+' '+ (company_currency_symbol) + """</col>""" xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour)+' '+ (company_currency_symbol) + """</col>""" xml += """<col f='yes'>"""+rml_obj.formatLang(cost_hour + cost_cycle)+' '+ (company_currency_symbol) + """</col>""" xml += '</row>' return xml, total xml = '' config_start = """ <config> <date>""" + to_xml(rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),date_time=True)) + """</date> <company>%s</company> <PageSize>210.00mm,297.00mm</PageSize> <PageWidth>595.27</PageWidth> <PageHeight>841.88</PageHeight> <tableSize>55.00mm,58.00mm,29.00mm,29.00mm,29.00mm</tableSize> """ % to_xml(user_pool.browse(cr, uid, uid).company_id.name) config_stop = """ <report-footer>Generated by Odoo</report-footer> </config> """ workcenter_header = """ <lines style='header'> <row> <col>%s</col> <col t='yes'/> <col t='yes'>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row> </lines> """ % (_('Work Center name'), _('Cycles Cost'), _('Hourly Cost'),_('Work Cost')) prod_header = """ <row> <col>%s</col> <col>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row> """ % (_('Components'), _('Components suppliers'), _('Quantity'),_('Cost Price per Unit of Measure'), _('Supplier Price per Unit of Measure')) purchase_price_digits = rml_obj.get_digits(dp='Product Price') for product in product_pool.browse(cr, uid, ids, context=context): product_uom_name = to_xml(product.uom_id.name) bom_id = bom_pool._bom_find(cr, uid, product_id=product.id, context=context) title = "<title>%s</title>" %(_("Cost Structure")) title += "<title>%s</title>" % (to_xml(product.name)) xml += "<lines style='header'>" + title + prod_header + "</lines>" if not bom_id: total_strd = number * product.standard_price total = number * product_pool.price_get(cr, uid, [product.id], 'standard_price')[product.id] xml += """<lines style='lines'><row> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> <col para='yes'>-</col> </row></lines>""" xml += """<lines style='total'> <row> <col> """ + _('Total Cost of %s %s') % (str(number), product_uom_name) + """: </col> <col/> <col f='yes'/> <col t='yes'>"""+ rml_obj.formatLang(total_strd, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> <col t='yes'>"""+ rml_obj.formatLang(total, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> </row></lines>'""" else: bom = bom_pool.browse(cr, uid, bom_id, context=context) factor = number * product.uom_id.factor / bom.product_uom.factor sub_boms = bom_pool._bom_explode(cr, uid, bom, product, factor / bom.product_qty, context=context) total = 0 total_strd = 0 parent_bom = { 'product_qty': bom.product_qty, 'name': bom.product_id.name, 'product_uom': bom.product_uom.id, 'product_id': bom.product_id.id } xml_tmp = '' for sub_bom in (sub_boms and sub_boms[0]) or [parent_bom]: txt, sum, sum_strd = process_bom(sub_bom, company_currency.id) xml_tmp += txt total += sum total_strd += sum_strd xml += "<lines style='lines'>" + xml_tmp + '</lines>' xml += """<lines style='sub_total'> <row> <col> """ + _('Components Cost of %s %s') % (str(number), product_uom_name) + """: </col> <col/> <col t='yes'/> <col t='yes'>"""+ rml_obj.formatLang(total_strd, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> <col t='yes'></col> </row></lines>'""" total2 = 0 xml_tmp = '' for wrk in (sub_boms and sub_boms[1]): txt, sum = process_workcenter(wrk) xml_tmp += txt total2 += sum if xml_tmp: xml += workcenter_header xml += "<lines style='lines'>" + xml_tmp + '</lines>' xml += """<lines style='sub_total'> <row> <col> """ + _('Work Cost of %s %s') % (str(number), product_uom_name) +""": </col> <col/> <col/> <col/> <col t='yes'>"""+ rml_obj.formatLang(total2, digits=purchase_price_digits) +' '+ (company_currency_symbol) +"""</col> </row></lines>'""" xml += """<lines style='total'> <row> <col> """ + _('Total Cost of %s %s') % (str(number), product_uom_name) + """: </col> <col/> <col t='yes'/> <col t='yes'>"""+ rml_obj.formatLang(total_strd+total2, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> <col t='yes'></col> </row></lines>'""" xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>' return xml
def create_xml(self, cr, uid, ids, data, context): registry = openerp.registry(cr.dbname) obj_emp = registry['hr.employee'] depts=[] emp_id={} rpt_obj = registry['hr_attendance.record.report'] rml_obj=report_sxw.rml_parse(cr, uid, rpt_obj._name,context) cr.execute("SELECT name FROM res_company") res=cr.fetchone()[0] date_xml=[] date_today=time.strftime('%Y-%m-%d %H:%M:%S') date_xml +=['<res name="%s" today="%s" />' % (to_xml(res),date_today)] legend = {'Present':'green','Weekends':'lightgrey','Absent':'red','Leave':'violet','Public Holiday':'blue'} today=datetime.datetime.today() today_year = today.strftime('%Y-%m-%d %H:%M:%S')[0:4] #### Check for Filter in Wizard to get Start and end date ##### if data['form']['filter_by_date'] == True: first_date = datetime.datetime.strptime(data['form']['date_from'],'%Y-%m-%d') + datetime.timedelta() last_date = datetime.datetime.strptime(data['form']['date_to'],'%Y-%m-%d') + datetime.timedelta() else : month_selected = data['form']['monthly_status'] first_date = datetime.datetime(int(today_year),int(month_selected),1) number_of_days = lengthmonth( int(today_year), int(month_selected)) last_date = datetime.datetime(int(today_year),int(month_selected),number_of_days) day_diff=last_date-first_date name = '' if len(data['form'].get('emp_id', ())) == 1: name = obj_emp.read(cr, uid, data['form']['emp_id'][0], ['name'])['name'] date_xml.append('<from>%s</from>\n'% (str(rml_obj.formatLang(first_date.strftime("%Y-%m-%d"),date=True)))) date_xml.append('<to>%s</to>\n' %(str(rml_obj.formatLang(last_date.strftime("%Y-%m-%d"),date=True)))) date_xml.append('<name>%s</name>'%(name)) # date_xml=[] for l in range(0,len(legend)): date_xml += ['<legend row="%d" id="%d" name="%s" color="%s" />' % (l+1, l+1, legend.keys()[l], legend.values()[l] )] date_xml += ['<date month="%s" year="%d" />' % (ustr(first_date.strftime('%B')),first_date.year),'<days>'] cell=1 if day_diff.days>=31: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(first_date.replace(day=x).strftime('%a')), x-first_date.day+1) for x in range(first_date.day, day_diff.days +1)] else: #date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(first_date.replace(day=x).strftime('%a')), x-first_date.day+1) for x in range(first_date.day, last_date.day+1)] if day_diff.days>=(lengthmonth(first_date.year, first_date.month)-first_date.day): date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(first_date.replace(day=x).strftime('%a')),x-first_date.day+1) for x in range(first_date.day, lengthmonth(first_date.year, first_date.month)+1)] else: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(first_date.replace(day=x).strftime('%a')), x-first_date.day+1) for x in range(first_date.day, last_date.day+1)] cell=x-first_date.day+1 day_diff1=day_diff.days-cell+1 width_dict={} month_dict={} i=1 j=1 year=first_date.year month=first_date.month month_dict[j]=first_date.strftime('%B') width_dict[j]=cell while day_diff1>0: if month + i <=12: # If month + i <=12 if day_diff1 > lengthmonth(year,i+month): # Not on 30 else you have problems when entering 01-01-2009 for example som1=datetime.date(year,month+i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, lengthmonth(year,i+month)+1)] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x else: som1=datetime.date(year,month+i,1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, _(som1.replace(day=x).strftime('%a')),cell+x) for x in range(1, last_date.day +1 )] i=i+1 j=j+1 month_dict[j]=som1.strftime('%B') cell=cell+x width_dict[j]=x day_diff1=day_diff1-x date_xml.append('</days>') date_xml.append('<cols>3.5cm%s,1.0cm</cols>\n' % (',0.7cm' * (day_diff.days+1))) date_xml = ''.join(date_xml) st='<cols_months>3.5cm' for m in range(1,len(width_dict)+1): st+=',' + str(0.7 *width_dict[m])+'cm' st+=',1.0cm</cols_months>\n' months_xml =['<months number="%d" name="%s"/>' % (x, _(month_dict[x])) for x in range(1,len(month_dict)+1) ] months_xml.append(st) emp_xml='' row_id=1 if data['model'] == 'hr.employee': for items in obj_emp.read(cr, uid, data['form']['emp_id'], ['id', 'name']): emp_xml += emp_create_xml(self, cr, uid, 0, row_id, items['id'], items['name'], first_date, last_date) row_id = row_id +1 header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M")),to_xml(registry['res.users'].browse(cr,uid,uid).company_id.name)) # Computing the xml xml='''<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s %s </report> ''' % (header_xml,months_xml,date_xml, ustr(emp_xml)) return xml
def get_results(self, pool, cr, uid, start, end): account_invoice_obj = pool.get('account.invoice') account_invoice_tax_obj = pool.get('account.invoice.tax') util_parser = rml_parse(cr, uid, 'internal') util_parser.objects = [] # FIXME util_parser.setLang('it_IT') # FIXME invoice_ids = account_invoice_obj.search( cr, uid, [ ('type', 'in', ['out_invoice', 'out_refund']), ('date_invoice', '>=', start), ('date_invoice', '<=', end), ], order='number') invoice_tax_ids = account_invoice_tax_obj.search( cr, uid, [ ('invoice_id', 'in', invoice_ids), ('tax_amount', '!=', 0), ]) invoice_taxes = account_invoice_tax_obj.browse(cr, uid, invoice_tax_ids) tax_map = OrderedDict() for tax in sorted(invoice_taxes, key=lambda t: t.invoice_id.number): if tax.tax_code_id.exclude_from_company_vs_private: continue tax.rate = int(round(tax.tax_amount * 100 / tax.base_amount)) tax_map.setdefault(tax.invoice_id, []).append(tax) tax_map[tax.invoice_id].sort(key=lambda t: t.rate) char_attrs = "oe_list_field_cell oe_list_field_char" num_attrs = "oe_list_field_cell oe_list_field_float oe_number" date_attrs = "oe_list_field_cell oe_list_field_date" header_attrs = "oe_list_header" def to_number(number): return number if '/' not in number else number.split('/')[-1] html = '<table class="oe_list_content"><tbody>' html += '<thead><tr class="oe_list_header_columns">' html += '<td class="%s">Kind</td>' % header_attrs html += '<td class="%s">Date</td>' % header_attrs html += '<td class="%s">Number</td>' % header_attrs html += '<td class="%s">Base Amount</td>' % header_attrs html += '<td class="%s">Tax Rate</td>' % header_attrs html += '<td class="%s">Tax Amount</td>' % header_attrs html += '<td class="%s">Total Amount</td>' % header_attrs html += '</tr></thead>' private_total_map = {} company_total_map = {} total_map = {} for invoice, taxes in tax_map.items(): kind = 'Company' if invoice.partner_id.vat else 'Private' for tax in taxes: html += '<tr>' html += '<td class="%s">%s</td>' % (char_attrs, kind) html += '<td class="%s">%s</td>' % ( date_attrs, tax.invoice_id.date_invoice) html += '<td class="%s">%s</td>' % ( num_attrs, to_number(tax.invoice_id.number)) html += '<td class="%s">%s</td>' % ( num_attrs, util_parser.formatLang(tax.base_amount)) html += '<td class="%s">%d%%</td>' % (num_attrs, tax.rate) html += '<td class="%s">%s</td>' % ( num_attrs, util_parser.formatLang(tax.tax_amount)) html += '<td class="%s">%s</td>' % ( num_attrs, util_parser.formatLang(tax.base_amount + tax.tax_amount)) html += '</tr>' total_map.setdefault(tax.rate, { 'base': 0, 'tax': 0, 'total': 0 }) total_map[tax.rate]['base'] += tax.base_amount total_map[tax.rate]['tax'] += tax.tax_amount total_map[ tax.rate]['total'] += tax.base_amount + tax.tax_amount if kind == 'Company': company_total_map.setdefault(tax.rate, { 'base': 0, 'tax': 0, 'total': 0 }) company_total_map[tax.rate]['base'] += tax.base_amount company_total_map[tax.rate]['tax'] += tax.tax_amount company_total_map[ tax.rate]['total'] += tax.base_amount + tax.tax_amount else: private_total_map.setdefault(tax.rate, { 'base': 0, 'tax': 0, 'total': 0 }) private_total_map[tax.rate]['base'] += tax.base_amount private_total_map[tax.rate]['tax'] += tax.tax_amount private_total_map[ tax.rate]['total'] += tax.base_amount + tax.tax_amount html += '</tbody></table>' def get_column_headers(): html = '<thead><tr class="oe_list_header_columns">' html += '<td class="%s">Base Amount</td>' % header_attrs html += '<td class="%s">Rate</td>' % header_attrs html += '<td class="%s">Tax Amount</td>' % header_attrs html += '<td class="%s">Total Amount</td>' % header_attrs html += '</tr></thead>' return html def get_totals_table(title, t_map): html = '<h2 style="margin-top: 20px; margin-bottom: 10px;">%s</h2>' % title html += '<table class="oe_list_content"><tbody>' html += get_column_headers() for rate, totals in t_map.items(): html += '<tr>' html += '<td class="%s">%s</td>' % ( num_attrs, util_parser.formatLang(totals['base'])) html += '<td class="%s">%d%%</td>' % (num_attrs, rate) html += '<td class="%s">%s</td>' % ( num_attrs, util_parser.formatLang(totals['tax'])) html += '<td class="%s">%s</td>' % ( num_attrs, util_parser.formatLang(totals['total'])) html += '</tr>' html += '</tbody></table>' return html html += get_totals_table('Private Amounts', private_total_map) html += get_totals_table('Company Amounts', company_total_map) html += get_totals_table('Total Amounts', total_map) return html
def create_xml(self, cr, uid, ids, datas, context=None): obj_student = pooler.get_pool(cr.dbname).get('student.student') attendance_sheet_obj = pooler.get_pool (cr.dbname).get('attendance.sheet') if context is None: context = {} month = datetime(datas['form']['year'], datas['form']['month'], 1) # stu_ids = context.get('active_ids', []) stu_ids = datas['form']['stud_ids'] user_xml = ['<month>%s</month>' % month2name[month.month], '<year>%s</year>' % month.year] if stu_ids: for student in obj_student.read(cr, uid, stu_ids, ['name', 'standard_id']): days_xml = False, [] user_repr = ''' <user> <name>%s</name> %%s </user> ''' % (ustr(toxml(student['name']))) today, tomor = month, month + one_day while today.month == month.month: day = today.day attendance_sheet_domain = [('standard_id', '=', student['standard_id'][0]), ('month_id', '=', today.month)] attendance_sheet_search_ids =\ attendance_sheet_obj.search(cr, uid, attendance_sheet_domain, context=context) if not attendance_sheet_search_ids: var = 'A' else: for attendance_sheet_data in \ attendance_sheet_obj. \ browse(cr, uid, attendance_sheet_search_ids, context=context): for line in attendance_sheet_data.attendance_ids: if line.name == student['name']: if day == 1: att = line.one elif day == 2: att = line.two elif day == 3: att = line.three elif day == 4: att = line.four elif day == 5: att = line.five elif day == 6: att = line.six elif day == 7: att = line.seven elif day == 8: att = line.eight elif day == 9: att = line.nine elif day == 10: att = line.ten elif day == 11: att = line.one_1 elif day == 12: att = line.one_2 elif day == 13: att = line.one_3 elif day == 14: att = line.one_4 elif day == 15: att = line.one_5 elif day == 16: att = line.one_6 elif day == 17: att = line.one_7 elif day == 18: att = line.one_8 elif day == 19: att = line.one_9 elif day == 20: att = line.one_0 elif day == 21: att = line.two_1 elif day == 22: att = line.two_2 elif day == 23: att = line.two_3 elif day == 24: att = line.two_4 elif day == 25: att = line.two_5 elif day == 26: att = line.two_6 elif day == 27: att = line.two_7 elif day == 28: att = line.two_8 elif day == 29: att = line.two_9 elif day == 30: att = line.two_0 else: att = line.three_1 if att is True: var = 'P' else: var = 'A' # Week xml representation # wh = hour2str(wh) today_xml = '<day num="%s"><wh>%s</wh></day>' %\ ((today - month).days + 1, var) dy = (today - month).days + 1 days_xml.append(today_xml) today, tomor = tomor, tomor + one_day user_xml.append(user_repr % '\n'.join(days_xml)) rpt_obj = pooler.get_pool(cr.dbname).get('student.student') rml_obj = report_sxw.rml_parse(cr, uid, rpt_obj._name, context) header_xml = ''' <header> <date>%s</date> <company>%s</company> </header> ''' % (str(rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), pooler.get_pool(cr.dbname) .get('res.users').browse(cr, uid, uid).company_id.name) first_date = str(month) som = datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S') eom = som + timedelta(int(dy) - 1) day_diff = eom - som date_xml = [] # cell = 1 date_xml.append('<days>') if day_diff.days >= 30: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, som.replace(day=x).strftime('%a'), x - som.day + 1) for x in range(som.day, lengthmonth (som.year, som.month) + 1)] else: if day_diff.days >= (lengthmonth(som.year, som.month) - som.day): date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, som.replace(day=x).strftime('%a'), x - som.day + 1) for x in range(som.day, lengthmonth (som.year, som.month) + 1)] else: date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, som.replace(day=x).strftime('%a'), x - som.day + 1) for x in range (som.day, eom.day + 1)] cell = x - som.day + 1 day_diff1 = day_diff.days - cell + 1 width_dict = {} month_dict = {} i = 1 j = 1 year = som.year month = som.month month_dict[j] = som.strftime('%B') width_dict[j] = cell while day_diff1 > 0: if month + i <= 12: if day_diff1 > lengthmonth(year, i + month): # Not on 30 else you have problems when entering 01-01-2009 # for example som1 = datetime.date(year, month + i, 1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, som1.replace(day=x).strftime('%a'), cell + x) for x in range (1, lengthmonth(year, i + month) + 1)] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x else: som1 = datetime.date(year, month + i, 1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, som1.replace(day=x).strftime('%a'), cell + x) for x in range(1, eom.day + 1)] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x day_diff1 = day_diff1 - x else: years = year + 1 year = years month = 0 i = 1 if day_diff1 >= 30: som1 = datetime.date(years, i, 1) date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, som1.replace(day=x).strftime('%a'), cell + x) for x in range(1, lengthmonth(years, i) + 1)] i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') cell = cell + x width_dict[j] = x else: som1 = datetime.date(years, i, 1) i = i + 1 j = j + 1 month_dict[j] = som1.strftime('%B') date_xml += ['<dayy number="%d" name="%s" cell="%d"/>' % (x, som1.replace(day=x).strftime('%a'), cell + x) for x in range(1, eom.day + 1)] cell = cell + x width_dict[j] = x day_diff1 = day_diff1 - x date_xml.append('</days>') date_xml.append('<cols>3.5cm%s</cols>\n' % (',0.74cm' * (int(dy)))) xml = '''<?xml version="1.0" encoding="UTF-8" ?> <report> %s %s %s </report> ''' % (header_xml, '\n'.join(user_xml), date_xml) return xml
def write_bc(self,cr,uid,ids,context): # siapkan format penulisan L,R or C def dikiri(length,kata): txtFormat='' txtFormat = '{:<%d}' % length return txtFormat.format(kata) def dikanan(length,kata): txtFormat='' txtFormat = '{:>%d}' % length return txtFormat.format(kata) def ditengah(length,kata,separator): if not separator: separator=" " txtFormat='' txtFormat = '{:%s^%d}' % (separator,length) return txtFormat.format(kata) def diDiv(length,kata): kata = kata.split("\n") dived=[] for kt in kata: x0=0 x=len(kt) L=[];st=[];fs=[] while x>0: st.append(x0*length) x0+=1 fs.append(x0*length) x-=length for x,y in zip(st,fs): L.append(kt[x:y]) dived += L return dived def cekElem(arrDict): # input : arrDict = {'a':arrayA,'b':arrayB,'c':arrayC} # output : length array will same acording to the bigest length, append by " " kosong = arrDict['kosong'] arrDict.pop('kosong') L=0 if len(arrDict.keys()) > 1 : L= max(len(k) for k in arrDict.values()) for div in arrDict.keys(): while len(arrDict[div])<L: arrDict[div].append(dikiri(kosong[div]-1," ")) return arrDict,L # PAPER LENGTH 95 chrs # grs separator 95chrs length separator="-----------------------------------------------------------------------------------------------" for data in self.browse(cr,uid,ids,): result="" comp = data.company_id.name.upper() alamatC = ' '.join([str(data.company_id.street or ''), str(data.company_id.street2 or ''), str(data.company_id.city or ''), str(data.company_id.state_id and data.company_id.state_id.name or ''), str(data.company_id.zip or ''), str(data.company_id.country_id and data.company_id.country_id.name or '')]) phoneC = ' '.join([data.company_id.phone and str("phone %s" % data.company_id.phone) or '', data.company_id.fax and str(", fax %s" % data.company_id.fax) or '']) if data.company_id.partner_id.npwp: phoneC = " ".join([phoneC,data.company_id.partner_id.npwp]) # Company header mainHeader=[dikiri(95,comp),dikiri(95,alamatC),dikiri(95,phoneC),separator] partner = data.partner_id.name almatkpd = ' '.join([str(data.partner_id.street or ''), str(data.partner_id.street2 or ''), str(data.partner_id.city or '')]) phkpd = ' '.join([data.partner_id.phone or '', data.partner_id.fax and str(" fax %s" % data.partner_id.fax) or '']) # main title titles = [] hdL=[12,22,18,40] tabs = 54 titles.append(ditengah(tabs,"PURCHASE ORDER"," ")) titles.append(" ".join([dikiri(hdL[0],"No.Order :"), dikiri(hdL[1],"Order Date :"), dikiri(hdL[2],"Prepared By :"), dikiri(hdL[3],partner[:hdL[3]])])) titles.append(" ".join([dikiri(hdL[0],data.name), dikiri(hdL[1],data.date_order), dikiri(hdL[2],data.validator.name), dikiri(hdL[3],almatkpd[:hdL[3]])])) if almatkpd[hdL[3]:] : titles.append(" ".join([dikanan(tabs," "),dikiri(hdL[3],almatkpd[hdL[3]:])])) titles.append(" ".join([dikanan(tabs," "),dikiri(tabs,phkpd[:hdL[3]])])) if phkpd[hdL[3]:] : titles.append(" ".join([dikanan(tabs," "),dikiri(tabs,phkpd[37:])])) # lines lines=[] # panjang karakter max tiap kolom, to joined by single space lgt = [22,7,8,14,18,21] lineH = ["Description","Tax","Disc (%)","Qty","Unit Price","Net Price"] # format header lines.append(separator) lines.append(' '.join([dikiri(lgt[0],lineH[0]),dikiri(lgt[1],lineH[1]),dikiri(lgt[2],lineH[2]),dikanan(lgt[3],lineH[3]),dikanan(lgt[4],lineH[4]),dikanan(lgt[5],lineH[5])]) ) lines.append(separator) rp = str(data.currency_id.symbol) rml_parser = report_sxw.rml_parse(cr, uid, '', context=context) for line in data.order_line: taxes=[] for tx in line.taxes_id: amt = tx.amount or 0.0 if tx.type == 'percent': taxes.append(" ".join([str(amt*100),"%"])) elif tx.type == 'fixed': taxes.append(" ".join([rp,str(amt)])) else : taxes.append(tx.name) taxes = ",".join(taxes) names = diDiv(lgt[0],line.name) # names = names.split("\n") # import pdb;pdb.set_trace() amt_price_unit = rml_parser.formatLang(line.price_unit, currency_obj=data.currency_id).replace(u'\xa0', u' ') amt_price_stot = rml_parser.formatLang(line.price_subtotal, currency_obj=data.currency_id).replace(u'\xa0', u' ') lines.append(' '.join([ dikiri(lgt[0],names[0]), dikiri(lgt[1],taxes[:lgt[1]]), dikiri(lgt[2],str(line.taxes_str)), dikanan(lgt[3]," ".join([str(line.product_qty),line.product_uom.name])), dikanan(lgt[4],amt_price_unit), dikanan(lgt[5],amt_price_stot) ])) if len(names)>1: names.remove(names[0]) for nm in names: lines.append(dikiri(lgt[0],nm)) # konstruk div for 3 cols footerkiri = [] Lf={'1':tabs,'2':3,'3':19,'4':17} if data.notes2: note = '\n'.join(["Terms & Condition :",data.notes2]) footerkiri += [dikiri(Lf['1'],x) for x in diDiv(tabs,note)] footerkanan1 = [dikiri(Lf['3'],x) for x in ["-------------------","Total Without Taxes", "Taxes","-------------------","Total"]] amt_amount_untax = rml_parser.formatLang(data.amount_untaxed, currency_obj=data.currency_id).replace(u'\xa0', u' ') amt_amount_tax = rml_parser.formatLang(data.amount_tax, currency_obj=data.currency_id).replace(u'\xa0', u' ') amt_amount_tot = rml_parser.formatLang(data.amount_total, currency_obj=data.currency_id).replace(u'\xa0', u' ') footerkanan2 = [dikanan(Lf['4'],x) for x in ["-----------------",amt_amount_untax, amt_amount_tax,"-----------------", amt_amount_tot]] kosong=[] elem = {} elem.update({'1':footerkiri,'2':kosong,'3':footerkanan1,'4':footerkanan2,'kosong':Lf}) elem,L = cekElem(elem) L= max(len(k) for k in elem.values()) i=0 footer = [] while i<L: all=[] for y in zip(x for x in elem.values()): all.append(y[0][i]) S = " ".join(all) footer.append(S) i+=1 # print("\n".join(footer)) ttd = [separator, ditengah(tabs/2," Supplier "," ")+ditengah(tabs/2," Hormat Kami, "," "), "\n\n"+ditengah(tabs/2,"( ________________ )"," ")+ditengah(tabs/2,"( ________________ )"," ")] result = '\n'.join(mainHeader+titles+lines+footer+ttd) self.write(cr,uid,data.id,{'barcode_data': result}) return True