def test_generate_fod(self): "Testing generate fod" thisdir = os.path.dirname(__file__) filepath = os.path.join(thisdir, 'test.fodt') with open(filepath, mode='rb') as source: oot = Template(source) oot.generate(**self.data)
def generate(template_path, data_file, out_file=None, year=None): """ Generate a week calendar for an entire year in odt format. Args: template_path (str): The file path of the template to render. data_file (str): The path of the configuration to load. out_file (io.IOBase): A file-like object to write the calendar to. year (int): The year to render the calendar for. A year specified in the data_file is used as a fallback value. Raises: .BadConfigError: If the given configuration file is missing configurations. """ with open(data_file) as f: calendar_data = yaml.load(f, yaml.Loader) try: year = year or calendar_data['year'] birthdays = calendar_data['birthdays'] weddings = calendar_data['weddings'] special_dates = calendar_data['special dates'] except KeyError: raise BadConfigError() weeks = create_weeks_for_year(year, birthdays, weddings, special_dates) template = Template(source=None, filepath=template_path) generated = template.generate(weeks=weeks) data = generated.render().getvalue() if not out_file: out_file = open('calendar-{:d}.odt'.format(year), 'wb') out_file.write(data)
def setUp(self): thisdir = os.path.dirname(__file__) filepath = os.path.join(thisdir, 'test.odt') self._source = open(filepath, mode='rb') self.oot = Template(self._source) self.data = { 'first_name': u'Trente', 'last_name': u'Møller', 'ville': u'Liège', 'friends': [{ 'first_name': u'Camille', 'last_name': u'Salauhpe' }, { 'first_name': u'Mathias', 'last_name': u'Lechat' }], 'hobbies': [u'Music', u'Dancing', u'DJing'], 'animals': [u'Felix da housecat', u'Dog eat Dog'], 'images': [(open(os.path.join(thisdir, 'one.jpg'), 'rb'), 'image/jpeg', None, None, 'One'), (open(os.path.join(thisdir, 'two.png'), 'rb'), 'image/png', '2cm', '2.2cm', 'Two')], 'oeuf': open(os.path.join(thisdir, 'egg.jpg'), 'rb'), 'footer': u'We sell stuff' }
def make(self, metadatas): raw = [] with open(self["input"]) as csvfile: raw = sorted(list(csv.DictReader(csvfile)), key=lambda x: self._sortKey(x)) data = self._makeGroups(raw, self.get("groups", [])) with open(self["output"], "wb") as outfile: template = Template(source='', filepath=self["template"]) doc = template.generate(data=data, meta=metadatas) outfile.write(doc.render().getvalue())
def generate_odf(filename, template_path, data, tmp_path, uuid): uniq_tmp = tmp_path + '/' + uuid if not os.path.exists(tmp_path): os.makedirs(tmp_path) if not os.path.exists(uniq_tmp): os.makedirs(uniq_tmp) basic = Template(source='', filepath=template_path) with open(uniq_tmp + '/' + filename, 'wb') as file: file.write(basic.generate(o=data).render().getvalue())
def render_template(self): """Returns document like BytesIO object and new filename""" template_name, template_ext = self.template.filename.split('.', 1) if self.ext == template_ext and self.ext in ALLOWED_EXTENSIONS: basic = Template(source=self.template, filepath='') basic_generated = basic.generate(o=self.data).render() document = BytesIO(basic_generated.getvalue()) filename = self.new_filename(template_name) return document, filename else: raise DocumentWorkerException('Incorrect extension!')
def generate(table_name, nb=DEFAULT_Q_NB, scheme=None, oldest_prevail=False, output=None, force=False, tpl=None, edit_after=True, use_previous=False): """ Generate a new document using n data from the table and the matching template. """ if use_previous: sw_data = sweepstakes.load_sweepstake(int(table_name)) table_name, rows = sw_data[0], sw_data[1:] table_name = table_name[0] if len(rows[0]) != len(database.get_cols(table_name)): raise ColumnsDoNotMatchError( len(database.get_cols(table_name)), len(rows[0]), table_name, database.get_cols(table_name), sweepstakes._get_sweepstake_name(use_previous)) if tpl is None: tpl_name = table_name else: if not os.path.isfile(template.path(tpl)): raise NotFoundError(f'Cannot find template file: {tpl}') tpl_name = tpl if output is None: output = f'{table_name}.{TEMPLATE_EXT}' if os.path.exists(output) and not force: overwrite = terminal.ask_yes_no(f'Output file {output} already ' f'exists, overwrite it?') if not overwrite: raise CommandCancelledError('generate') if not use_previous: rows = database.draw_rows(table_name, nb, oldest_prevail=oldest_prevail) data = _process_data(rows, scheme=scheme) template.sanitize(template.path(tpl_name)) basic = Template(source='', filepath=template.path(tpl_name)) basic_generated = basic.generate(o=data).render() with open(output, 'wb') as f: f.write(basic_generated.getvalue()) if edit_after: edit(output)
def form(): if request.method == 'POST': classData = request.get_json(force=True) class Schedules(dict): testingCounter = 0 contentCounter = -1 yearCounter = -1 monthIntervals = [1] monthNames = [] years = [] def __init__(self, classData): self.classData = classData def monthNumberToName(monthNumber): if monthNumber == '01': return 'January' elif monthNumber == '02': return 'February' elif monthNumber == '03': return 'March' elif monthNumber == '04': return 'April' elif monthNumber == '05': return 'May' elif monthNumber == '06': return 'June' elif monthNumber == '07': return 'July' elif monthNumber == '08': return 'August' elif monthNumber == '09': return 'September' elif monthNumber == '10': return 'October' elif monthNumber == '11': return 'November' elif monthNumber == '12': return 'December' monthNames.append(monthNumberToName(classData[0]['start'][5:7])) years.append(classData[0]['start'][0:4]) monthIntervalsCounter = 1 for index, item in enumerate(classData): monthIntervalsCounter += 1 try: if item['start'][5:7] != classData[index + 1]['start'][5:7]: monthIntervals.append(monthIntervalsCounter) monthNames.append( monthNumberToName(classData[index + 1]['start'][5:7])) # if item['start'][0:4] != classData[index + 1]['start'][0:4]: years.append(classData[index + 1]['start'][0:4]) except: continue @property def testing(self): Schedules.testingCounter += 1 for i in Schedules.monthIntervals: if Schedules.testingCounter == i: return True return False @property def content(self): Schedules.contentCounter += 1 return Schedules.monthNames[Schedules.contentCounter] @property def year(self): Schedules.yearCounter += 1 return Schedules.years[Schedules.yearCounter] sched = Schedules(classData) basic = Template(source='', filepath='template-schedules.odt') open('app/static/generated-iftest.odt', 'wb').write(basic.generate(o=sched).render().getvalue()) return str(classData) return render_template('form.html') # [{'start': '2018-12-12', # 'end': '2018-12-13', # 'length': '6 weeks', # 'course': 'Beg. Obedience', # 'price': '$140', # 'city': 'Glendora', # 'preregister': 'Pre-Registration Required! Call (999) 222-3333', # 'time': '6PM - 7PM', # 'address': '555 A St, 98821', # 'note': 'No dogs at first meeting!'}, # {'start': '2019-01-16', # 'end': '2019-02-13', # 'length': '4 weeks', # 'course': 'Beg. Obedience', # 'price': '$180', # 'city': 'Upland', # 'preregister': 'Pre-Registration Required! Call (999) 555-3333', # 'time': '6PM - 7PM', # 'address': '555 A St, 98821', # 'note': 'No dogs at first meeting!'}, # {'start': '2019-01-16', # 'end': '2018-12-13', # 'length': '6 weeks', # 'course': 'Beg. Obedience', # 'price': '$140', # 'city': 'Glendora', # 'preregister': 'Pre-Registration Required! Call (999) 222-3333', # 'time': '6PM - 7PM', # 'address': '555 A St, 98821', # 'note': 'No dogs at first meeting!'}, # {'start': '2019-01-18', # 'end': '2018-12-13', # 'length': '6 weeks', # 'course': 'Beg. Obedience', # 'price': '$140', # 'city': 'Glendora', # 'preregister': 'Pre-Registration Required! Call (999) 222-3333', # 'time': '6PM - 7PM', # 'address': '555 A St, 98821', # 'note': 'No dogs at first meeting!'}, # {'start': '2019-02-16', # 'end': '2018-12-13', # 'length': '6 weeks', # 'course': 'Beg. Obedience', # 'price': '$140', # 'city': 'Glendora', # 'preregister': 'Pre-Registration Required! Call (999) 222-3333', # 'time': '6PM - 7PM', # 'address': '555 A St, 98821', # 'note': 'No dogs at first meeting!'}]
# from relatorio.templates.opendocument import Template # from data import sched # basic = Template(source='', filepath='schedules-template.odt') # basic_generated = basic.generate(o=sched).render() # file('generated-schedules.odt', 'wb').write(basic_generated.getvalue()) # basic = Template(source='', filepath='schedules-template.odt') # file('generated-schedules.odt', 'wb').write(basic.generate(o=sched).render().getvalue()) from common import inv from relatorio.templates.opendocument import Template basic = Template(source='', filepath='basic.odt') open('bonham_basic.odt', 'wb').write(basic.generate(o=inv).render().getvalue())
def download_stock_picking(stock_picking, model, type_document_partner_it, stock_picking_id, filename=None, **kw): cr, uid, context = request.cr, request.uid, request.context stock_picking = request.registry[model] stock_picking = stock_picking.browse(cr, uid, int(stock_picking_id), context) lines = [] i = 0 for item in stock_picking.move_lines: codigo = "" description = "" unidad_de_medida = "" i = i + 1 if item.product_id.default_code: codigo = item.product_id.default_code if item.name: description = str(item.name).upper() if item.product_uom.name: unidad_de_medida = item.product_uom.name lines.append({ "item": i, "codigo": codigo, "description": description, "qty": int(item.product_qty), "unit_uom": unidad_de_medida, "peso": "", }) #verificar si existen datos y poner "- -" para que no salga False date = "" min_date = "" origin_address = "" delivery_address_id = "" name = "" nro_documento = "" vehicle_transport = "" name_transport = "" addres_transport = "" ruc_transport = "" type_document_partner_it = "" delivery_address = "" if stock_picking.date: date = str(stock_picking.date)[0:11] if stock_picking.min_date: min_date = str(stock_picking.min_date)[0:11] if stock_picking.origin_address_id.street: origin_address = str(stock_picking.origin_address_id.street)[0:92] if stock_picking.delivery_address_id.street: delivery_address = str(stock_picking.delivery_address_id.street)[0:92] if stock_picking.partner_id.name: name = str(stock_picking.partner_id.name) if stock_picking.partner_id.nro_documento: nro_documento = stock_picking.partner_id.nro_documento if stock_picking.driver_id.vehicle_id.model_id.brand_id.name != False and stock_picking.driver_id.vehicle_id.license_plate != False: vehicle_transport = str(stock_picking.driver_id.vehicle_id.model_id.brand_id.name) + " - " + str(stock_picking.driver_id.vehicle_id.license_plate) if stock_picking.carrier_id.partner_id.name: name_transport = stock_picking.carrier_id.partner_id.name if stock_picking.carrier_id.partner_id.street: addres_transport = str(stock_picking.carrier_id.partner_id.street) if stock_picking.carrier_id.partner_id.nro_documento: ruc_transport = stock_picking.carrier_id.partner_id.nro_documento if stock_picking.picking_type_id.name: type_document_partner_it = stock_picking.picking_type_id.name datas = { "date": date, "min_date": min_date, "origin_address": origin_address, "delivery_address": delivery_address, "name": name, "nro_documento": nro_documento, "vehicle_transport": vehicle_transport, "name_transport": name_transport, "addres_transport": addres_transport, "constancia": "", "ruc_transport": ruc_transport, "nro_licencia": "", "nro_constancia": "", "lines": lines, #"type_document_partner_it": type_document_partner_it, "null": "" } stock_picking_path = openerp.modules.get_module_resource('fxo_mv_print_documents','templates', "stock_picking.odt") if not stock_picking_path: error = { 'code': 200, 'message': "Odoo Server Error", 'data': "Not found file template in module!." } return werkzeug.exceptions.InternalServerError(simplejson.dumps(error)) try: basic = Template(source="", filepath=stock_picking_path) except: error = { 'code': 200, 'message': "Odoo Server Error", 'data': "You do not have permission to read\nfile template!." } return werkzeug.exceptions.InternalServerError(simplejson.dumps(error)) basic_generated = basic.generate(o=datas).render() filecontent = basic_generated.getvalue() if not filecontent: return request.not_found() else: if not filename: filename = '%s_%s' % (model.replace('.', '_'), wid) return request.make_response(filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
from relatorio.templates.opendocument import Template from data import sched # basic = Template(source='', filepath='schedules-template.odt') # basic_generated = basic.generate(o=sched).render() # file('generated-schedules.odt', 'wb').write(basic_generated.getvalue()) basic = Template(source='', filepath='schedules-template-p-l.odt') open('generated-iftest.odt', 'wb').write(basic.generate(o=sched).render().getvalue()) # from common import inv # from relatorio.templates.opendocument import Template # basic = Template(source='', filepath='basic.odt') # open('bonham_basic.odt', 'wb').write(basic.generate(o=inv).render().getvalue())
from relatorio.templates.opendocument import Template from exdata import inv # basic = Template(source='', filepath='schedules-template.odt') # basic_generated = basic.generate(o=sched).render() # file('generated-schedules.odt', 'wb').write(basic_generated.getvalue()) basic = Template(source='', filepath='from-basic-nfor.odt') open('generated-ex-nfor.odt', 'wb').write(basic.generate(o=inv).render().getvalue()) # from common import inv # from relatorio.templates.opendocument import Template # basic = Template(source='', filepath='basic.odt') # open('bonham_basic.odt', 'wb').write(basic.generate(o=inv).render().getvalue())
def generate(self, *args, **kwargs): self.parent._print("*" * 10, " generate ", "*" * 10) self.parent._print(args) self.parent._print(kwargs) self.parent._print("*" * 10, " generate ", "*" * 10) doc_type = kwargs.get('doc_type') doc_number = kwargs.get('doc_number') data = kwargs.get('data') answer = { "params": args, "kwargs": kwargs, } if doc_type and doc_number and not data: #пришел документ и его номер, достаем данные из базы, делаем обработку if doc_type == 'shipment': doc_gen = Shipment data = self._generate_short_shipment(doc_number) elif doc_type == 'arrival': doc_gen = Arrival data = self._generate_short_arrival(doc_number) elif doc_type == 'rest': doc_gen = Rest data = self._generate_short_rest(doc_number) elif doc_type == 'movement': doc_gen = Movement data = self._generate_short_movement(doc_number) elif doc_type == 'balance': doc_gen = Balance data = self._generate_balance() if data: #есть данные inv = doc_gen(**data) zip_path = os.path.dirname( os.path.dirname(os.path.abspath(__file__))) with zipfile.ZipFile(zip_path, mode='r') as _zf: _zf.extract(f'doc_tmpl/{inv.doc_template}', path=self.temp_dir) t_path = os.path.join(self.temp_dir, 'doc_tmpl', inv.doc_template) basic = Template(source='', filepath=t_path) basic_generated = basic.generate(o=inv).render() fn = os.path.join(self.temp_dir, self.gen_file_name(doc_type)) file_data = basic_generated.getvalue() with open(fn, 'wb') as _f: _f.write(file_data) md5 = self.parent.filesave(fn) l_file_name = os.path.basename(fn).replace('.ods', '') link_name = f"""https://sklad71.org/filehash/{l_file_name}.pdf?{md5}""" print(link_name) bi = base64.b64encode(file_data) bi = bi.decode() # print(bi) # print(len(bi)) answer = { "params": args, "kwargs": kwargs, "timing": { "sql": 0, "process": 0 }, "data": { "link": link_name, "file_name": os.path.basename(fn), "binary": bi } } return answer
def product_movement(self, *args, **kwargs): self.parent._print("*" * 10, " product_movement ", "*" * 10) self.parent._print(args) self.parent._print(kwargs) self.parent._print("*" * 10, " product_movement ", "*" * 10) doc_type = 'products_movements' date1 = kwargs.get('date1') date2 = kwargs.get('date2') arr_fg = kwargs.get('arr_fg') dep_fg = kwargs.get('dep_fg') item_id = kwargs.get('item_id') answer = { "params": args, "kwargs": kwargs, } d_data = [] a_data = [] sql_move = f"""select jmh.n_number as doc_number, jmh.n_dt_invoice as doc_date, '' as suppl, rp.n_name as point, 0, (jmb.n_product->'n_amount')::text::numeric as amount, (select c_name from ref_products where c_id = {item_id}) from journals_movements_bodies jmb join journals_movements_headers jmh on jmb.n_doc_id = jmh.n_id join ref_partners rp ON rp.n_id = jmh.n_recipient where (jmb.n_product->'n_balance_id')::text in (select jpb.n_id::text from journals_products_balance jpb where jpb.n_product_id = {item_id}) and jmb.n_deleted=false and jmh.n_dt_invoice >= '{date1}'::date and jmh.n_dt_invoice <= '{date2}'::date """ sql_arr = f"""select jah.n_number as doc_number, jah.n_dt_invoice as doc_date, rp.n_name as suppl, '' as point, (jab.n_product->'n_amount')::text::numeric as amount, 0, (select c_name from ref_products where c_id = {item_id}) from journals_arrivals_bodies jab join journals_arrivals_headers jah on jab.n_doc_id = jah.n_id join ref_partners rp ON rp.n_id = jah.n_supplier where (jab.n_product->'n_product')::text = '{item_id}' and jab.n_deleted=false and jah.n_dt_invoice >= '{date1}'::date and jah.n_dt_invoice <= '{date2}'::date """ sqls = [] if not arr_fg and not dep_fg: return answer if arr_fg: sqls.append(sql_arr) if dep_fg: sqls.append(sql_move) sqls = '\nunion all\n'.join(sqls) sql = f"""select * from ( {sqls} ) as aa order by doc_date asc, doc_number """ # print(sql) a_data = self.parent._request(sql) if a_data: data = { 'lines': [], 'tovar': a_data[0][6], 'date1': datetime.datetime.strptime( date1, '%Y-%m-%d %H:%M:%S').strftime('%d-%m-%y'), 'date2': datetime.datetime.strptime( date2, '%Y-%m-%d %H:%M:%S').strftime('%d-%m-%y'), 'arr_total': 0, 'dep_total': 0, } for i, row in enumerate(a_data, 1): d = datetime.datetime.strptime(row[1], '%Y-%m-%d') r = { 'item': { 'doc': row[0], 'date': d.strftime('%d-%m-%y'), 'suppl': row[2], 'recip': row[3], 'arriv': row[4] or '', 'depart': row[5] or '' } } data['lines'].append(r) ta = sum([ int(i['item']['arriv']) if i['item']['arriv'] != '' else 0 for i in data['lines'] ]) td = sum([ int(i['item']['depart']) if i['item']['depart'] != '' else 0 for i in data['lines'] ]) data['arr_total'] = ta data['dep_total'] = td inv = Prod_movements(**data) zip_path = os.path.dirname( os.path.dirname(os.path.abspath(__file__))) with zipfile.ZipFile(zip_path, mode='r') as _zf: _zf.extract(f'doc_tmpl/{inv.doc_template}', path=self.temp_dir) t_path = os.path.join(self.temp_dir, 'doc_tmpl', inv.doc_template) basic = Template(source='', filepath=t_path) basic_generated = basic.generate(o=inv).render() fn = os.path.join(self.temp_dir, self.gen_file_name(doc_type)) file_data = basic_generated.getvalue() with open(fn, 'wb') as _f: _f.write(file_data) md5 = self.parent.filesave(fn) l_file_name = os.path.basename(fn).replace('.ods', '') link_name = f"""https://sklad71.org/filehash/{l_file_name}.pdf?{md5}""" print(link_name) bi = base64.b64encode(file_data) bi = bi.decode() # print(bi) # print(len(bi)) answer = { "params": args, "kwargs": kwargs, "timing": { "sql": 0, "process": 0 }, "data": { "link": link_name, "file_name": os.path.basename(fn), "binary": bi } } return answer
def download_document(invoice, model, type_document_partner_it, inv_id, filename=None, **kw): cr, uid, context = request.cr, request.uid, request.context invoice = request.registry[model] invoice = invoice.browse(cr, uid, int(inv_id), context) picking_name = "" if invoice.picking_ids: pickings = [i.nro_documento for i in invoice.picking_ids] if i.nro_documento: picking_name = ", ".join(pickings) order_name = "" if invoice.sale_ids: orders = [i.name for i in invoice.sale_ids] if i.name: order_name = ", ".join(orders) lines = [] for item in invoice.invoice_line: description = "" codigo = "" if item.name: description = str(item.name).upper() if item.product_id.default_code: codigo = item.product_id.default_code lines.append({ "codigo": codigo, "product": item.product_id.name, "description": description, "qty": int(item.quantity), "price_unit": item.price_unit, "price_subtotal": '{:,.2f}'.format(item.price_subtotal), "price_subtotal_igv": '{:,.2f}'.format(item.invoice_line_tax_id.amount * item.price_subtotal + item.price_subtotal) }) if(invoice.tax_line != False): igv = 18 else: igv = 0 #Validacion de datos name ="" street = "" nro_documento = "" date_invoice = "" day = "" month = "" month_number = "" year = "" y = "" payment_term = "" user = "" doc_modificado = "" nro_doc_modificado = "" fecha_doc_modificado = "" informacion_adicional = "" tipo_nd = "" number_invoice = "" if invoice.number: number_invoice = invoice.number if invoice.partner_id.name: name = invoice.partner_id.name if invoice.partner_id.street: street = str(invoice.partner_id.street)[:90].upper() if invoice.partner_id.nro_documento: nro_documento = invoice.partner_id.nro_documento if invoice.date_invoice: date_invoice=invoice.date_invoice day = time.strftime('%d', time.strptime(invoice.date_invoice,'%Y-%m-%d')) month = str(time.strftime('%B', time.strptime(invoice.date_invoice,'%Y-%m-%d'))).upper() month_number = str(time.strftime('%m', time.strptime(invoice.date_invoice,'%Y-%m-%d'))).upper() year = time.strftime('%y', time.strptime(invoice.date_invoice,'%Y-%m-%d')) y = time.strftime('%y', time.strptime(invoice.date_invoice,'%Y-%m-%d'))[1] if invoice.payment_term: payment_term = str(invoice.payment_term.name).upper() if invoice.user_id.name: user = str(invoice.user_id.name).upper() datas = { "number": number_invoice, "name": name, "street": street, "nro_documento": nro_documento, "date_invoice": date_invoice, "guia": "", "day": day, "month": month, "month_number": month_number, "year": year, "y": y, "picking_name": picking_name, "order_name": order_name, "lines": lines, "payment_term": payment_term, "a_untaxed": 'S/{:,.2f}'.format(invoice.amount_untaxed), "igv": igv, "a_tax": 'S/{:,.2f}'.format(invoice.amount_tax), "a_total": 'S/{:,.2f}'.format(invoice.amount_total), "user": user, "number2letter": number_to_letter(str('{0:.2f}'.format(invoice.amount_total))) + " SOLES", ################################## "prueba": "", "null": "", } if "invoice" == type_document_partner_it: invoice_path = openerp.modules.get_module_resource('fxo_mv_print_documents','templates', "invoice.odt") if "ticket" == type_document_partner_it: invoice_path = openerp.modules.get_module_resource('fxo_mv_print_documents','templates', "ticket.odt") if not invoice_path: error = { 'code': 200, 'message': "Odoo Server Error", 'data': "Not found file template in module!." } return werkzeug.exceptions.InternalServerError(simplejson.dumps(error)) try: basic = Template(source="", filepath=invoice_path) except: error = { 'code': 200, 'message': "Odoo Server Error", 'data': "You do not have permission to read\nfile template!." } return werkzeug.exceptions.InternalServerError(simplejson.dumps(error)) basic_generated = basic.generate(o=datas).render() filecontent = basic_generated.getvalue() if not filecontent: return request.not_found() else: if not filename: filename = '%s_%s' % (model.replace('.', '_'), wid) return request.make_response(filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])