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")), 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 _get_sign_round(self, amount, report): rml_obj = report_sxw.rml_parse(self.cr, self.uid, "", self.context) return_amount = report.round and round(amount, 2) or int(amount) if return_amount > 0: return str(rml_obj.formatLang(return_amount)) if return_amount == 0: return str(0.00) if report.sign == 'no_sign': return str(rml_obj.formatLang(abs(return_amount))) elif report.sign == 'bracket': return '(' + str(rml_obj.formatLang(abs(return_amount))) + ')' else: return str(rml_obj.formatLang(return_amount))
def create_xml(self, cr, uid, ids, datas, context=None): self.pool = pooler.get_pool(cr.dbname) period_obj = self.pool.get('account.period') fiscal_year_obj = self.pool.get('account.fiscalyear') user_obj = self.pool.get('res.users') analytic_obj = self.pool.get('account.analytic.account') datas.get('form', {}).update({"fiscalyear_id": datas.get('form', {}).get('first_fiscalyear')}) fiscalyear = datas.get('form', {}).get('first_fiscalyear') analytic_account_ids = datas.get('form', {}).get('analytic_account_ids', []) or [datas.get('form', {}).get('chart_analytic_account_id')] or [] period_from = datas.get('form', {}).get('period_from', False) and [datas.get('form', {}).get('period_from', False)] or period_obj.search(cr, uid, [('fiscalyear_id', '=', fiscalyear)], context=context, order='date_start', limit=1) period_to = datas.get('form', {}).get('period_to', False) and [datas.get('form', {}).get('period_to', False)] or period_obj.search(cr, uid, [('fiscalyear_id', '=', fiscalyear)], context=context, order='date_start desc', limit=1) year = fiscal_year_obj.browse(cr, uid, fiscalyear, context=context).name title = datas.get('form', {}).get('report_name') == 'summary' and u'تقرير ملخص الموازنة للعام %s' % (year) or \ datas.get('form', {}).get('report_name') == 'flow' and u'التدفقــات النقديـة' period_from = period_from and period_obj.browse(cr, uid, period_from[0], context=context).name or "" period_to = period_to and period_obj.browse(cr, uid, period_to[0], context=context).name or "" self.accuracy = datas.get('form', {}).get('accuracy', 1) self.landscape = datas.get('form',{}).get('landscape',True) self.size = datas.get('form',{}).get('size','A4') self.columns = self.size == 'A4' and 1 or 2 self.columns = self.landscape and self.columns or self.columns*0.66 self.size += (self.landscape and '_landscape' or '_portrait') self.rml_obj = report_sxw.rml_parse(cr, uid, "", context=context) self.type = datas.get('form', {}).get('report_name') usr_company = user_obj.browse(cr, uid, uid, context=context).company_id header_xml = ''' <header> <date>%s</date> <company>%s</company> <accuracy>%s</accuracy> <period_from>%s</period_from> <period_to>%s</period_to> ''' % (str(self.rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), usr_company.name, str(self.accuracy) + ' ' + (usr_company.currency_id.units_name or ' '), period_from, period_to) if datas.get('form', {}).get('report_name') == 'summary': return self.dept_compare_fiscalyear_budget_xml(cr, uid, ids, datas, header_xml + '<title>%s</title></header>' % (title), context=context) elif datas.get('form', {}).get('report_name') == 'flow': xml = '' for analytic_acc in analytic_account_ids: full_title = title + ' - ' + analytic_obj.browse(cr, uid, analytic_acc, context=context).name xml += self.period_compare_budget_xml(cr, uid, ids, datas, header_xml + '<title>%s</title></header>' % (full_title), analytic_acc, context=context) return '''<?xml version="1.0" encoding="UTF-8" ?><report>%s</report>''' % (xml)
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")),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, 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, [] 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': wh += (float((dt - ldt).seconds)/60/60) else: ldt = dt # Week xml representation 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 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")),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 <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, datas, context=None): number = (datas.get('form', False) and datas['form']['number']) or 1 pool = pooler.get_pool(cr.dbname) product_pool = pool.get('product.product') product_uom_pool = pool.get('product.uom') supplier_info_pool = pool.get('product.supplierinfo') workcenter_pool = pool.get('mrp.workcenter') user_pool = pool.get('res.users') bom_pool = pool.get('mrp.bom') pricelist_pool = pool.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.cost_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: 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> """ % (user_pool.browse(cr, uid, uid).company_id.name) config_stop = """ <report-footer>Generated by OpenERP</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 Uom'), _('Supplier Price per Uom')) purchase_price_digits = rml_obj.get_digits(dp='Purchase 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.uom_id.id) 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.cost_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, factor / bom.product_qty) 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): # 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")),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, data, context): obj_dept = pooler.get_pool(cr.dbname).get('hr.department') obj_emp = pooler.get_pool(cr.dbname).get('hr.employee') depts=[] emp_id={} # done={} rpt_obj = pooler.get_pool(cr.dbname).get('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))) 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")),pooler.get_pool(cr.dbname).get('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_xml(self, cr, uid, ids, datas, context=None): self.pool = pooler.get_pool(cr.dbname) period_obj = self.pool.get('account.period') fiscal_year_obj = self.pool.get('account.fiscalyear') user_obj = self.pool.get('res.users') datas.get('form', {}).update( {"fiscalyear_id": datas.get('form', {}).get('first_fiscalyear')}) fiscalyear = datas.get('form', {}).get('first_fiscalyear') period_from = datas.get('form', {}).get('period_from', False) and [ datas.get('form', {}).get('period_from', False) ] or period_obj.search(cr, uid, [('fiscalyear_id', '=', fiscalyear)], context=context, order='date_start', limit=1) period_start_date = period_obj.browse(cr, uid, period_from[0], context=context).date_start period_to = datas.get('form', {}).get('period_to', False) and [ datas.get('form', {}).get('period_to', False) ] or period_obj.search(cr, uid, [('fiscalyear_id', '=', fiscalyear)], context=context, order='date_start desc', limit=1) period_end_date = period_obj.browse(cr, uid, period_to[0], context=context).date_stop year = fiscal_year_obj.browse(cr, uid, fiscalyear, context=context).name title = datas.get('form', {}).get('report_name') == 'compare' and ( (u' مقترح موازنة للعام المالي %s' % (year))) period_from = period_from and period_obj.browse( cr, uid, period_from[0], context=context).name or "" period_to = period_to and period_obj.browse( cr, uid, period_to[0], context=context).name or "" self.accuracy = datas.get('form', {}).get('accuracy', 1) self.landscape = datas.get('form', {}).get('landscape', True) self.size = datas.get('form', {}).get('size', 'A4') self.columns = self.size == 'A4' and 1 or 2 self.columns = self.landscape and self.columns or self.columns * 0.66 self.size += (self.landscape and '_landscape' or '_portrait') self.rml_obj = report_sxw.rml_parse(cr, uid, "", context=context) self.type = datas.get('form', {}).get('report_name') usr_company = user_obj.browse(cr, uid, uid, context=context).company_id period_start_month = datetime.strptime(period_start_date, "%Y-%m-%d").month period_end_month = datetime.strptime(period_end_date, "%Y-%m-%d").month periods = [] for i in range(period_start_month, period_end_month + 2): periods += [i] self.periods = periods header_xml = ''' <header> <date>%s</date> <accuracy>%s</accuracy> <period_from>%s</period_from> <period_to>%s</period_to> <period_start_date>%s</period_start_date> <period_end_date>%s</period_end_date> ''' % (str( self.rml_obj.formatLang(time.strftime("%Y-%m-%d"), date=True)) + ' ' + str(time.strftime("%H:%M")), str(self.accuracy) + ' ' + (usr_company.currency_id.units_name or ' '), period_from, period_to, period_start_date, period_end_date) account_chart = datas.get('form', {}).get('chart_account_id', []) account_child_ids = self._get_children_and_consol( cr, uid, account_chart, 'account.account', context) general_account = self._sort_filter(cr, uid, account_child_ids, context=context) classification_ids = datas.get('form', {}).get('classification_ids', False) xml = '' if general_account == [] or classification_ids == []: xml += self.generate_empty(cr, uid, ids, datas, header_xml + '<title>%s</title></header>' % (title), context=context) else: xml += self.compare_budget(cr, uid, ids, datas, header_xml + '<title>%s</title></header>' % (title), context=context) return xml
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) _append_node('company', pooler.get_pool(self.cr.dbname).get('res.users').browse(self.cr,uid,uid).company_id.name) rpt_obj = pooler.get_pool(self.cr.dbname).get('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] != 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] != 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, data, context=None): partner_id = ids[0] pool = pooler.get_pool(cr.dbname) user_pool = pool.get('res.users') company_id = user_pool.browse(cr, uid, uid).company_id period_from_id = data['form']['period_from_id'] period_to_id = data['form']['period_to_id'] pool_period = pool.get('account.period') period_from = pool_period.browse(cr, uid, period_from_id) period_to = pool_period.browse(cr, uid, period_to_id) pool_partner = pool.get('res.partner') partner = pool_partner.browse(cr, uid, partner_id) date_from = period_from['date_start'] date_to = period_to['date_stop'] rml_obj = report_sxw.rml_parse(cr, uid, pool_period._name, context) rml_obj.localcontext.update({'lang': context.get('lang', False)}) if date_from > date_to: raise osv.except_osv( _('Error'), _('Start period should be smaller than end period')) sql = ''' select per.name as period_name, per.date_start as period_start, per.date_stop as period_stop, sum(inv.amount_untaxed) as total_untaxed, sum(inv.amount_total) as total from account_invoice inv inner join account_period per on inv.period_id = per.id where inv.partner_id = %s and per.date_start >= date(%s) and per.date_stop <= date(%s) and inv.state in ('open', 'paid') group by per.name, per.date_start, per.date_stop order by per.date_start ''' cr.execute(sql, (partner_id, date_from, date_to)) results = cr.dictfetchall() if not results: raise osv.except_osv(_('No Data Available'), _('No records found for your selection!')) xml = '' config_start = """ <config> <date>Data: """ + to_xml( rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d'), date=True)) + """</date> <reportname>STAMPA CLIENTI/FORNITORI</reportname> <company>Azienda: %s</company> <PageSize>210.00mm,297.00mm</PageSize> <PageWidth>595.27</PageWidth> <PageHeight>841.88</PageHeight> <tableSize>60.00mm,80.00mm,40.00mm</tableSize> """ % (company_id.name) config_stop = """ <report-footer>Generated by OpenERP</report-footer> </config> """ partner_type = '' if partner.customer: partner_type += 'Cliente' if partner.customer and partner.supplier: partner_type += '/' if partner.supplier: partner_type += 'Fornitore' partner_ref = partner.ref or '' partner_name = partner.name partner_piva = partner.vat or '' title = """ <row> <col>""" + to_xml(partner_type) + """: """ + to_xml( partner_ref) + """</col> <col>Rag. Soc.: """ + to_xml(partner_name) + """</col> <col>P.IVA: """ + to_xml(partner_piva) + """</col> </row>""" invoice_header = """ <row> <col>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row>""" % (_('Periodo'), _('Fatturato'), _('Fatt. Netto')) xml += "<lines style='total'>" + title + "</lines>" + "<lines style='header'>" + invoice_header + "</lines>" purchase_price_digits = rml_obj.get_digits(dp='Purchase Price') company_currency = company_id.currency_id company_currency_symbol = company_currency.symbol or company_currency.name for period in results: period_name = period['period_name'] total_untaxed = period['total_untaxed'] total = period['total'] xml += """<lines style='lines'><row> <col para='yes'>""" + period_name + """</col> <col f='yes'>""" + rml_obj.formatLang( total, digits=purchase_price_digits) + ' ' + ( company_currency_symbol) + """</col> <col f='yes'>""" + rml_obj.formatLang( total_untaxed, digits=purchase_price_digits) + ' ' + ( company_currency_symbol) + """</col> </row></lines>""" xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>' 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 _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) _append_node( 'company', pooler.get_pool(self.cr.dbname).get('res.users').browse( self.cr, uid, uid).company_id.name) rpt_obj = pooler.get_pool(self.cr.dbname).get('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] != 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] != 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): number = (datas.get('form', False) and datas['form']['number']) or 1 pool = pooler.get_pool(cr.dbname) product_pool = pool.get('product.product') product_uom_pool = pool.get('product.uom') supplier_info_pool = pool.get('product.supplierinfo') workcenter_pool = pool.get('mrp.workcenter') user_pool = pool.get('res.users') bom_pool = pool.get('mrp.bom') pricelist_pool = pool.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: 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> """ % (user_pool.browse(cr, uid, uid).company_id.name) config_stop = """ <report-footer>Generated by OpenERP</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 Uom'), _('Supplier Price per Uom')) purchase_price_digits = rml_obj.get_digits(dp='Purchase 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.uom_id.id) 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, factor / bom.product_qty) 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): # 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")), 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(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 set_context(self, objects, data, ids, report_type=None): super(ar_ap_report_parser, self).set_context(objects, data, ids, report_type) form = self.localcontext['data']['form'] self.user = self.localcontext['user'] self.date_start = data['form']['date_start'] self.date_end = data['form']['date_end'] self.localcontext['date_end'] = self.date_end self.localcontext['title'] = '' purchase_order_pool = self.pool.get('purchase.order') currency_pool = self.pool.get('res.currency') account_invoice_pool = self.pool.get('account.invoice') sale_order_pool = self.pool.get('sale.order') purchase_order_line_pool = self.pool.get('purchase.order.line') rml_obj=report_sxw.rml_parse(self.cr, self.uid, account_invoice_pool._name,context={}) currencys = [] currency_ids = currency_pool.search(self.cr, self.uid, []) currency_objs = currency_pool.browse(self.cr, self.uid, currency_ids, context=None) #硬编码写定以HKD为主汇率 hkd_id = currency_pool.search(self.cr, self.uid, [('name','=','HKD')]) hkd_objs = currency_pool.browse(self.cr, self.uid, hkd_id, context=None) for currency_obj in currency_objs: currency = {'out_invoices':False, 'in_invoices':False, 'out_invoice_current_total':False, 'out_invoice_1_30_total':False, 'out_invoice_31_60_total':False, 'out_invoice_61_90_total':False, 'out_invoice_90_total':False, 'out_invoice_amount_total':False, 'in_invoice_current_total':False, 'in_invoice_1_30_total':False, 'in_invoice_31_60_total':False, 'in_invoice_61_90_total':False, 'in_invoice_90_total':False, 'in_invoice_amount_total':False, 'currency_name':''} account_out_invoice_by_currency_ids = account_invoice_pool.search(self.cr, self.uid, [('currency_id','=',currency_obj.id),('state','=','open'),('type','=','out_invoice')],order="date_due") if account_out_invoice_by_currency_ids: out_invoices = account_invoice_pool.browse(self.cr, self.uid, account_out_invoice_by_currency_ids, context=None) currency['out_invoices'] = out_invoices for out_invoice in out_invoices: date_diff = self.get_date_diff(out_invoice.date_due or self.date_end,self.date_end) if date_diff <=0: currency['out_invoice_current_total'] = currency['out_invoice_current_total'] + out_invoice.amount_total elif 1 <= date_diff <= 30: currency['out_invoice_1_30_total'] = currency['out_invoice_1_30_total'] + out_invoice.amount_total elif 31 <= date_diff <= 60: currency['out_invoice_31_60_total'] = currency['out_invoice_31_60_total'] + out_invoice.amount_total elif 61 <= date_diff <= 90: currency['out_invoice_61_90_total'] = currency['out_invoice_61_90_total'] + out_invoice.amount_total elif date_diff > 90: currency['out_invoice_90_total'] = currency['out_invoice_90_total'] + out_invoice.amount_total currency['out_invoice_amount_total'] = currency['out_invoice_amount_total'] + out_invoice.amount_total account_in_invoice_by_currency_ids = account_invoice_pool.search(self.cr, self.uid, [('currency_id','=',currency_obj.id),('state','=','open'),('type','=','in_invoice')],order="date_due") if account_in_invoice_by_currency_ids: in_invoices = account_invoice_pool.browse(self.cr, self.uid, account_in_invoice_by_currency_ids, context=None) currency['in_invoices'] = in_invoices for in_invoice in in_invoices: date_diff = self.get_date_diff(in_invoice.date_due or self.date_end,self.date_end) if date_diff <=0: currency['in_invoice_current_total'] = currency['in_invoice_current_total'] + in_invoice.amount_total elif 1 <= date_diff <= 30: currency['in_invoice_1_30_total'] = currency['in_invoice_1_30_total'] + in_invoice.amount_total elif 31 <= date_diff <= 60: currency['in_invoice_31_60_total'] = currency['in_invoice_31_60_total'] + in_invoice.amount_total elif 61 <= date_diff <= 90: currency['in_invoice_61_90_total'] = currency['in_invoice_61_90_total'] + in_invoice.amount_total elif date_diff > 90: currency['in_invoice_90_total'] = currency['in_invoice_90_total'] + in_invoice.amount_total currency['in_invoice_amount_total'] = currency['in_invoice_amount_total'] + in_invoice.amount_total if currency['out_invoices'] or currency['in_invoices']: currency['currency_name'] = currency_obj.name #报表头现在硬编码HKD为标准 context = {} context['date']=self.date_end rate = currency_pool._get_conversion_rate(self.cr, self.uid, hkd_objs[0], currency_obj,context) self.localcontext['title'] = self.localcontext['title'] + str(currency_obj.name) +'@ '+str(rml_obj.formatLang(rate)) +' ' currencys.append(currency) self.localcontext['currencys'] = currencys #pre-order pre_order_supplier_invoice_ids = account_invoice_pool.search(self.cr, self.uid, [('state','=','draft'),('type','=','in_invoice')],order="date_due") pre_order_supplier_invoices = account_invoice_pool.browse(self.cr, self.uid, pre_order_supplier_invoice_ids, context=None) pre_orders = [] pre_order = {} for pre_order_supplier_invoice in pre_order_supplier_invoices: if pre_order_supplier_invoice.origin: purchase_order_ids = purchase_order_pool.search(self.cr, self.uid, [('name','=',pre_order_supplier_invoice.origin)],order="date_due") purchase_order = purchase_order_pool.browse(self.cr, self.uid, purchase_order_ids, context=None) purchase_order_line_ids = purchase_order_line_pool.search(self.cr, self.uid, [('order_id','=',purchase_order_ids[0])],order="date_due") purchase_order_lines = purchase_order_line_pool.browse(self.cr, self.uid, purchase_order_line_ids, context=None) pre_order['product'] = purchase_order_lines[0].product_id.name #取第一个Purchase Order Line的产品,可能需要修正 pre_order['purchase_order'] = purchase_order[0] if purchase_order[0].origin: sale_order_ids = sale_order_pool.search(self.cr, self.uid, [('name','=',purchase_order[0].origin)],order="date_due") sale_order = sale_order_pool.browse(self.cr, self.uid, sale_order_ids, context=None) pre_order_customer_invoice_ids = account_invoice_pool.search(self.cr, self.uid, [('origin','=',sale_order[0].name)],order="date_due") if pre_order_customer_invoice_ids: pre_order_customer_invoices = account_invoice_pool.browse(self.cr, self.uid, pre_order_customer_invoice_ids, context=None) pre_order['pre_order_customer_invoice'] = pre_order_customer_invoices[0] pre_orders.append(pre_order) if pre_orders: self.localcontext['pre_orders'] = pre_orders else: self.localcontext['pre_orders'] = False
def create_xml(self, cr, uid, ids, data, context=None): partner_id = ids[0] pool = pooler.get_pool(cr.dbname) user_pool = pool.get('res.users') company_id = user_pool.browse(cr, uid, uid).company_id period_from_id = data['form']['period_from_id'] period_to_id = data['form']['period_to_id'] pool_period = pool.get('account.period') period_from = pool_period.browse(cr, uid, period_from_id) period_to = pool_period.browse(cr, uid, period_to_id) pool_partner = pool.get('res.partner') partner = pool_partner.browse(cr, uid, partner_id) date_from = period_from['date_start'] date_to = period_to['date_stop'] rml_obj=report_sxw.rml_parse(cr, uid, pool_period._name,context) rml_obj.localcontext.update({'lang':context.get('lang',False)}) if date_from > date_to: raise osv.except_osv(_('Error'), _('Start period should be smaller than end period')) sql = ''' select per.name as period_name, per.date_start as period_start, per.date_stop as period_stop, sum(inv.amount_untaxed) as total_untaxed, sum(inv.amount_total) as total from account_invoice inv inner join account_period per on inv.period_id = per.id where inv.partner_id = %s and per.date_start >= date(%s) and per.date_stop <= date(%s) and inv.state in ('open', 'paid') group by per.name, per.date_start, per.date_stop order by per.date_start ''' cr.execute(sql, (partner_id, date_from, date_to)) results = cr.dictfetchall() if not results: raise osv.except_osv(_('No Data Available'), _('No records found for your selection!')) xml = '' config_start = """ <config> <date>Data: """ + to_xml(rml_obj.formatLang(datetime.now().strftime('%Y-%m-%d'),date=True)) + """</date> <reportname>STAMPA CLIENTI/FORNITORI</reportname> <company>Azienda: %s</company> <PageSize>210.00mm,297.00mm</PageSize> <PageWidth>595.27</PageWidth> <PageHeight>841.88</PageHeight> <tableSize>60.00mm,80.00mm,40.00mm</tableSize> """ % (company_id.name) config_stop = """ <report-footer>Generated by OpenERP</report-footer> </config> """ partner_type ='' if partner.customer: partner_type +='Cliente' if partner.customer and partner.supplier: partner_type +='/' if partner.supplier: partner_type +='Fornitore' partner_ref = partner.ref or '' partner_name = partner.name partner_piva = partner.vat or '' title = """ <row> <col>""" + to_xml(partner_type) +""": """ + to_xml(partner_ref) + """</col> <col>Rag. Soc.: """ + to_xml(partner_name) + """</col> <col>P.IVA: """ + to_xml(partner_piva) + """</col> </row>""" invoice_header = """ <row> <col>%s</col> <col t='yes'>%s</col> <col t='yes'>%s</col> </row>""" % (_('Periodo'),_('Fatturato'), _('Fatt. Netto')) xml += "<lines style='total'>" + title + "</lines>" + "<lines style='header'>" + invoice_header + "</lines>" purchase_price_digits = rml_obj.get_digits(dp='Purchase Price') company_currency = company_id.currency_id company_currency_symbol = company_currency.symbol or company_currency.name for period in results: period_name = period['period_name'] total_untaxed = period['total_untaxed'] total = period['total'] xml += """<lines style='lines'><row> <col para='yes'>""" + period_name + """</col> <col f='yes'>""" + rml_obj.formatLang(total, digits=purchase_price_digits) + ' '+ (company_currency_symbol) + """</col> <col f='yes'>""" + rml_obj.formatLang(total_untaxed, digits=purchase_price_digits) +' '+ (company_currency_symbol) + """</col> </row></lines>""" xml = '<?xml version="1.0" ?><report>' + config_start + config_stop + xml + '</report>' return xml
def _rml_parse_data(self, cr, uid, ids, o, context): global local_data str_lines = _amount_text(o.amount) or ['', ''] str_date = _get_date(o.date) parser = rml_parse(cr, uid, 'parser') if o.voucher_type != 'other': title = { 'sale': 'Sale', 'purchase': 'Purchase', 'payment': 'Comprobante de pago', 'receipt': 'Comprobante de cobro', } else: title = { 'sale': 'Sale', 'purchase': 'Purchase', 'payment': 'Comprobante de egreso', 'receipt': 'Comprobante de ingreso', } user_title = { 'sale': 'Sale', 'purchase': 'Purchase', 'payment': 'Pagador', 'receipt': 'Cobrador', } data = {'voucher': o, 'amount': parser.formatLang(o.amount, digits=2), 'beneficiary': _str_2_rml(o.beneficiary), 'nat_str': _str_2_rml(' '.join(str_lines).strip()), 'nat_line_1': _str_2_rml(str_lines[0]), 'nat_line_2': _str_2_rml(str_lines[1]), 'str_date': _str_2_rml(_get_date(o.date)), 'city_date': _str_2_rml('%s, %s' % \ (_get_city(o.company_id.partner_id), str_date[0])), 'date_year': _str_2_rml(str_date[1]), 'restricted': 'NO ENDOSABLE', 'comany_name': _str_2_rml('%s (%s)' % \ (o.company_id.partner_id.name, o.company_id.partner_id.str_rif)), 'main_title': _str_2_rml(title[o.type]), 'nbr_title': _str_2_rml('Nº'), 'number': _str_2_rml(o.number), 'date': parser.formatLang(o.date, date='True'), 'reference': _str_2_rml(o.reference), 'partner': _str_2_rml('%s (%s)' % (o.partner_id.name, o.partner_id.str_rif or 'S/R')), 'name': _str_2_rml(o.name), 'payment_doc': _str_2_rml(_get_type_doc(o.payment_doc)), 'voucher_type': _str_2_rml(_get_type_doc(o.voucher_type)), 'period': _str_2_rml(o.period_id.name), 'journal': _str_2_rml(o.journal_id.name), 'bank_name': _str_2_rml(o.check_id and o.check_id.bank_acc_id.bank_id.name), 'bank_acc_name': _str_2_rml(o.check_id and o.check_id.bank_acc_id.name), 'check_name': o.check_id and o.check_id.full_name, 'user_title': _str_2_rml(user_title[o.type]), 'user_name': _str_2_rml(o.check_id and o.check_id.user_id and o.check_id.user_id.name or o.user_id and o.user_id.name), } lst = [] for l in o.line_ids: factor = 1 if l.type == 'dr' else -1 lst.append((_str_2_rml( '%s (%s)' % (l.name, l.move_line_id and l.move_line_id.invoice and l.move_line_id.invoice.supplier_invoice_number)), _str_2_rml('[%s] %s' % (l.account_id.code, l.account_id.name)), parser.formatLang(l.amount_original, digits=2), parser.formatLang(l.amount_unreconciled, digits=2), parser.formatLang(l.amount * factor, digits=2))) data.update({'line_ids': lst}) lst = [] if o.move_ids: for l in o.move_ids: lst.append((_str_2_rml(l.account_id.code), _str_2_rml(l.account_id.name), parser.formatLang(l.debit, digits=2), parser.formatLang(l.credit, digits=2), _str_2_rml(l.reconcile_id.name))) acc_move = { 'move': _str_2_rml(l.move_id.name), 'ref': _str_2_rml(l.move_id.ref), 'period': _str_2_rml(l.move_id.period_id.name), 'date': parser.formatLang(l.move_id.date, date='True'), 'state': _str_2_rml(l.move_id.state), } data.update({'move_ids': lst, 'acc_move': acc_move}) local_data = data return data
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(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 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 = context.get('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, [] 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': wh += (dt - ldt).seconds / 60 / 60 else: ldt = dt # Week xml representation # wh = hour2str(wh) today_xml = '<day num="%s"><wh>%s</wh></day>' % ( (today - month).days + 1, round(wh, 2)) 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('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) 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