Exemple #1
0
    def test_ignore_undefined_variables_logo(self):

        template_name = pkg_resources.resource_filename(
            'py3o.template', 'tests/templates/py3o_logo.odt')

        outname = get_secure_filename()

        template = Template(template_name, outname)

        data = {}

        error = True
        try:
            template.render(data)
            print("Error: template contains a logo variable that must be "
                  "replaced")
        except ValueError:
            error = False

        assert error is False

        template = Template(template_name,
                            outname,
                            ignore_undefined_variables=True)

        error = False
        try:
            template.render(data)
        except:
            traceback.print_exc()
            error = True

        assert error is False
Exemple #2
0
    def test_remove_soft_breaks_without_tail(self):
        template_xml = pkg_resources.resource_filename(
            "py3o.template", "tests/templates/py3o_page_break_without_tail.odt"
        )
        t = Template(template_xml, get_secure_filename())
        soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces)
        assert len(soft_breaks) > 0

        t.remove_soft_breaks()
        soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces)
        assert len(soft_breaks) == 0

        t = Template(template_xml, get_secure_filename())
        soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces)
        assert len(soft_breaks) > 0

        t.render(
            data={
                "items": [
                    {"Amount": 3, "Currency": "D"},
                    {"Amount": 2, "Currency": "E"},
                    {"Amount": 1, "Currency": "C"},
                ]
            }
        )
        soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces)
        assert len(soft_breaks) == 0
Exemple #3
0
    def test_ignore_undefined_variables_1(self):

        template_name = pkg_resources.resource_filename(
            "py3o.template", "tests/templates/py3o_undefined_variables_1.odt"
        )

        outname = get_secure_filename()

        template = Template(template_name, outname)

        data = {}

        error = True
        try:
            template.render(data)
            print(
                "Error: template contains variables that must be " "replaced"
            )
        except TemplateError:
            error = False

        assert error is False

        template = Template(
            template_name, outname, ignore_undefined_variables=True
        )

        error = False
        try:
            template.render(data)
        except Exception:
            traceback.print_exc()
            error = True

        assert error is False
Exemple #4
0
    def test_remove_soft_breaks_without_tail(self):
        template_xml = pkg_resources.resource_filename(
            'py3o.template',
            'tests/templates/py3o_page_break_without_tail.odt')
        t = Template(template_xml, get_secure_filename())
        soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces)
        assert len(soft_breaks) > 0

        t.remove_soft_breaks()
        soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces)
        assert len(soft_breaks) == 0

        t = Template(template_xml, get_secure_filename())
        soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces)
        assert len(soft_breaks) > 0

        t.render(
            data={
                "items": [
                    {
                        'Amount': 3,
                        'Currency': 'D'
                    },
                    {
                        'Amount': 2,
                        'Currency': 'E'
                    },
                    {
                        'Amount': 1,
                        'Currency': 'C'
                    },
                ]
            })
        soft_breaks = get_soft_breaks(t.content_trees[0], t.namespaces)
        assert len(soft_breaks) == 0
Exemple #5
0
    def test_ignore_undefined_variables_image_injection(self):
        """Test ignore undefined variables for injected image"""

        template_name = pkg_resources.resource_filename(
            "py3o.template", "tests/templates/py3o_image_injection.odt"
        )

        outname = get_secure_filename()

        data = {"items": [], "document": Mock(total=6)}

        template = Template(template_name, outname)
        error = True
        try:
            template.render(data)
            print(
                "Error: template contains variables that must be " "replaced"
            )
        except TemplateError:
            error = False

        self.assertFalse(error)

        template = Template(
            template_name, outname, ignore_undefined_variables=True
        )
        error = False
        try:
            template.render(data)
        except Exception:
            traceback.print_exc()
            error = True

        self.assertFalse(error)
Exemple #6
0
    def test_remove_soft_page_breaks(self):
        template_xml = pkg_resources.resource_filename(
            "py3o.template", "tests/templates/py3o_soft_page_break.odt"
        )
        outname = get_secure_filename()

        template = Template(template_xml, outname)
        soft_breaks = get_soft_breaks(
            template.content_trees[0], template.namespaces
        )
        self.assertEqual(len(soft_breaks), 2)

        template.remove_soft_breaks()
        soft_breaks = get_soft_breaks(
            template.content_trees[0], template.namespaces
        )
        self.assertEqual(len(soft_breaks), 0)

        template = Template(template_xml, outname)
        soft_breaks = get_soft_breaks(
            template.content_trees[0], template.namespaces
        )
        self.assertEqual(len(soft_breaks), 2)

        template.render(data={"list1": [1, 2, 3]})
        soft_breaks = get_soft_breaks(
            template.content_trees[0], template.namespaces
        )
        self.assertEqual(len(soft_breaks), 0)

        outodt = zipfile.ZipFile(outname, "r")
        content_list = lxml.etree.parse(
            BytesIO(outodt.read(template.templated_files[0]))
        )

        nmspc = template.namespaces
        paragraphs = content_list.findall("//text:p", nmspc)
        bottom_break_paragraphs, middle_break_paragraphs = 0, 0
        for p in paragraphs:
            if not p.text:
                continue
            text = p.text.strip()
            if text == (
                u"This is a text with a margin at the bottom and a "
                u"soft-page-break"
            ):
                bottom_break_paragraphs += 1
            elif text == (
                u"This is a paragraph that is cut in half by a "
                u"soft-page-break. This text should not remain cut "
                u"in half after rendering."
            ):
                middle_break_paragraphs += 1
            else:
                self.fail(u"Unidentified text in result: {}".format(text))

        self.assertEqual(bottom_break_paragraphs, 3)
        self.assertEqual(middle_break_paragraphs, 3)
Exemple #7
0
    def test_escape_false_template(self):
        template_name = pkg_resources.resource_filename(
            "py3o.template", "tests/templates/test_false_value.odt"
        )

        outname = get_secure_filename()

        template = Template(template_name, outname)
        template.render({"false_value": False})
        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_test_false_value_result.xml",
            )
        ).read()

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

        self.assertEqual(result_a, result_e)

        outname = get_secure_filename()

        template = Template(template_name, outname, escape_false=True)
        template.render({"false_value": False})
        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_test_escape_false_value_result.xml",
            )
        ).read()

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

        self.assertEqual(result_a, result_e)
Exemple #8
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()
Exemple #9
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
Exemple #11
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
 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])
Exemple #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
Exemple #14
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
Exemple #15
0
    def test_missing_opening(self):
        """test orphaned /for raises a TemplateException"""
        template_name = pkg_resources.resource_filename(
            'py3o.template', 'tests/templates/py3o_missing_open_template.odt')
        outname = get_secure_filename()
        try:
            template = Template(template_name, outname)

        finally:
            os.remove(outname)

        class Item(object):
            def __init__(self, val):
                self.val = val

        data_dict = {"items": [Item(1), Item(2), Item(3), Item(4)]}

        template.set_image_path(
            'staticimage.logo',
            pkg_resources.resource_filename(
                'py3o.template', 'tests/templates/images/new_logo.png'))
        # this will raise a TemplateException... or the test will fail
        error_occured = False
        try:
            template.render(data_dict)

        except TemplateException as e:
            error_occured = True
            # make sure this is the correct TemplateException that pops
            assert e.message == "No open instruction for /for"

        # and make sure we raised
        assert error_occured is True
Exemple #16
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
 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()
Exemple #18
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))
Exemple #19
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)
Exemple #20
0
    def test_link_validation_missing_equal(self):
        """test a missing equal sign in a link raises a template error"""
        template_name = pkg_resources.resource_filename(
            "py3o.template", "tests/templates/py3o_missing_eq_in_link.odt"
        )
        outname = get_secure_filename()

        template = Template(template_name, outname)

        class Item(object):
            def __init__(self, val):
                self.val = val

        data_dict = {"items": [Item(1), Item(2), Item(3), Item(4)]}

        template.set_image_path(
            "staticimage.logo",
            pkg_resources.resource_filename(
                "py3o.template", "tests/templates/images/new_logo.png"
            ),
        )
        except_occured = False
        error_text = ""
        try:
            template.render(data_dict)
        except TemplateException as e:
            except_occured = True
            error_text = "{}".format(e)

        assert except_occured is True
        assert error_text == (
            "Missing '=' in instruction 'for \"item in items\"'"
        )
Exemple #21
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
Exemple #22
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
Exemple #23
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)
Exemple #24
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 = []
Exemple #25
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)
Exemple #26
0
    def _create_single_report(self, model_instance, data, save_in_attachment):
        """ This function to generate our py3o report
        """
        self.ensure_one()
        report_xml = self.ir_actions_report_xml_id
        filetype = report_xml.py3o_filetype

        result_fd, result_path = tempfile.mkstemp(
            suffix='.' + filetype, 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)
            is_native = Formats().get_format(filetype).native
            if report_xml.py3o_is_local_fusion:
                template.render(localcontext)
                out_stream.seek(0)
                tmpl_data = out_stream.read()
                datadict = {}
            else:
                expressions = template.get_all_user_python_expression()
                py_expression = template.convert_py3o_to_python_ast(
                    expressions)
                convertor = Py3oConvertor()
                data_struct = convertor(py_expression)
                datadict = data_struct.render(localcontext)

        # if not is_native or not report_xml.py3o_is_local_fusion:
        #     # Call py3o.server to render the template in the desired format
        #     files = {
        #         'tmpl_file': tmpl_data,
        #     }
        #     fields = {
        #         "targetformat": filetype,
        #         "datadict": json.dumps(datadict),
        #         "image_mapping": "{}",
        #         "escape_false": "on",
        #     }
        #     if report_xml.py3o_is_local_fusion:
        #         fields['skipfusion'] = '1'
        #     r = requests.post(
        #         report_xml.py3o_server_id.url, data=fields, files=files)
        #     if r.status_code != 200:
        #         # server says we have an issue... let's tell that to enduser
        #         raise UserError(
        #             _('Fusion server error %s') % r.text,
        #         )

        #     chunk_size = 1024
        #     with open(result_path, 'w+') as fd:
        #         for chunk in r.iter_content(chunk_size):
        #             fd.write(chunk)
        if len(model_instance) == 1:
            self._postprocess_report(
                result_path, model_instance.id, save_in_attachment)
        return result_path
Exemple #27
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])
Exemple #28
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)
Exemple #29
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 = []
Exemple #30
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 ()