示例#1
0
 def print_shipping_label_clicked(self, button):
     contact = Item()
     self.cursor.execute(
         "SELECT name, address, city, state, zip, phone, "
         "fax, email FROM contacts WHERE id = %s", (self.contact_id, ))
     for row in self.cursor.fetchall():
         contact.name = row[0]
         contact.street = row[1]
         contact.city = row[2]
         contact.state = row[3]
         contact.zip = row[4]
         contact.phone = row[5]
         contact.fax = row[6]
         contact.email = row[7]
     company = Item()
     self.cursor.execute("SELECT * FROM company_info")
     for row in self.cursor.fetchall():
         company.name = row[1]
         company.street = row[2]
         company.city = row[3]
         company.state = row[4]
         company.zip = row[5]
         company.country = row[6]
         company.phone = row[7]
         company.fax = row[8]
         company.email = row[9]
         company.website = row[10]
     data = dict(contact=contact, company=company)
     from py3o.template import Template
     label_file = "/tmp/contact_label_template.odt"
     t = Template("./templates/contact_label_template.odt", label_file,
                  True)
     t.render(data)  #the data holds all the info of the invoice
     subprocess.call("libreoffice " + label_file, shell=True)
    def _create_single_report(self, model_instance, data, save_in_attachment):
        """ This function to generate our py3o report
        """
        self.ensure_one()
        result_fd, result_path = tempfile.mkstemp(suffix='.ods',
                                                  prefix='p3o.report.tmp.')
        tmpl_data = self.get_template(model_instance)

        in_stream = StringIO(tmpl_data)
        with closing(os.fdopen(result_fd, 'w+')) as out_stream:
            template = Template(in_stream, out_stream, escape_false=True)
            localcontext = self._get_parser_context(model_instance, data)
            template.render(localcontext)
            out_stream.seek(0)
            tmpl_data = out_stream.read()

        if self.env.context.get('report_py3o_skip_conversion'):
            return result_path

        result_path = self._convert_single_report(result_path, model_instance,
                                                  data)

        if len(model_instance) == 1:
            self._postprocess_report(result_path, model_instance.id,
                                     save_in_attachment)

        return result_path
示例#3
0
    def print_time_sheet(self):
        from py3o.template import Template  #import for every invoice or there is
        #an error about invalid magic header numbers

        self.time_card_name = "/tmp/time_card_" + self.name.split()[0]
        self.time_card_odt = self.time_card_name + ".odt"
        self.time_card_pdf = self.time_card_name + ".pdf"

        #self.tmp_timecard_file = "/tmp/" + self.document_odt
        t = Template("./templates/time_card_template.odt", self.time_card_odt,
                     True)
        t.render(
            self.data
        )  #the self.data holds all the info to be passed to the template

        subprocess.call("odt2pdf " + self.time_card_odt, shell=True)
        p = printing.Operation(settings_file='time_card',
                               file_to_print=self.time_card_pdf,
                               parent=self.window)
        if self.print_directly == False:
            result = p.print_dialog()
        else:
            result = p.print_directly()

        f = open(self.time_card_pdf, 'rb')
        dat = f.read()
        f.close()
        self.cursor.execute(
            "UPDATE payroll.pay_stubs SET timecard_pdf = %s WHERE id = %s",
            (dat, self.paystubs_id))
 def generate_label(self):
     label = Item()
     label.aisle = self.get_object('entry5').get_text()
     label.cart = self.get_object('entry6').get_text()
     label.rack = self.get_object('entry7').get_text()
     label.shelf = self.get_object('entry8').get_text()
     label.cabinet = self.get_object('entry9').get_text()
     label.drawer = self.get_object('entry10').get_text()
     label.bin = self.get_object('entry11').get_text()
     self.cursor.execute(
         "SELECT name, description, barcode FROM products "
         "WHERE id = (%s)", [self.product_id])
     for row in self.cursor.fetchall():
         label.name = row[0]
         label.description = row[1]
         label.code128 = barcode_generator.makeCode128(row[2])
         label.barcode = row[2]
     price = pricing.product_retail_price(self.product_id)
     label.price = '${:,.2f}'.format(price)
     data = dict(label=label)
     from py3o.template import Template
     self.label_file = "/tmp/product_label.odt"
     t = Template(template_dir + "/product_label_template.odt",
                  self.label_file)
     t.render(data)
     DB.rollback()
示例#5
0
    def test_variable_type_checking(self):
        template_name = pkg_resources.resource_filename(
            'py3o.template', 'tests/templates/py3o_ods_variable_type.ods')

        outname = get_secure_filename()

        template = Template(template_name, outname)

        data_dict = {
            'items': [
                Mock(val1=10, val2='toto'),
                Mock(val1=50.12, val2='titi'),
            ]
        }

        template.render(data_dict)
        outodt = zipfile.ZipFile(outname, 'r')

        content_list = lxml.etree.parse(
            BytesIO(outodt.read(template.templated_files[0])))

        result_a = lxml.etree.tostring(
            content_list,
            pretty_print=True,
        ).decode('utf-8')

        result_e = open(
            pkg_resources.resource_filename(
                'py3o.template',
                'tests/templates/py3o_ods_variable_type_result.xml')).read()

        result_a = result_a.replace("\n", "").replace(" ", "")
        result_e = result_e.replace("\n", "").replace(" ", "")

        assert result_a == result_e
示例#6
0
    def test_input_fields_with_control(self):
        template_name = pkg_resources.resource_filename(
            "py3o.template",
            "tests/templates/py3o_template_for_loop_input_field.odt",
        )

        outname = get_secure_filename()

        template = Template(template_name, outname)

        data_dict = {"items": ["one", "two", "three"]}

        template.render(data_dict)
        outodt = zipfile.ZipFile(outname, "r")

        content_list = lxml.etree.parse(
            BytesIO(outodt.read(template.templated_files[0]))
        )

        result_a = lxml.etree.tostring(content_list, pretty_print=True).decode(
            "utf-8"
        )

        result_e = open(
            pkg_resources.resource_filename(
                "py3o.template",
                "tests/templates/input_fields_for_loop_result.xml",
            )
        ).read()

        result_a = result_a.replace("\n", "").replace(" ", "")
        result_e = result_e.replace("\n", "").replace(" ", "")

        assert result_a == result_e
示例#7
0
 def populate_template_clicked(self, button):
     from py3o.template import Template
     product_list = dict()
     self.cursor.execute("SELECT "
                         "'name'||p.barcode, p.name, "
                         "'price'||p.barcode, price::money "
                         "FROM products AS p "
                         "JOIN products_markup_prices AS pmp "
                         "ON pmp.product_id = p.id "
                         "JOIN customer_markup_percent AS cmp "
                         "ON cmp.id = pmp.markup_id "
                         "WHERE (p.catalog, cmp.standard) = (True, True)")
     for row in self.cursor.fetchall():
         name_id = row[0]
         name = row[1]
         price_id = row[2]
         price = row[3]
         product_list[name_id] = name
         product_list[price_id] = price
     catalog_file = "/tmp/catalog.odt"
     t = Template(main.template_dir + "/catalog_template.odt", catalog_file,
                  False)
     try:
         t.render(
             product_list)  #the product_list holds all the catalog info
     except Exception as e:
         print(e)
         dialog = Gtk.MessageDialog(self.window, 0, Gtk.MessageType.ERROR,
                                    Gtk.ButtonsType.CLOSE, e)
         dialog.run()
         dialog.destroy()
         return
     subprocess.Popen(["soffice", catalog_file])
示例#8
0
def gera_pdf_boletos(lista_boletos, template_boleto=None):
    if template_boleto is None:
        boleto = lista_boletos[0]

        if boleto.template_boleto is not None:
            if isinstance(boleto.template_boleto, basestring):
                template_boleto = BytesIO().write(
                    open(boleto.arquivo_template_boleto, 'rb').read())
            else:
                template_boleto = boleto.template_boleto
        else:
            template_boleto = boleto.banco.template_boleto

    arquivo_renderizado = tempfile.NamedTemporaryFile(delete=False)
    arquivo_pdf = arquivo_renderizado.name + '.pdf'

    template = Template(template_boleto, arquivo_renderizado.name)
    template.render({'boletos': lista_boletos})
    sh.libreoffice('--headless', '--invisible', '--convert-to', 'pdf',
                   '--outdir', '/tmp', arquivo_renderizado.name)

    pdf = open(arquivo_pdf, 'rb').read()

    os.remove(arquivo_pdf)
    os.remove(arquivo_renderizado.name)

    return pdf
示例#9
0
def compile_template(instance, template, additionnal_context=None):
    """
    Fill the given template with the instance's datas and return the odt file

    For every instance class, common values are also inserted in the context
    dict (and so can be used) :

        * config values

    :param obj instance: the instance of a model (like Userdatas, Company)
    :param template: the template object to use
    :param dict additionnal_context: A dict containing datas we'd like to add to
    the py3o compilation template
    :return: a stringIO object filled with the resulting odt's informations
    """
    py3o_context = get_compilation_context(instance)

    if additionnal_context is not None:
        py3o_context.update(additionnal_context)

    output_doc = BytesIO()

    odt_builder = Template(template, output_doc)
    odt_builder.render(py3o_context)

    return output_doc
示例#10
0
 def print_10_env_clicked(self, button):
     contact = Item()
     self.cursor.execute(
         "SELECT name, address, city, state, zip, phone, "
         "fax, email FROM contacts WHERE id = %s", (self.contact_id, ))
     for row in self.cursor.fetchall():
         contact.name = row[0]
         contact.street = row[1]
         contact.city = row[2]
         contact.state = row[3]
         contact.zip = row[4]
         contact.phone = row[5]
         contact.fax = row[6]
         contact.email = row[7]
     company = Item()
     self.cursor.execute("SELECT * FROM company_info")
     for row in self.cursor.fetchall():
         company.name = row[1]
         company.street = row[2]
         company.city = row[3]
         company.state = row[4]
         company.zip = row[5]
         company.country = row[6]
         company.phone = row[7]
         company.fax = row[8]
         company.email = row[9]
         company.website = row[10]
     data = dict(contact=contact, company=company)
     from py3o.template import Template
     env_file = "/tmp/env10_template.odt"
     t = Template(main.template_dir + "env10_template.odt", env_file, True)
     t.render(data)  #the data holds all the info of the invoice
     subprocess.Popen("soffice --headless -p " + env_file, shell=True)
示例#11
0
def renderdoc(data_input, outputfile):
    t = Template(os.path.abspath("masterdata/bestellung_template.odt"),
                 outputfile)
    t.set_image_path('staticimage.logo', os.path.abspath("masterdata/logo.png"))

    supplier = data_input['supplier']
    responsible = Staff04.objects.get(id=data_input['responsible'])
    items = []
    total = '%.2f' % sum(item['amount'] for item in data_input['data'])
    for item in data_input['data']:
        if item['packing'] != '':
            item['packing'] = 'Verpackt als: %s' % item['packing']
        items.append(
            {'id': item['prodid'], 'name': item['name'], 'unit': item['unit'], 'quantity': '%.3f' % item['quantity'],
             'price': '%.2f' % item['price'], 'amount': '%.2f' % item['amount'], 'packing': item['packing'],
             'comment': item['comment']})
    recipient = {'address': format_py3o_context_value(
        '%s\n%s\n\n%s %s' % (supplier['namea'], supplier['address'], supplier['zipcode'], supplier['city']))}
    sender = {'address': data_input['adr_kurz'], 'info': 'info'}
    # company specific
    info = {'kostenstelle': data_input['kostenstelle'],
            'bez_kostenstelle': data_input['bez_kostenstelle'],
            'id': data_input['id'], 'date': data_input['docdate'],
            'bauleiter': '%s %s' % (responsible.firstname, responsible.lastname),
            'bauleitertel': responsible.mobile,
            'polier': '', 'lieferadresse': data_input['adr_lang'],
            'infotext': format_py3o_context_value(unicode(data_input['infotext']))}
    data = dict(items=items, recipient=recipient, sender=sender, info=info, total=total)
    t.render(data)
示例#12
0
    def _renderiza_documento(self):
        '''
        Renderiza o documento e salva o pdf do tipo de documento especificado
        de acordo com o template correspondente

        :return:
        '''
        script_dir = os.path.dirname(__file__)
        template_path = os.path.join(script_dir, self.tipo_impressao + '.odt')
        template = open(template_path, 'rb')
        arq_template = tempfile.NamedTemporaryFile()
        arq_template.write(template.read())
        arq_template.seek(os.SEEK_SET)
        template.close()

        arq_odt = tempfile.NamedTemporaryFile(suffix=".odt")

        t = Template(arq_template.name, arq_odt.name)
        t.render({'danfe': self})

        lo = sh.libreoffice('--headless', '--invisible', '--convert-to',
                            'pdf', '--outdir', tempfile.gettempdir(),
                            arq_odt.name, _bg=True)
        lo.wait()

        arq_pdf = arq_odt.name[:-3] + 'pdf'
        self.pdf = open(arq_pdf, 'rb').read()

        arq_template.close()
        arq_odt.close()
示例#13
0
    def test_input_fields_with_function(self):
        template_name = pkg_resources.resource_filename(
            'py3o.template',
            'tests/templates/py3o_template_input_fields_for_function.odt')

        outname = get_secure_filename()

        template = Template(template_name, outname)

        data_dict = {
            'datestring': '2017-10-02',
        }

        template.render(data_dict)
        outodt = zipfile.ZipFile(outname, 'r')

        content_list = lxml.etree.parse(
            BytesIO(outodt.read(template.templated_files[0])))

        result_a = lxml.etree.tostring(
            content_list,
            pretty_print=True,
        ).decode('utf-8')

        result_e = open(
            pkg_resources.resource_filename(
                'py3o.template',
                'tests/templates/input_fields_function_result.xml')).read()

        result_a = result_a.replace("\n", "").replace(" ", "")
        result_e = result_e.replace("\n", "").replace(" ", "")

        assert result_a == result_e
示例#14
0
    def test_template_with_function_call(self):
        template_name = pkg_resources.resource_filename(
            "py3o.template", "tests/templates/py3o_template_function_call.odt"
        )

        outname = get_secure_filename()

        template = Template(template_name, outname)

        data_dict = {"amount": 32.123}

        template.render(data_dict)
        outodt = zipfile.ZipFile(outname, "r")

        content_list = lxml.etree.parse(
            BytesIO(outodt.read(template.templated_files[0]))
        )

        result_a = lxml.etree.tostring(content_list, pretty_print=True).decode(
            "utf-8"
        )

        result_e = open(
            pkg_resources.resource_filename(
                "py3o.template",
                "tests/templates/template_with_function_call_result.xml",
            )
        ).read()

        result_a = result_a.replace("\n", "").replace(" ", "")
        result_e = result_e.replace("\n", "").replace(" ", "")

        assert result_a == result_e
示例#15
0
	def print_directly(self):
		from py3o.template import Template #import for every purchase order or there is an error about invalid magic header numbers
		purchase_order_file = "/tmp/" + self.document_odt
		t = Template(template_dir+"/document_template.odt", purchase_order_file , True)
		t.render(self.data)
		subprocess.Popen("libreoffice --nologo --headless -p " + purchase_order_file, shell = True)
		subprocess.call("odt2pdf " + purchase_order_file, shell = True)
		self.store = []
示例#16
0
 def view(self):
     from py3o.template import Template
     purchase_order_file = "/tmp/" + self.document_odt
     t = Template(main.template_dir + "/purchase_order_template.odt",
                  purchase_order_file, True)
     t.render(
         self.data)  #the self.data holds all the info of the purchase_order
     subprocess.Popen("libreoffice " + purchase_order_file, shell=True)
示例#17
0
	def print_dialog(self, window):
		from py3o.template import Template 
		purchase_order_file = "/tmp/" + self.document_odt
		t = Template(main.template_dir+"/document_template.odt", purchase_order_file , True)
		t.render(self.data)  #the self.data holds all the info of the purchase_order
		subprocess.call("odt2pdf " + purchase_order_file, shell = True)
		p = printing.Setup("/tmp/" + self.document_pdf, "document")
		p.print_dialog (window)
示例#18
0
 def render_template():
     finder = config['pylons.app_globals'].dotted_filename_finder
     odt_template_file = finder.get_dotted_filename(
                      template_name=template_name,
                      template_extension=".odt")
     output = NamedTemporaryFile()
     t = Template(odt_template_file, output.name)
     t.render(dict(document=template_vars))
     return output.read()
示例#19
0
	def print_serial_number(self, serial_number):
		document = Item()
		document.serial_number = serial_number
		data = dict(label = document)
		from py3o.template import Template
		sn_file = "/tmp/job_serial.odt"
		t = Template(template_dir+"/job_serial_template.odt", sn_file, True)
		t.render(data)
		subprocess.Popen(["soffice", sn_file])
示例#20
0
    def view_report(self):
        self.cursor.execute("SELECT * FROM contacts WHERE id = (%s)",
                            [self.employee_id])
        customer = Item()
        for row in self.cursor.fetchall():
            self.customer_id = row[0]
            customer.name = row[1]
            name = row[1]
            customer.ext_name = row[2]
            customer.street = row[3]
            customer.city = row[4]
            customer.state = row[5]
            customer.zip = row[6]
            customer.fax = row[7]
            customer.phone = row[8]
            customer.email = row[9]
        company = Item()
        self.cursor.execute("SELECT * FROM company_info")
        for row in self.cursor.fetchall():
            company.name = row[1]
            company.street = row[2]
            company.city = row[3]
            company.state = row[4]
            company.zip = row[5]
            company.country = row[6]
            company.phone = row[7]
            company.fax = row[8]
            company.email = row[9]
            company.website = row[10]
            company.tax_number = row[11]
        actual_hours = self.actual_seconds / 3600
        adjusted_hours = self.adjusted_seconds / 3600
        cost_sharing_hours = self.cost_sharing_seconds / 3600
        profit_sharing_hours = self.profit_sharing_seconds / 3600
        time = Item()
        time.actual = round(actual_hours, 2)
        time.adjusted = round(adjusted_hours, 2)
        time.cost_sharing = round(cost_sharing_hours, 2)
        time.profit_sharing = round(profit_sharing_hours, 2)
        time.efficiency = round(self.efficiency, 2)
        payment = Item()
        time.payment_due = '${:,.2f}'.format(self.payment)
        wage = self.builder.get_object('spinbutton1').get_value()
        time.wage = '${:,.2f}'.format(wage)
        self.data = dict(contact=customer,
                         time=time,
                         company=company,
                         payment=payment)
        from py3o.template import Template  #import for every use or there is an error about invalid magic header numbers
        self.time_file = "/tmp/employee_time.odt"
        self.time_file_pdf = "/tmp/employee_time.pdf"
        t = Template(main.template_dir + "/employee_time.odt", self.time_file,
                     True)
        t.render(self.data)  #the self.data holds all the info of the invoice

        subprocess.call('soffice ' + self.time_file, shell=True)
示例#21
0
 def print_directly(self):
     from py3o.template import Template
     purchase_order_file = "/tmp/" + self.document_odt
     t = Template(main.template_dir + "/purchase_order_template.odt",
                  purchase_order_file, True)
     t.render(self.data)
     subprocess.call("odt2pdf " + purchase_order_file, shell=True)
     p = printing.Setup("/tmp/" + self.document_pdf, 'purchase_order')
     p.print_direct(window)
     self.store = []
示例#22
0
	def print_dialog(self, window):
		from py3o.template import Template 
		purchase_order_file = "/tmp/" + self.document_odt
		t = Template(template_dir+"/document_template.odt", purchase_order_file , True)
		t.render(self.data)  #the self.data holds all the info of the purchase_order
		subprocess.call("odt2pdf " + purchase_order_file, shell = True)
		p = printing.Operation(settings_file = "document")
		p.set_parent(window)
		p.set_file_to_print ("/tmp/" + self.document_pdf)
		p.print_dialog ()
示例#23
0
 def test_jsonify_empty_for_loop(self):
     """ Test the jsonify function
     """
     template_xml = pkg_resources.resource_filename(
         'py3o.template', 'tests/templates/py3o_empty_for_loop.odt')
     t = Template(template_xml, get_secure_filename())
     for_lists, variables = t.get_user_instructions_mapping()
     data = {'my1list': []}
     res = ForList.to_dict(for_lists, variables, data)
     expected = {'my1list': []}
     assert res == expected
示例#24
0
	def print_label(self, widget):
		location_id = self.get_object('comboboxtext6').get_active_id()
		label = Item()
		self.cursor.execute("SELECT aisle, cart, rack, shelf, cabinet, drawer, "
							"bin FROM product_location "
							"WHERE (product_id, location_id) = (%s, %s)", 
							(self.product_id, location_id))
		for row in self.cursor.fetchall():
			label.aisle = row[0]
			label.cart = row[1]
			label.rack = row[2]
			label.shelf = row[3]
			label.cabinet = row[4]
			label.drawer = row[5]
			label.bin = row[6]
			break
		else:
			label.aisle = ''
			label.cart = ''
			label.rack = ''
			label.shelf = ''
			label.cabinet = ''
			label.drawer = ''
			label.bin = ''
		self.cursor.execute("SELECT name, description, barcode FROM products "
							"WHERE id = (%s)",[self.product_id])
		for row in self.cursor.fetchall():
			label.name= row[0]
			label.description = row[1]
			label.code128 = barcode_generator.makeCode128(row[2])
			label.barcode = row[2]
		self.cursor.execute("SELECT id FROM customer_markup_percent "
							"WHERE standard = True")
		default_markup_id = self.cursor.fetchone()[0]
		self.cursor.execute("SELECT price FROM products_markup_prices "
							"WHERE (product_id, markup_id) = (%s, %s)", 
							(self.product_id, default_markup_id))
		for row in self.cursor.fetchall():
			label.price = '${:,.2f}'.format(row[0])
			break
		else:
			cost = self.get_object('spinbutton1').get_value()
			self.cursor.execute("SELECT markup_percent "
								"FROM customer_markup_percent WHERE id = %s", 
								(markup_id,))
			markup = float(self.cursor.fetchone()[0])
			margin = (markup / 100) * cost
			label.price = '${:,.2f}'.format(margin + cost)
		data = dict(label = label)
		from py3o.template import Template
		label_file = "/tmp/product_label.odt"
		t = Template(main.template_dir+"/product_label_template.odt", label_file )
		t.render(data) #the self.data holds all the info
		subprocess.Popen(["soffice", label_file])
示例#25
0
    def create_report(self):
        # собираем условия с формы
        # name_company = self.cmbox_company.currentText()
        # id_company = conn.query(Counterparties).filter(Counterparties.name_c == name_company).first().id

        # data_start = self.date_start.text()
        # data_end = self.date_end.text()
        # action = self.cmbox_action.currentText()  # приход / расход
        # формируем запрос в базу
        bank_query = conn.query(BankDocsRev).filter(BankDocsRev.date_docs >= self.date_start.date().toPython()).filter(BankDocsRev.date_docs <= self.date_end.date().toPython()).filter(BankDocsRev.action_docs == self.cmbox_action.currentText()).all()
        for item in bank_query:
            print(f'Контрагент: {item.p_counterparties.name_c}, сумма: {item.summ_docs:.2f}, статус документа: {item.action_docs}')
        # определяем пути к файлам
        path_empty = os.path.join('templates', 'report_bank.ods')
        path_full = os.path.join('temp', 'report_bank.ods')
        t = Template(path_empty, path_full)

        items = list()
        total_summ = 0

        # перебираем значения из запроса
        for bank in bank_query:
            item = Item()
            item.date = bank.date_docs.strftime('%d.%m.%Y')
            # item.summ = str(round(bank.summ_docs, 2)).replace('.', ',')
            item.summ = round(bank.summ_docs, 2)
            item.counterp = bank.p_counterparties.name_c
            item.coment = bank.comment_docs
            items.append(item)
            total_summ += bank.summ_docs
        
        # формируем даты
        start_date = Item()
        start_date.date = datetime.strftime(self.date_start.date().toPython(), '%d.%m.%Y')

        end_date = Item()
        end_date.date = datetime.strftime(self.date_end.date().toPython(), '%d.%m.%Y')

        total = Item()
        # total.summ = str(round(total_summ, 2)).replace('.', ',')
        total.summ = round(total_summ, 2)
        
        # группируем данные для передачи в отчёт
        date = dict(items = items, start_date = start_date, end_date = end_date, total = total)

        # передаём данные в отчёт
        t.render(date)

        # открываем созданный отчёт
        if sys.platform == "win32":
                os.startfile(path_full)
        else:
            opener ="open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, path_full])
示例#26
0
 def test_jsonify_in_loop_variable_with_attribute(self):
     """ Test the jsonify function
     """
     template_xml = pkg_resources.resource_filename(
         'py3o.template',
         'tests/templates/py3o_access_in_loop_variable_with_attribute.odt')
     t = Template(template_xml, get_secure_filename())
     for_lists, variables = t.get_user_instructions_mapping()
     data = {'my3list': [Mock(val='val1'), Mock(val='val2')]}
     res = ForList.to_dict(for_lists, variables, data)
     expected = {'my3list': [{'val': 'val1'}, {'val': 'val2'}]}
     assert res == expected
 def reprint_serial_number_clicked(self, button):
     barcode = self.get_object('serial_number_entry').get_text()
     label = Item()
     label.code128 = barcode_generator.makeCode128(str(barcode))
     label.barcode = barcode
     from py3o.template import Template
     label_file = "/tmp/manufacturing_serial_label.odt"
     t = Template(template_dir + "/manufacturing_serial_template.odt",
                  label_file)
     data = dict(label=label)
     t.render(data)
     subprocess.call(["soffice", "--headless", "-p", label_file])
示例#28
0
 def test_jsonify_global_variable_inside_loop(self):
     """ Test the jsonify function
     """
     template_xml = pkg_resources.resource_filename(
         'py3o.template',
         'tests/templates/py3o_access_global_variable_inside_loop.odt')
     t = Template(template_xml, get_secure_filename())
     for_lists, variables = t.get_user_instructions_mapping()
     data = {'global_var': Mock(val='global_val')}
     res = ForList.to_dict(for_lists, variables, data)
     expected = {'global_var': {'val': 'global_val'}, 'my4list': []}
     assert res == expected
示例#29
0
 def test_jsonify_iterator_with_attribute(self):
     """ Test the jsonify function
     """
     template_xml = pkg_resources.resource_filename(
         'py3o.template',
         'tests/templates/py3o_iterator_with_attribute.odt')
     t = Template(template_xml, get_secure_filename())
     for_lists, variables = t.get_user_instructions_mapping()
     data = {'global_var': Mock(my5list=[])}
     res = ForList.to_dict(for_lists, variables, data)
     expected = {'global_var': {'my5list': []}}
     assert res == expected
示例#30
0
    def create_payment_receipt(self, line):
        self.payment_id = line[0]
        payment = Item()
        payment.date = line[2]
        payment.amount = '${:,.2f}'.format(line[5])
        payment.text = line[6]
        payment.type = line[7]
        payment.invoice_number = line[8]
        payment.invoice_name = line[9]
        contact_id = line[3]
        self.cursor.execute("SELECT * FROM contacts "
                            "WHERE id = (%s)", [contact_id])
        customer = Item()
        for row in self.cursor.fetchall():
            self.customer_id = row[0]
            customer.name = row[1]
            name = row[1]
            customer.ext_name = row[2]
            customer.street = row[3]
            customer.city = row[4]
            customer.state = row[5]
            customer.zip = row[6]
            customer.fax = row[7]
            customer.phone = row[8]
            customer.email = row[9]
            customer.label = row[10]
            customer.tax_exempt = row[11]
            customer.tax_exempt_number = row[12]
        company = Item()
        self.cursor.execute("SELECT * FROM company_info")
        for row in self.cursor.fetchall():
            company.name = row[1]
            company.street = row[2]
            company.city = row[3]
            company.state = row[4]
            company.zip = row[5]
            company.country = row[6]
            company.phone = row[7]
            company.fax = row[8]
            company.email = row[9]
            company.website = row[10]
            company.tax_number = row[11]

        document_name = "payment_receipt"
        self.document_name = document_name
        self.document_odt = document_name + ".odt"
        self.document_pdf = document_name + ".pdf"
        data = dict(payment=payment, contact=customer, company=company)
        from py3o.template import Template
        self.receipt_file = "/tmp/" + self.document_odt
        t = Template(template_dir + "/payment_receipt_template.odt",
                     self.receipt_file, True)
        t.render(data)  #the data holds all the info of the invoice
示例#31
0
 def print_serial_number(self, barcode, label_qty):
     label = Item()
     label.code128 = barcode_generator.makeCode128(str(barcode))
     label.barcode = barcode
     from py3o.template import Template
     label_file = "/tmp/manufacturing_serial_label.odt"
     t = Template(template_dir + "/manufacturing_serial_template.odt",
                  label_file)
     data = dict(label=label)
     t.render(data)  #the self.data holds all the info
     for i in range(label_qty):
         subprocess.call(["soffice", "--headless", "-p", label_file])
示例#32
0
	def print_and_post_clicked (self, button):
		total = Decimal(self.get_object('spinbutton1').get_text())
		check_number = self.get_object('entry7').get_text()
		bank_account = self.get_object('combobox2').get_active_id()
		self.cursor.execute("SELECT "
								"name, "
								"checks_payable_to, "
								"address, "
								"city, "
								"state, "
								"zip, "
								"phone "
							"FROM contacts WHERE id = %s",(self.provider_id,))
		provider = Item()
		for line in self.cursor.fetchall():
			provider.name = line[0]
			provider.pay_to = line[1]
			provider.street = line[2]
			provider.city = line[3]
			provider.state = line[4]
			provider.zip = line[5]
			provider.phone = line[6]
			pay_to = line[1].split()[0]
		items = list()
		'''for row in self.provider_invoice_store:
			if row[3] == True:'''
				
		item = Item()
		item.po_number = ''#row[0] 
		item.amount = ''#row[2]
		item.date = ''#row[4]
		items.append(item)
		check = Item()
		check.check_number = check_number
		check.checking_account = bank_account
		check.date = self.date
		check.amount = total 
		check.amount_text = get_written_check_amount_text (total)
		from py3o.template import Template
		data = dict(contact = provider, check = check, items = items )#- kept this
		#in case we ever wish to list the accountbreakdown on the check stubs
		self.tmp_file = "/tmp/check" + pay_to +".odt"
		self.tmp_file_pdf = "/tmp/check" + pay_to + ".pdf"
		t = Template(template_dir+"/vendor_check_template.odt", self.tmp_file, True)
		t.render(data)
		subprocess.call(["odt2pdf", self.tmp_file])
		p = printing.Operation(settings_file = 'Vendor_check')
		p.set_file_to_print(self.tmp_file_pdf)
		p.set_parent(self.window)
		result = p.print_dialog()
		if result != "user canceled":
			self.perform_payment()
示例#33
0
 def test_jsonify_access_in_loop_variable(self):
     """ Test the jsonify function
     """
     template_xml = pkg_resources.resource_filename(
         'py3o.template',
         'tests/templates/py3o_access_in_loop_variable.odt'
     )
     t = Template(template_xml, get_secure_filename())
     for_lists, variables = t.get_user_instructions_mapping()
     data = {
         'my2list': ['val1', 'val2']
     }
     res = ForList.to_dict(for_lists, variables, data)
     expected = {'my2list': ['val1', 'val2']}
     assert res == expected
示例#34
0
 def test_jsonify_iterator_with_attribute_and_in_loop_variable(self):
     """ Test the jsonify function
     """
     template_xml = pkg_resources.resource_filename(
         'py3o.template',
         'tests/templates/py3o_iterator_with_attribute_and_in_loop_variable.odt'
     )
     t = Template(template_xml, get_secure_filename())
     for_lists, variables = t.get_user_instructions_mapping()
     data = {
         'global_var': Mock(my6list=['val1', 'val2'])
     }
     res = ForList.to_dict(for_lists, variables, data)
     expected = {'global_var': {'my6list': ['val1', 'val2']}}
     assert res == expected
示例#35
0
 def test_jsonify_global_variable_inside_loop(self):
     """ Test the jsonify function
     """
     template_xml = pkg_resources.resource_filename(
         'py3o.template',
         'tests/templates/py3o_access_global_variable_inside_loop.odt'
     )
     t = Template(template_xml, get_secure_filename())
     for_lists, variables = t.get_user_instructions_mapping()
     data = {
         'global_var': Mock(val='global_val')
     }
     res = ForList.to_dict(for_lists, variables, data)
     expected = {'global_var': {'val': 'global_val'}, 'my4list': []}
     assert res == expected
示例#36
0
 def test_jsonify_in_loop_variable_with_attribute(self):
     """ Test the jsonify function
     """
     template_xml = pkg_resources.resource_filename(
         'py3o.template',
         'tests/templates/py3o_access_in_loop_variable_with_attribute.odt'
     )
     t = Template(template_xml, get_secure_filename())
     for_lists, variables = t.get_user_instructions_mapping()
     data = {
         'my3list': [Mock(val='val1'), Mock(val='val2')]
     }
     res = ForList.to_dict(for_lists, variables, data)
     expected = {'my3list': [{'val': 'val1'}, {'val': 'val2'}]}
     assert res == expected
示例#37
0
def renderdoc1(data_input, outputfile):
    t = Template(os.path.abspath("masterdata/lagerausgang_template.odt"),
                 outputfile)
    t.set_image_path('staticimage.logo', os.path.abspath("masterdata/logo_sofico.png"))

    #responsible = Staff01.objects.get(id=data_input['responsible'])
    items = []
    #total = '%.2f' % sum(item['amount'] for item in data_input['data'])
    for item in data_input['data']:
        packing = item['packing'] if item['packing'] else ''
        comment = item['comment'] if item['comment'] else ''
        items.append(
            {'id': item['prodid'], 'name': item['name'], 'unit': item['unit'], 'quantity': '%.3f' % item['quantity'],
             'price': '%.2f' % item['price'], 'packing': packing, 'comment': comment})
    # company specific
    info = {'kostenstelle': data_input['modulerefid'], 'stock': data_input["stockid"],
            'bez_kostenstelle': data_input['subject'], 'id':data_input['id'],
            'date': data_input['docdate'], 'recipient':'%s'%(data_input['responsible']),
            'polier': data_input['leader'],
            'abholer': data_input['abholer']}
    data = dict(items=items, info=info)
    t.render(data)
示例#38
0
def render(data):
    t = Template(TEMPLATE, OUTPUT)
    t.render(data)
示例#39
0
    def test_jsonify_iterator_with_attribute_and_in_loop_variable_with_attribute(self):
        """ Test the jsonify function
        """
        template_xml = pkg_resources.resource_filename(
            'py3o.template',
            'tests/templates/py3o_iterator_with_attribute_and_in_loop_variable_with_attribute.odt'
        )
        t = Template(template_xml, get_secure_filename())
        for_lists, variables = t.get_user_instructions_mapping()
        data = {
            'global_var': Mock(my7list=[Mock(val='val1'), Mock(val='val2')])
        }
        res = ForList.to_dict(for_lists, variables, data)
        expected = {'global_var': {'my7list': [{'val': 'val1'}, {'val': 'val2'}]}}
        assert res == expected

#    def test_jsonify_access_variable_in_nested_loop(self):
#        """ Test the jsonify function
#        """
#        template_xml = pkg_resources.resource_filename(
#            'py3o.template',
#            'tests/templates/py3o_access_variable_in_nested_loop.odt'
#        )
#        t = Template(template_xml, get_secure_filename())
#        for_lists, variables = t.get_user_instructions_mapping()
#        data = {
#            'my8list': [['val1', 'val2'], ['val3']]
#        }
#        res = ForList.to_dict(for_lists, variables, data)
#        expected = {'my8list': [['val1', 'val2'], ['val3']]}
#        assert res == expected

#    def test_jsonify_access_parent_variable_in_nested_loop(self):
#        """ Test the jsonify function
#        """
#        template_xml = pkg_resources.resource_filename(
#            'py3o.template',
#            'tests/templates/py3o_access_parent_variable_in_nested_loop.odt'
#        )
#        t = Template(template_xml, get_secure_filename())
#        for_lists, variables = t.get_user_instructions_mapping()
#        data = {
#            'my9list': [Mock(val='val1', mylist=[]), Mock(val='val2', mylist=[])]
#        }
#        res = ForList.jsonify(for_lists, variables, data)
#        expected = "{'my9list': [{'val': 'val1', 'mylist': []}, {'val': 'val2', 'mylist': []}]}"
#        assert res == expected
#
#    def test_jsonify_access_variable_in_nested_loop_with_attribute(self):
#        """ Test the jsonify function
#        """
#        template_xml = pkg_resources.resource_filename(
#            'py3o.template',
#            'tests/templates/py3o_access_variable_in_nested_loop_with_attribute.odt'
#        )
#        t = Template(template_xml, get_secure_filename())
#        for_lists, variables = t.get_user_instructions_mapping()
#        data = {
#            'my10list': [Mock(my_list=[Mock(val='val1'), Mock(val='val2')]), Mock(my_list=[Mock(val='val3')])]
#        }
#        res = ForList.jsonify(for_lists, variables, data)
#        expected = "{'my10list': [{'my_list': [{'val': 'val1'}, {'val': 'val2'}]}, {'my_list': [{'val': 'val3'}]}]}"
#        assert res == expected
示例#40
0
from py3o.template import Template

t = Template(
    "py3o_example_template_page_break.odt",
    "py3o_example_page_break_output.odt"
)


class Item(object):
    pass

items = list()

item1 = Item()
item1.val1 = 'Item1 Value1'
item1.val2 = 'Item1 Value2'
item1.val3 = 'Item1 Value3'
item1.Currency = 'EUR'
item1.Amount = '12345.35'
item1.InvoiceRef = '#1234'
items.append(item1)

for i in xrange(10):
    item = Item()
    item.val1 = 'Item%s Value1' % i
    item.val2 = 'Item%s Value2' % i
    item.val3 = 'Item%s Value3' % i
    item.Currency = 'EUR'
    item.Amount = '6666.77'
    item.InvoiceRef = 'Reference #%04d' % i
    items.append(item)
示例#41
0
    def create(self, cr, uid, ids, data, context=None):
        # Find the report definition to get its settings.
        pool = pooler.get_pool(cr.dbname)
        report_xml_obj = pool.get('ir.actions.report.xml')
        report_xml_ids = report_xml_obj.search(
            cr, uid,
            [('report_name', '=', self.name[7:])],  # Ignore "report."
            context=context,
        )
        if not report_xml_ids:
            return super(py3o_report, self).create(cr, uid, ids, data,
                                                   context=context)
        report_xml = report_xml_obj.browse(cr, uid,
                                           report_xml_ids[0],
                                           context=context)

        tmpl_def = report_xml.py3o_template_id
        filetype = report_xml.py3o_fusion_filetype

        # py3o.template operates on filenames so create temporary files.
        with NamedTemporaryFile(
            suffix='.odt', prefix='py3o-template-'
        ) as in_temp, NamedTemporaryFile(
            suffix='.odt',
            prefix='py3o-report-'
        ) as out_temp:

            in_temp.write(b64decode(tmpl_def.py3o_template_data))
            in_temp.flush()
            in_temp.seek(0)

            datadict = self.get_values(cr, uid, ids, data, context)

            template = Template(in_temp.name, out_temp.name)
            template.render(datadict)
            out_temp.seek(0)

            # TODO: use py3o.formats to know native formats instead
            # of hardcoding this value
            # TODO: why use the human readable form when you're a machine?
            # this is non-sense AND dangerous... please use technical name
            if filetype.human_ext != 'odt':
                # Now we ask fusion server to convert our template
                fusion_server_obj = pool.get('py3o.server')
                fusion_server_id = fusion_server_obj.search(
                    cr, uid, [], context=context
                )[0]
                fusion_server = fusion_server_obj.browse(
                    cr, uid, fusion_server_id, context=context
                )
                files = {
                    'tmpl_file': out_temp,
                }
                fields = {
                    "targetformat": filetype.fusion_ext,
                    "datadict": "{}",
                    "image_mapping": "{}",
                    "skipfusion": True,
                }
                # Here is a little joke about Odoo
                # we do nice chunked reading from the network...
                r = requests.post(fusion_server.url, data=fields, files=files)
                if r.status_code == 400:
                    # server says we have an issue... let's tell that to enduser
                    raise osv.except_osv(
                        _('Fusion server error'),
                        r.json(),
                    )

                else:
                    chunk_size = 1024
                    with NamedTemporaryFile(
                        suffix=filetype.human_ext,
                        prefix='py3o-template-'
                    ) as fd:
                        for chunk in r.iter_content(chunk_size):
                            fd.write(chunk)
                        fd.seek(0)
                        # ... but odoo wants the whole data in memory anyways :)
                        return fd.read(), filetype.human_ext

            return out_temp.read(), 'odt'
示例#42
0
from py3o.template import Template

t = Template("py3o_example_template_single_cell.odt", "py3o_example_output_single_cell.odt")

t.set_image_path('logo', 'images/new_logo.png')


class Item(object):
    pass

items = list()

item1 = Item()
item1.val1 = 'Item1 Value1'
item1.val2 = 'Item1 Value2'
item1.val3 = 'Item1 Value3'
item1.Currency = 'EUR'
item1.Amount = '12,345.35'
item1.InvoiceRef = '#1234'
items.append(item1)

for i in xrange(1000):
    item = Item()
    item.val1 = 'Item%s Value1' % i
    item.val2 = 'Item%s Value2' % i
    item.val3 = 'Item%s Value3' % i
    item.Currency = 'EUR'
    item.Amount = '6,666.77'
    item.InvoiceRef = 'Reference #%04d' % i
    items.append(item)
示例#43
0
    def gerar_danfce(self):
        if self.NFe is None:
            raise ValueError('Não é possível gerar um DANFCE sem a informação de uma NFC-e')

        if self.protNFe is None:
            self.protNFe = ProtNFe_310()

        if self.procEventoCancNFe is None:
            self.procEventoCancNFe = ProcEventoCancNFe_100()

        #
        # Prepara o queryset para impressão
        #
        self.NFe.monta_chave()
        self.NFe.monta_qrcode()
        self.NFe.site = self.site

        # Emissão para simples conferência / sem protocolo de autorização
        self.mensagem_protocolo = ''
        self.mensagem_sem_valor = ''
        if (not self.protNFe.infProt.nProt.valor) or self.NFe.infNFe.ide.tpAmb.valor == 2:
            self.mensagem_sem_valor = u'Sem valor fiscal'

        # NF-e denegada
        if self.protNFe.infProt.cStat.valor in ('110', '301', '302'):
            self.mensagem_protocolo = u'Protocolo de Denegação '
            self.mensagem_protocolo += self.protNFe.protocolo_formatado

        # Emissão normal
        elif self.protNFe.infProt.nProt.valor:
            self.mensagem_protocolo = u'Protocolo de Autorização '
            self.mensagem_protocolo += self.protNFe.protocolo_formatado

        # A NF-e foi cancelada por um evento de cancelamento, , no DANFCE imprimir o "carimbo" de cancelamento
        self.mensagem_cancelamento = ''
        self.motivo_cancelamento = ''
        if self.procEventoCancNFe.retEvento.infEvento.nProt.valor:
            self.mensagem_cancelamento = self.procEventoCancNFe.retEvento.protocolo_formatado
            self.motivo_cancelamento = self.procEventoCancNFe.evento.infEvento.detEvento.xJust.valor

        ##
        ## Observação de impressão
        ##
        #if self.nome_sistema:
            #self.obs_impressao = self.nome_sistema + ' - ' + self.obs_impressao
        #else:
            #self.obs_impressao = self.obs_impressao


        if self.template:
            if isinstance(self.template, file):
                template = self.template
            else:
                template = open(self.template)

        else:
            template = open(os.path.join(DIRNAME, 'danfce_a4.odt'))

        self.caminho_temporario = self.caminho_temporario or '/tmp/'


        nome_arq_template = self.caminho_temporario + uuid4().hex
        open(nome_arq_template, 'w').write(template.read())
        template.close()

        nome_arq_temp = uuid4().hex
        nome_arq_odt = self.caminho_temporario + nome_arq_temp + '.odt'
        nome_arq_pdf = self.caminho_temporario + nome_arq_temp + '.pdf'

        t = Template(nome_arq_template, nome_arq_odt)
        t.render({'danfce': self})

        print(sh.libreoffice('--headless', '--invisible', '--convert-to', 'pdf', '--outdir', '/tmp', nome_arq_odt))

        self.conteudo_pdf = open(nome_arq_pdf, 'r').read()

        os.remove(nome_arq_template)
        os.remove(nome_arq_odt)
        os.remove(nome_arq_pdf)

        if self.salvar_arquivo:
            nome_arq = self.caminho + self.NFe.chave + '.pdf'
            open(nome_arq, 'w').write(self.conteudo_pdf)