def do_receipt_deliver(self):
     envio = self._read_xml('parse')
     company_id = self.env['res.company'].search(
         [('vat', '=',
           self.format_rut(
               envio['EnvioDTE']['SetDTE']['Caratula']['RutReceptor']))],
         limit=1)
     id_seq = self.env.ref('l10n_cl_dte.response_sequence').id
     IdRespuesta = self.env['ir.sequence'].browse(id_seq).next_by_id()
     try:
         signature_d = self.env['account.invoice'].get_digital_signature(
             company_id)
     except:
         raise UserError(
             _('''There is no Signer Person with an \
     authorized signature for you in the system. Please make sure that \
     'user_signature_key' module has been installed and enable a digital \
     signature, for you or make the signer to authorize you to use his \
     signature.'''))
     certp = signature_d['cert'].replace(BC,
                                         '').replace(EC,
                                                     '').replace('\n', '')
     recep = self._receipt(IdRespuesta)
     NroDetalles = len(envio['EnvioDTE']['SetDTE']['DTE'])
     dicttoxml.set_debug(False)
     resp_dtes = dicttoxml.dicttoxml(recep, root=False,
                                     attr_type=False).replace(
                                         '<item>',
                                         '\n').replace('</item>', '\n')
     RecepcionEnvio = '''<RecepcionEnvio>
                 {0}
                 </RecepcionEnvio>
                 '''.format(resp_dtes)
     RutRecibe = envio['EnvioDTE']['SetDTE']['Caratula']['RutEmisor']
     caratula_recepcion_envio = self._caratula_respuesta(
         self.env['account.invoice'].format_vat(company_id.vat), RutRecibe,
         IdRespuesta, NroDetalles)
     caratula = dicttoxml.dicttoxml(caratula_recepcion_envio,
                                    root=False,
                                    attr_type=False).replace(
                                        '<item>',
                                        '\n').replace('</item>', '\n')
     resp = self._RecepcionEnvio(caratula, RecepcionEnvio)
     respuesta = self.inv.sign_full_xml(resp, signature_d['priv_key'],
                                        certp, 'Odoo_resp', 'env_resp')
     if self.inv:
         self.inv.sii_xml_response = respuesta
     att = self._create_attachment(
         respuesta, 'recepcion_envio_' +
         (self.filename or self.inv.sii_send_file_name) + '_' +
         str(IdRespuesta))
     if self.inv.partner_id and att:
         self.inv.message_post(
             body='XML de Respuesta Envío, Estado: %s , Glosa: %s ' %
             (recep['EstadoRecepEnv'], recep['RecepEnvGlosa']),
             subject='XML de Respuesta Envío',
             partner_ids=[self.inv.partner_id.id],
             attachment_ids=[att.id],
             message_type='comment',
             subtype='mt_comment')
Exemplo n.º 2
0
 def _crear_envio_cesion(self):
     dicttoxml.set_debug(False)
     try:
         signature_d = self.get_digital_signature(self.company_id)
     except:
         raise UserError(
             _('''There is no Signer Person with an \
     authorized signature for you in the system. Please make sure that \
     'user_signature_key' module has been installed and enable a digital \
     signature, for you or make the signer to authorize you to use his \
     signature.'''))
     certp = signature_d['cert'].replace(BC,
                                         '').replace(EC,
                                                     '').replace('\n', '')
     file_name = "AEC_1"
     file_name += ".xml"
     DTECedido = self._cesion_dte(certp, signature_d['priv_key'])
     Cesion = self._cesion(certp, signature_d['priv_key'])
     caratulado = self._caratula_aec(DTECedido + '\n' + Cesion, )
     envio_cesion_dte = self._crear_envio_aec(caratulado)
     envio_dte = self.sign_full_xml(
         envio_cesion_dte,
         signature_d['priv_key'],
         certp,
         'Doc1',
         'aec',
     )
     return envio_dte, file_name
Exemplo n.º 3
0
 def do_validar_comercial(self):
     id_seq = \
         self.env.ref("l10n_cl_electronic_invoicing.response_sequence").id
     IdRespuesta = self.env["ir.sequence"].browse(id_seq).next_by_id()
     NroDetalles = 1
     dicttoxml.set_debug(False)
     for inv in self.invoice_ids:
         if inv.claim in ["ACD", "RCD"]:
             continue
         dte = self._resultado(
             TipoDTE=inv.sii_document_class_id.sii_code,
             Folio=inv.reference,
             FchEmis=inv.date_invoice,
             RUTEmisor=inv.format_vat(inv.partner_id.vat),
             RUTRecep=inv.format_vat(inv.company_id.vat),
             MntTotal=int(round(inv.amount_total, 0)),
             IdRespuesta=IdRespuesta,
         )
         ResultadoDTE = (dicttoxml.dicttoxml(
             dte, root=False, attr_type=False).decode().replace(
                 "<item>", "\n").replace("</item>", "\n"))
         RutRecibe = inv.format_vat(inv.partner_id.vat)
         caratula_validacion_comercial = self._caratula_respuesta(
             inv.format_vat(inv.company_id.vat), RutRecibe, IdRespuesta,
             NroDetalles)
         caratula = (dicttoxml.dicttoxml(caratula_validacion_comercial,
                                         root=False,
                                         attr_type=False).decode().replace(
                                             "<item>",
                                             "\n").replace("</item>", "\n"))
         resp = self._ResultadoDTE(caratula, ResultadoDTE)
         respuesta = ('<?xml version="1.0" encoding="ISO-8859-1"?>\n' +
                      inv.sign_full_xml(
                          resp.replace(
                              '<?xml version="1.0"'
                              ' encoding="ISO-8859-1"?>\n', ""),
                          "Odoo_resp",
                          "env_resp",
                      ))
         inv.sii_message = respuesta
         att = self._create_attachment(
             respuesta, "validacion_comercial_" + str(IdRespuesta))
         inv.message_post(
             body=(
                 _("XML of Commercial Validation, State: %s, Comment: %s") %
                 (dte["ResultadoDTE"]["EstadoDTE"],
                  dte["ResultadoDTE"]["EstadoDTEGlosa"])),
             subject=_("XML of Commercial Validation"),
             partner_ids=[inv.partner_id.id],
             attachment_ids=att.ids,
             message_type="comment",
             subtype="mt_comment",
         )
         inv.claim = "ACD"
         try:
             inv.set_dte_claim(
                 rut_emisor=inv.format_vat(inv.partner_id.vat))
         except:
             _logger.warning("TODO crear código que encole la respuesta")
Exemplo n.º 4
0
    def get_barcode(self, no_product=False):
        partner_id = self.partner_id or self.company_id.partner_id
        ted = False
        RutEmisor = self.format_vat(self.company_id.vat)
        result['TED']['DD']['RE'] = RutEmisor
        result['TED']['DD']['TD'] = self.location_id.sii_document_class_id.sii_code
        result['TED']['DD']['F']  = self.get_folio()
        result['TED']['DD']['FE'] = fields.Datetime.context_timestamp(self.with_context(tz='America/Santiago'), fields.Datetime.from_string(self.scheduled_date)).strftime(DF)
        if not partner_id.commercial_partner_id.vat:
            raise UserError(_("Fill Partner VAT"))
        result['TED']['DD']['RR'] = self.format_vat(partner_id.commercial_partner_id.vat)
        result['TED']['DD']['RSR'] = self._acortar_str(partner_id.commercial_partner_id.name,40)
        result['TED']['DD']['MNT'] = int(round(self.amount_total))
        if no_product:
            result['TED']['DD']['MNT'] = 0
        for line in self.move_lines:
            result['TED']['DD']['IT1'] = self._acortar_str(line.product_id.name,40)
            if line.product_id.default_code:
                result['TED']['DD']['IT1'] = self._acortar_str(line.product_id.name.replace('['+line.product_id.default_code+'] ',''),40)
            break

        resultcaf = self.location_id.sequence_id.get_caf_file()
        result['TED']['DD']['CAF'] = resultcaf['AUTORIZACION']['CAF']
        if RutEmisor != result['TED']['DD']['CAF']['DA']['RE']:
            raise UserError(_('NO coincide el Dueño del CAF : %s con el emisor Seleccionado: %s' %(result['TED']['DD']['CAF']['DA']['RE'], RutEmisor)))
        dte = result['TED']['DD']
        timestamp = self.time_stamp()
        picking_date = fields.Datetime.context_timestamp(self.with_context(tz='America/Santiago'), fields.Datetime.from_string(self.date)).strftime(DTF)
        if date( int(timestamp[:4]), int(timestamp[5:7]), int(timestamp[8:10])) < date(int(picking_date[:4]), int(picking_date[5:7]), int(picking_date[8:10])):
            raise UserError("La fecha de timbraje no puede ser menor a la fecha de emisión del documento")
        dte['TSTED'] = timestamp
        dicttoxml.set_debug(False)
        ddxml = '<DD>'+dicttoxml.dicttoxml(
            dte, root=False, attr_type=False).decode().replace(
            '<key name="@version">1.0</key>','',1).replace(
            '><key name="@version">1.0</key>',' version="1.0">',1).replace(
            '><key name="@algoritmo">SHA1withRSA</key>',
            ' algoritmo="SHA1withRSA">').replace(
            '<key name="#text">','').replace(
            '</key>','').replace('<CAF>','<CAF version="1.0">')+'</DD>'
        keypriv = resultcaf['AUTORIZACION']['RSASK'].replace('\t','')
        root = etree.XML( ddxml )
        ddxml = etree.tostring(root)
        frmt = self.signmessage(ddxml, keypriv)
        ted = (
            '''<TED version="1.0">{}<FRMT algoritmo="SHA1withRSA">{}\
</FRMT></TED>''').format(ddxml.decode(), frmt)
        self.sii_barcode = ted
        image = False
        if ted:
            barcodefile = BytesIO()
            image = self.pdf417bc(ted)
            image.save(barcodefile,'PNG')
            data = barcodefile.getvalue()
            self.sii_barcode_img = base64.b64encode(data)
        ted  += '<TmstFirma>{}</TmstFirma>'.format(timestamp)
        return ted
Exemplo n.º 5
0
    def get_barcode(self, no_product=False):
        util_model = self.env['cl.utils']
        fields_model = self.env['ir.fields.converter']
        from_zone = pytz.UTC
        to_zone = pytz.timezone('America/Santiago')
        date_order = util_model._change_time_zone(
            datetime.strptime(self.date_order, DTF), from_zone,
            to_zone).strftime(DTF)
        ted = False
        folio = self.get_folio()
        result['TED']['DD']['RE'] = self.format_vat(self.company_id.vat)
        result['TED']['DD']['TD'] = self.document_class_id.sii_code
        result['TED']['DD']['F'] = folio
        result['TED']['DD']['FE'] = date_order[:10]
        result['TED']['DD']['RR'] = self.format_vat(self.partner_id.vat)
        result['TED']['DD']['RSR'] = self._acortar_str(
            self.partner_id.name or 'Usuario Anonimo', 40)
        amount_total = int(round(self.amount_total))
        if amount_total < 0:
            amount_total *= -1
        result['TED']['DD']['MNT'] = amount_total
        if no_product:
            result['TED']['DD']['MNT'] = 0
        lines = self.lines
        sorted(lines, key=lambda e: e.pos_order_line_id)
        result['TED']['DD']['IT1'] = self._acortar_str(
            lines[0].product_id.with_context(display_default_code=False,
                                             lang='es_CL').name, 40)
        resultcaf = self.sequence_id.get_caf_file(folio)
        result['TED']['DD']['CAF'] = resultcaf['AUTORIZACION']['CAF']
        dte = result['TED']['DD']
        timestamp = date_order.replace(' ', 'T')
        #if date( int(timestamp[:4]), int(timestamp[5:7]), int(timestamp[8:10])) < date(int(self.date[:4]), int(self.date[5:7]), int(self.date[8:10])):
        #    raise UserError("La fecha de timbraje no puede ser menor a la fecha de emisión del documento")
        dte['TSTED'] = timestamp
        dicttoxml.set_debug(False)
        ddxml = '<DD>' + dicttoxml.dicttoxml(
            dte, root=False, attr_type=False
        ).decode().replace('<key name="@version">1.0</key>', '', 1).replace(
            '><key name="@version">1.0</key>', ' version="1.0">', 1).replace(
                '><key name="@algoritmo">SHA1withRSA</key>',
                ' algoritmo="SHA1withRSA">').replace(
                    '<key name="#text">', '').replace('</key>', '').replace(
                        '<CAF>', '<CAF version="1.0">') + '</DD>'
        keypriv = resultcaf['AUTORIZACION']['RSASK'].replace('\t', '')
        root = etree.XML(ddxml)
        ddxml = etree.tostring(root)
        frmt = self.env['account.invoice'].signmessage(ddxml, keypriv)
        ted = ('''<TED version="1.0">{}<FRMT algoritmo="SHA1withRSA">{}\
</FRMT></TED>''').format(ddxml.decode(), frmt)
        if self.signature and ted != self.signature:
            _logger.warning(ted)
            _logger.warning(self.signature)
            _logger.warning("¡La firma del pos es distinta a la del Backend!")
        self.sii_barcode = ted
        ted += '<TmstFirma>{}</TmstFirma>'.format(timestamp)
        return ted
Exemplo n.º 6
0
 def save_joke_on_disk(self, idx, joke):
     if not os.path.exists(self.out_dir):
         os.makedirs(self.out_dir)
     with open("{0}/joke-{1}.json".format(self.out_dir, idx), "w") as f:
         data = json.dumps(joke, encoding='utf-8', ensure_ascii=False)
         f.write(data.encode("utf-8"))
     with open("{0}/joke-{1}.xml".format(self.out_dir, idx), "w") as f:
         dicttoxml.set_debug()
         joke['votes'] = str(joke['votes'])
         joke['id'] = str(joke['id'])
         joke['comments_count'] = str(joke['comments_count'])
         xml = dicttoxml.dicttoxml(joke)
         f.write(xml.encode('utf-8'))
 def do_validar_comercial(self):
     id_seq = self.env.ref('l10n_cl_dte.response_sequence').id
     IdRespuesta = self.env['ir.sequence'].browse(id_seq).next_by_id()
     for inv in self.inv:
         if inv.estado_recep_dte not in ['0']:
             try:
                 signature_d = inv.get_digital_signature(inv.company_id)
             except:
                 raise UserError(
                     _('''There is no Signer Person with an \
             authorized signature for you in the system. Please make sure that \
             'user_signature_key' module has been installed and enable a digital \
             signature, for you or make the signer to authorize you to use his \
             signature.'''))
             certp = signature_d['cert'].replace(BC, '').replace(
                 EC, '').replace('\n', '')
             dte = self._resultado(IdRespuesta)
     envio = self._read_xml('parse')
     NroDetalles = len(envio['EnvioDTE']['SetDTE']['DTE'])
     if 'Documento' in envio['EnvioDTE']['SetDTE']['DTE']:
         NroDetalles = 1
     dicttoxml.set_debug(False)
     ResultadoDTE = dicttoxml.dicttoxml(dte, root=False,
                                        attr_type=False).replace(
                                            '<item>',
                                            '\n').replace('</item>', '\n')
     RutRecibe = envio['EnvioDTE']['SetDTE']['Caratula']['RutEmisor']
     caratula_validacion_comercial = self._caratula_respuesta(
         self.env['account.invoice'].format_vat(inv.company_id.vat),
         RutRecibe, IdRespuesta, NroDetalles)
     caratula = dicttoxml.dicttoxml(caratula_validacion_comercial,
                                    root=False,
                                    attr_type=False).replace(
                                        '<item>',
                                        '\n').replace('</item>', '\n')
     resp = self._ResultadoDTE(caratula, ResultadoDTE)
     respuesta = self.inv.sign_full_xml(resp, signature_d['priv_key'],
                                        certp, 'Odoo_resp', 'env_resp')
     if self.inv:
         self.inv.sii_message = respuesta
     att = self._create_attachment(
         respuesta, 'validacion_comercial_' + str(IdRespuesta))
     self.inv.message_post(
         body='XML de Validación Comercial, Estado: %s, Glosa: %s' %
         (dte['ResultadoDTE']['EstadoDTE'],
          dte['ResultadoDTE']['EstadoDTEGlosa']),
         subject='XML de Validación Comercial',
         partner_ids=[self.inv.partner_id.id],
         attachment_ids=[att.id],
         message_type='comment',
         subtype='mt_comment')
Exemplo n.º 8
0
async def change_order_state(**kwargs):
    order_id = kwargs['ORDER_ID']
    need_state = kwargs['NEED_STATE']
    result = {
        'response': {
            'code': 0,
            'descr': 'OK',
            'data': {
                'order_id': order_id,
                'new_state': need_state
            },
        },
    }
    dicttoxml.set_debug(False)
    result = dicttoxml.dicttoxml(result, root=False, attr_type=False)
    return result
Exemplo n.º 9
0
 async def get(self, request):
     # self.set_status(200, 'OK')
     tornado.log.logging.info(self.request.arguments)
     uri, params = tornado.escape.url_unescape(self.request.uri).split('?')
     params = {p.split('=')[0]: p.split('=')[1] for p in params.split('&')}
     order_id = int(params['order_id'])
     # response = await tmtapi.requests['get_info_by_order_id'](params)
     order = list(filter(lambda x: x['id'] == order_id, tmtapi.ORDERS))[0]
     tornado.log.logging.info(order)
     crew = list(filter(lambda x: x['id'] == order['crew_id'], tmtapi.CREWS))[0]
     car = list(filter(lambda x: x['id'] == crew['car_id'], tmtapi.CARS))[0]
     data = {}
     response = {'response': {'code': 0, 'descr': 'OK', 'data': data}, }
     data.update(car_id=car['id'])
     data.update({k: v for k, v in car.items() if k != 'id'})
     data.update(order_id=order_id)
     data.update({k: v for k, v in order.items() if k != 'id'})
     dicttoxml.set_debug(False)
     response = dicttoxml.dicttoxml(response, root=False, attr_type=False)
     tornado.log.logging.info(response)
     self.write(response)
Exemplo n.º 10
0
async def get_info_by_order_id(order_data):
    # order_data = kwargs
    tornado.log.logging.info(f'{order_data}')
    if 'fields' in order_data.keys():
        order_data['fields'] = tuple(
            [f for f in order_data['fields'].split('-')])
    order_id = order_data['order_id']
    result = {
        'response': {
            'code': 0,
            'descr': 'OK',
            'data': {},
        },
    }
    for r in order_data['fields']:
        result['response']['data'][r] = ''

    dicttoxml.set_debug(False)
    result = dicttoxml.dicttoxml(result, root=False, attr_type=False)
    # result = xmltodict.parse(result)
    tornado.log.logging.info(result)
    return result
Exemplo n.º 11
0
    def __call__(self, model_description, system):
        """ Call the renderer implementation with the value
        and the system value passed in as arguments and return
        the result (a string or unicode object).  The value is
        the return value of a view.  The system value is a
        dictionary containing available system values
        (e.g. view, context, and request). """

        request = system['request']
        dicttoxml.set_debug(False)
        val = dicttoxml.dicttoxml(model_description.as_dict(), attr_type=False)
        # print val
        callback = request.GET.get('callback')
        if callback is None:
            ct = 'text/xml'
            body = val
        else:
            ct = 'text/xml'
            body = '%s(%s);' % (callback, val)
        response = request.response
        if response.content_type == response.default_content_type:
            response.content_type = ct
        return body
Exemplo n.º 12
0
    def __call__(self, model_description, system):
        """ Call the renderer implementation with the value
        and the system value passed in as arguments and return
        the result (a string or unicode object).  The value is
        the return value of a view.  The system value is a
        dictionary containing available system values
        (e.g. view, context, and request). """

        request = system['request']
        dicttoxml.set_debug(False)
        val = dicttoxml.dicttoxml(model_description.as_dict(), attr_type=False)
        # print val
        callback = request.GET.get('callback')
        if callback is None:
            ct = 'text/xml'
            body = val
        else:
            ct = 'text/xml'
            body = '%s(%s);' % (callback, val)
        response = request.response
        if response.content_type == response.default_content_type:
            response.content_type = ct
        return body
Exemplo n.º 13
0
    def do_dte_send(self, n_atencion=None):
        dicttoxml.set_debug(False)
        DTEs = {}
        clases = {}
        company_id = False
        for inv in self.with_context(lang='es_CL'):
            #@TODO Mejarorar esto en lo posible
            if not inv.document_class_id.sii_code in clases:
                clases[inv.document_class_id.sii_code] = []
            clases[inv.document_class_id.sii_code].extend([{
                'id':
                inv.id,
                'envio':
                inv.sii_xml_dte,
                'sii_document_number':
                inv.sii_document_number
            }])
            DTEs.update(clases)
            if not company_id:
                company_id = inv.company_id
            elif company_id.id != inv.company_id.id:
                raise UserError(
                    "Está combinando compañías, no está permitido hacer eso en un envío"
                )
            company_id = inv.company_id

        file_name = {}
        dtes = {}
        SubTotDTE = {}
        documentos = {}
        resol_data = self.get_resolution_data(company_id)
        signature_d = self.env.user.get_digital_signature(company_id)
        RUTEmisor = self.format_vat(company_id.vat)

        for id_class_doc, classes in clases.items():
            NroDte = 0
            documentos[id_class_doc] = ''
            for documento in classes:
                documentos[id_class_doc] += '\n' + documento['envio']
                NroDte += 1
                if not str(id_class_doc) in file_name:
                    file_name[str(id_class_doc)]
                file_name[str(id_class_doc)] += 'F' + str(
                    int(documento['sii_document_number'])) + 'T' + str(
                        id_class_doc)
            SubTotDTE[id_class_doc] = '<SubTotDTE>\n<TpoDTE>' + str(
                id_class_doc) + '</TpoDTE>\n<NroDTE>' + str(
                    NroDte) + '</NroDTE>\n</SubTotDTE>\n'
        file_name += ".xml"
        # firma del sobre
        RUTRecep = "60803000-K"  # RUT SII
        for id_class_doc, documento in documentos.items():
            dtes = self.create_template_envio(
                RUTEmisor, RUTRecep, resol_data['dte_resolution_date'],
                resol_data['dte_resolution_number'], self.time_stamp(),
                documento, signature_d, SubTotDTE[id_class_doc])
            env = 'env'
            if self._es_boleta(id_class_doc):
                envio_dte = self.create_template_env_boleta(dtes)
                env = 'env_boleta'
            else:
                envio_dte = self.create_template_env(dtes)
            envio_dte = self.env['account.invoice'].sudo(
                self.env.uid).sign_full_xml(
                    envio_dte,
                    'SetDoc',
                    env,
                )
            envio_id = self.env['sii.xml.envio'].create({
                'sii_xml_request':
                '<?xml version="1.0" encoding="ISO-8859-1"?>\n' + envio_dte,
                'name':
                file_name[str(id_class_doc)],
                'company_id':
                company_id.id,
                'user_id':
                self.env.uid,
            })
            if env == 'env':
                envio_id.send_xml()
            for order in self:
                if order.document_class_id.sii_code == id_class_doc:
                    order.sii_xml_request = envio_dte.id
Exemplo n.º 14
0
    def document_received(self):
        date = pysiidte.time_stamp()
        inv_obj = self.env['account.invoice']

        for message_id in self.message_ids:
            for attachment_id in message_id.attachment_ids:
                # if not (attachment_id.mimetype in [
                #    'text/plain'] and attachment_id.name.lower().find('.xml')):
                #    _logger.info(u'El adjunto no es un XML. Revisando otro...')
                #    continue
                _logger.info('El adjunto es un XML')
                xml = self._get_xml_content(attachment_id.datas)
                soup = bs(xml, 'xml')  # se crea un arbol de xml
                envio_dte = soup.find_all('EnvioDTE')  # busqueda

                if envio_dte:
                    # signature_d = inv_obj.get_digital_signature(
                    # self.env.user.company_id)
                    try:
                        signature_d = inv_obj.get_digital_signature(
                            self.env.user.company_id)
                    except:
                        raise UserError(
                            _('''There is no Signer Person with \
an authorized signature for you in the system. Please make sure that \
'user_signature_key' module has been installed and enable a digital \
signature, for you or make the signer to authorize you to use his \
signature.'''))
                    certp = signature_d['cert'].replace(BC, '').replace(
                        EC, '').replace('\n', '')
                    tz = pytz.timezone('America/Santiago')
                    day = datetime.now(tz).strftime('%y%d%H%M')
                    idrespuesta = day
                    caratula = collections.OrderedDict()
                    caratula['RutResponde'] = '{}'.format(
                        soup.RutReceptor.string)
                    caratula['RutRecibe'] = '{}'.format(soup.RUTEmisor.string)
                    caratula['IdRespuesta'] = idrespuesta
                    caratula['NroDetalles'] = 1
                    caratula['TmstFirmaResp'] = date

                    caratula_xml = dicttoxml.dicttoxml(caratula,
                                                       root=False,
                                                       attr_type=False)
                    fecha = datetime.strptime(
                        message_id.date,
                        '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%dT%H:%M:%S')
                    RecepcionEnvio = collections.OrderedDict()
                    RecepcionEnvio['NmbEnvio'] = '{}'.format(
                        attachment_id.name)
                    RecepcionEnvio['FchRecep'] = fecha
                    RecepcionEnvio['CodEnvio'] = idrespuesta
                    RecepcionEnvio['EnvioDTEID'] = soup.Documento['ID']
                    # soup.SetDTE['ID']
                    RecepcionEnvio['Digest'] = '{}'.format(
                        soup.DigestValue.string)
                    RecepcionEnvio['RutEmisor'] = '{}'.format(
                        soup.RUTEmisor.string)
                    RecepcionEnvio['RutReceptor'] = '{}'.format(
                        soup.RUTRecep.string)
                    RecepcionEnvio['EstadoRecepEnv'] = '0'
                    RecepcionEnvio['RecepEnvGlosa'] = 'Envio Recibido Conforme'

                    recepcionenvio_xml = dicttoxml.dicttoxml(
                        RecepcionEnvio,
                        root=False,
                        attr_type=False,
                    )
                    dicttoxml.set_debug(False)
                    xml = '''<?xml version="1.0" encoding="ISO-8859-1"?>
                    <RespuestaDTE xmlns="http://www.sii.cl/SiiDte" \
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" \
xsi:schemaLocation="http://www.sii.cl/SiiDte RespuestaEnvioDTE_v10.xsd">
                        <Resultado ID="Odoo_resp">
                            <Caratula version="1.0">
                                {0}
                            </Caratula>
                            <RecepcionEnvio>
                                {1}
                            </RecepcionEnvio>
                        </Resultado>
                    </RespuestaDTE>
                    '''.format(caratula_xml, recepcionenvio_xml)
                    acuse_recibo = inv_obj.sign_full_xml(
                        xml, signature_d['priv_key'],
                        inv_obj.split_cert(certp), 'Odoo_resp', 'env_resp')
                    _logger.info('estamos por crear')
                    self.save_xml_knowledge(acuse_recibo,
                                            'received_{}'.format(idrespuesta))
                    self.sii_xml_request = acuse_recibo
Exemplo n.º 15
0
 def do_validar_comercial(self):
     id_seq = self.env.ref('l10n_cl_fe.response_sequence').id
     IdRespuesta = self.env['ir.sequence'].browse(id_seq).next_by_id()
     NroDetalles = 1
     dicttoxml.set_debug(False)
     for inv in self.invoice_ids:
         if inv.claim in ['ACD', 'RCD']:
             continue
         dte = self._resultado(
             TipoDTE=inv.document_class_id.sii_code,
             Folio=inv.reference,
             FchEmis=inv.date_invoice,
             RUTEmisor=inv.format_vat(inv.partner_id.vat),
             RUTRecep=inv.format_vat(inv.company_id.vat),
             MntTotal=int(round(inv.amount_total, 0)),
             IdRespuesta=IdRespuesta,
         )
         ResultadoDTE = dicttoxml.dicttoxml(
             dte,
             root=False,
             attr_type=False,
         ).decode().replace('<item>', '\n').replace('</item>', '\n')
         RutRecibe = inv.format_vat(inv.partner_id.vat)
         caratula_validacion_comercial = self._caratula_respuesta(
             inv.format_vat(inv.company_id.vat),
             RutRecibe,
             IdRespuesta,
             NroDetalles,
         )
         caratula = dicttoxml.dicttoxml(
             caratula_validacion_comercial,
             root=False,
             attr_type=False,
         ).decode().replace('<item>', '\n').replace('</item>', '\n')
         resp = self._ResultadoDTE(
             caratula,
             ResultadoDTE,
         )
         respuesta = '<?xml version="1.0" encoding="ISO-8859-1"?>\n' + inv.sign_full_xml(
             resp.replace('<?xml version="1.0" encoding="ISO-8859-1"?>\n',
                          ''),
             'Odoo_resp',
             'env_resp',
         )
         inv.sii_message = respuesta
         att = self._create_attachment(
             respuesta,
             'validacion_comercial_' + str(IdRespuesta),
         )
         dte_email_id = inv.company_id.dte_email_id or self.env.user.company_id.dte_email_id
         values = {
             'res_id':
             inv.id,
             'email_from':
             dte_email_id.name_get()[0][1],
             'email_to':
             inv.commercial_partner_id.dte_email,
             'auto_delete':
             False,
             'model':
             "account.invoice",
             'body':
             'XML de Validación Comercial, Estado: %s, Glosa: %s' %
             (dte['ResultadoDTE']['EstadoDTE'],
              dte['ResultadoDTE']['EstadoDTEGlosa']),
             'subject':
             'XML de Validación Comercial',
             'attachment_ids': [[6, 0, att.ids]],
         }
         send_mail = self.env['mail.mail'].create(values)
         send_mail.send()
         inv.claim = 'ACD'
         try:
             inv.set_dte_claim(rut_emisor=inv.format_vat(
                 inv.partner_id.vat), )
         except:
             _logger.warning("@TODO crear código que encole la respuesta")
Exemplo n.º 16
0
    def do_reject(self, document_ids):
        dicttoxml.set_debug(False)
        inv_obj = self.env['account.invoice']
        id_seq = self.env.ref('l10n_cl_fe.response_sequence').id
        IdRespuesta = self.env['ir.sequence'].browse(id_seq).next_by_id()
        NroDetalles = 1
        for doc in document_ids:
            xml = xmltodict.parse(doc.xml)['DTE']['Documento']
            dte = self._resultado(
                TipoDTE=xml['Encabezado']['IdDoc']['TipoDTE'],
                Folio=xml['Encabezado']['IdDoc']['Folio'],
                FchEmis=xml['Encabezado']['IdDoc']['FchEmis'],
                RUTEmisor=xml['Encabezado']['Emisor']['RUTEmisor'],
                RUTRecep=xml['Encabezado']['Receptor']['RUTRecep'],
                MntTotal=xml['Encabezado']['Totales']['MntTotal'],
                IdRespuesta=IdRespuesta,
            )
            ResultadoDTE = dicttoxml.dicttoxml(
                dte,
                root=False,
                attr_type=False,
            ).decode().replace('<item>', '\n').replace('</item>', '\n')
            RutRecibe = xml['Encabezado']['Emisor']['RUTEmisor']
            caratula_validacion_comercial = self._caratula_respuesta(
                xml['Encabezado']['Receptor']['RUTRecep'], RutRecibe,
                IdRespuesta, NroDetalles)
            caratula = dicttoxml.dicttoxml(caratula_validacion_comercial,
                                           root=False,
                                           attr_type=False).replace(
                                               '<item>',
                                               '\n').replace('</item>', '\n')
            resp = self._ResultadoDTE(
                caratula,
                ResultadoDTE,
            )
            respuesta = '<?xml version="1.0" encoding="ISO-8859-1"?>\n' + inv_obj.sign_full_xml(
                resp.replace('<?xml version="1.0" encoding="ISO-8859-1"?>\n',
                             ''), 'Odoo_resp', 'env_resp')
            att = self._create_attachment(
                respuesta,
                'rechazo_comercial_' + str(IdRespuesta),
                id=doc.id,
                model="mail.message.dte.document",
            )
            partners = doc.partner_id.ids
            if not doc.partner_id:
                if att:
                    values = {
                        'model_id':
                        doc.id,
                        'email_from':
                        doc.company_id.dte_email,
                        'email_to':
                        doc.dte_id.sudo().mail_id.email_from,
                        'auto_delete':
                        False,
                        'model':
                        "mail.message.dte.document",
                        'body':
                        'XML de Respuesta Envío, Estado: %s , Glosa: %s ' %
                        (resp['EstadoRecepEnv'], resp['RecepEnvGlosa']),
                        'subject':
                        'XML de Respuesta Envío',
                        'attachment_ids': [[6, 0, att.ids]],
                    }
                    send_mail = self.env['mail.mail'].create(values)
                    send_mail.send()
            doc.message_post(
                body='XML de Rechazo Comercial, Estado: %s, Glosa: %s' %
                (dte['ResultadoDTE']['EstadoDTE'],
                 dte['ResultadoDTE']['EstadoDTEGlosa']),
                subject='XML de Validación Comercial',
                partner_ids=partners,
                attachment_ids=[att.id],
                message_type='comment',
                subtype='mt_comment',
            )

            inv_obj.set_dte_claim(
                rut_emisor=xml['Encabezado']['Emisor']['RUTEmisor'],
                company_id=doc.company_id,
                sii_document_number=doc.number,
                sii_document_class_id=doc.sii_document_class_id,
                claim='RCD',
            )
Exemplo n.º 17
0
    def do_reject(self, document_ids):
        dicttoxml.set_debug(False)
        inv_obj = self.env['account.invoice']
        id_seq = self.env.ref('l10n_cl_dte.response_sequence').id
        IdRespuesta = self.env['ir.sequence'].browse(id_seq).next_by_id()
        NroDetalles = 1
        for doc in document_ids:
            try:
                signature_d = inv_obj.get_digital_signature(doc.company_id)
            except:
                raise UserError(
                    _('''There is no Signer Person with an \
            authorized signature for you in the system. Please make sure that \
            'user_signature_key' module has been installed and enable a digital \
            signature, for you or make the signer to authorize you to use his \
            signature.'''))
            certp = signature_d['cert'].replace(BC, '').replace(EC,
                                                                '').replace(
                                                                    '\n', '')
            xml = xmltodict.parse(doc.xml)['DTE']['Documento']
            dte = self._resultado(
                TipoDTE=xml['Encabezado']['IdDoc']['TipoDTE'],
                Folio=xml['Encabezado']['IdDoc']['Folio'],
                FchEmis=xml['Encabezado']['IdDoc']['FchEmis'],
                RUTEmisor=xml['Encabezado']['Emisor']['RUTEmisor'],
                RUTRecep=xml['Encabezado']['Receptor']['RUTRecep'],
                MntTotal=xml['Encabezado']['Totales']['MntTotal'],
                IdRespuesta=IdRespuesta,
            )
            ResultadoDTE = dicttoxml.dicttoxml(
                dte,
                root=False,
                attr_type=False,
            ).replace('<item>', '\n').replace('</item>', '\n')
            RutRecibe = xml['Encabezado']['Emisor']['RUTEmisor']
            caratula_validacion_comercial = self._caratula_respuesta(
                xml['Encabezado']['Receptor']['RUTRecep'], RutRecibe,
                IdRespuesta, NroDetalles)
            caratula = dicttoxml.dicttoxml(caratula_validacion_comercial,
                                           root=False,
                                           attr_type=False).replace(
                                               '<item>',
                                               '\n').replace('</item>', '\n')
            resp = self._ResultadoDTE(
                caratula,
                ResultadoDTE,
            )
            respuesta = inv_obj.sign_full_xml(resp, signature_d['priv_key'],
                                              certp, 'Odoo_resp', 'env_resp')
            att = self._create_attachment(
                respuesta,
                'rechazo_comercial_' + str(IdRespuesta),
                id=doc.id,
                model="mail.message.dte.document",
            )
            partners = doc.partner_id.ids
            if not doc.partner_id:
                if att:
                    values = {
                        'model_id':
                        doc.id,
                        'email_from':
                        doc.company_id.dte_email,
                        'email_to':
                        doc.dte_id.sudo().mail_id.email_from,
                        'auto_delete':
                        False,
                        'model':
                        "mail.message.dte.document",
                        'body':
                        'XML de Respuesta Envío, Estado: %s , Glosa: %s ' %
                        (recep['EstadoRecepEnv'], recep['RecepEnvGlosa']),
                        'subject':
                        'XML de Respuesta Envío',
                        'attachment_ids':
                        att.ids,
                    }
                    send_mail = self.env['mail.mail'].create(values)
                    send_mail.send()
            doc.message_post(
                body='XML de Rechazo Comercial, Estado: %s, Glosa: %s' %
                (dte['ResultadoDTE']['EstadoDTE'],
                 dte['ResultadoDTE']['EstadoDTEGlosa']),
                subject='XML de Validación Comercial',
                partner_ids=partners,
                attachment_ids=[att.id],
                message_type='comment',
                subtype='mt_comment',
            )

            inv_obj.set_dte_claim(
                rut_emisor=xml['Encabezado']['Emisor']['RUTEmisor'],
                company_id=doc.company_id,
                sii_document_number=doc.number,
                sii_document_class_id=doc.sii_document_class_id,
                claim='RCD',
            )
Exemplo n.º 18
0
    def do_reject(self, document_ids):
        dicttoxml.set_debug(False)
        inv_obj = self.env["account.invoice"]
        id_seq = \
            self.env.ref("l10n_cl_electronic_invoicing.response_sequence").id
        IdRespuesta = self.env["ir.sequence"].browse(id_seq).next_by_id()
        NroDetalles = 1
        for doc in document_ids:
            xml = xmltodict.parse(doc.xml)["DTE"]["Documento"]
            dte = self._resultado(
                TipoDTE=xml["Encabezado"]["IdDoc"]["TipoDTE"],
                Folio=xml["Encabezado"]["IdDoc"]["Folio"],
                FchEmis=xml["Encabezado"]["IdDoc"]["FchEmis"],
                RUTEmisor=xml["Encabezado"]["Emisor"]["RUTEmisor"],
                RUTRecep=xml["Encabezado"]["Receptor"]["RUTRecep"],
                MntTotal=xml["Encabezado"]["Totales"]["MntTotal"],
                IdRespuesta=IdRespuesta,
            )
            ResultadoDTE = (dicttoxml.dicttoxml(
                dte, root=False, attr_type=False).decode().replace(
                    "<item>", "\n").replace("</item>", "\n"))
            RutRecibe = xml["Encabezado"]["Emisor"]["RUTEmisor"]
            caratula_validacion_comercial = self._caratula_respuesta(
                xml["Encabezado"]["Receptor"]["RUTRecep"],
                RutRecibe,
                IdRespuesta,
                NroDetalles,
            )
            caratula = (dicttoxml.dicttoxml(caratula_validacion_comercial,
                                            root=False,
                                            attr_type=False).replace(
                                                "<item>",
                                                "\n").replace("</item>", "\n"))
            resp = self._ResultadoDTE(caratula, ResultadoDTE)
            respuesta = ('<?xml version="1.0" encoding="ISO-8859-1"?>\n' +
                         inv_obj.sign_full_xml(
                             resp.replace(
                                 '<?xml version="1.0"'
                                 ' encoding="ISO-8859-1"?>\n', ""),
                             "Odoo_resp",
                             "env_resp",
                         ))
            att = self._create_attachment(
                respuesta,
                "rechazo_comercial_" + str(IdRespuesta),
                id=doc.id,
                model="mail.message.dte.document",
            )
            partners = doc.partner_id.ids
            if not doc.partner_id:
                if att:
                    values = {
                        "model_id":
                        doc.id,
                        "email_from":
                        doc.company_id.dte_email,
                        "email_to":
                        doc.dte_id.sudo().mail_id.email_from,
                        "auto_delete":
                        False,
                        "model":
                        "mail.message.dte.document",
                        "body":
                        "XML de Respuesta Envío, Estado: %s ,"
                        " Glosa: %s " %
                        (resp["EstadoRecepEnv"], resp["RecepEnvGlosa"]),
                        "subject":
                        "XML de Respuesta Envío",
                        "attachment_ids": [[6, 0, att.ids]],
                    }
                    send_mail = self.env["mail.mail"].create(values)
                    send_mail.send()
            doc.message_post(
                body=(_("XML of Commercial Denial, State: %s, Comment: %s") %
                      (dte["ResultadoDTE"]["EstadoDTE"],
                       dte["ResultadoDTE"]["EstadoDTEGlosa"])),
                subject=_("XML of Commercial Denial"),
                partner_ids=partners,
                attachment_ids=att.ids,
                message_type="comment",
                subtype="mt_comment")

            inv_obj.set_dte_claim(
                rut_emisor=xml["Encabezado"]["Emisor"]["RUTEmisor"],
                company_id=doc.company_id,
                sii_document_number=doc.number,
                sii_document_class_id=doc.sii_document_class_id,
                claim="RCD")
Exemplo n.º 19
0
    def do_receipt_deliver(self):
        envio = self._read_xml('parse')
        if 'Caratula' not in envio['SetDTE']:
            return True
        company_id = self.env['res.company'].search(
            [('vat', '=',
              self.format_rut(envio['SetDTE']['Caratula']['RutReceptor']))],
            limit=1)
        id_seq = self.env.ref('l10n_cl_fe.response_sequence').id
        IdRespuesta = self.env['ir.sequence'].browse(id_seq).next_by_id()
        try:
            signature_d = self.env['account.invoice'].get_digital_signature(
                company_id)
        except:
            raise UserError(
                _('''There is no Signer Person with an \
        authorized signature for you in the system. Please make sure that \
        'user_signature_key' module has been installed and enable a digital \
        signature, for you or make the signer to authorize you to use his \
        signature.'''))
        certp = signature_d['cert'].replace(BC,
                                            '').replace(EC,
                                                        '').replace('\n', '')
        recep = self._receipt(IdRespuesta)
        NroDetalles = len(envio['SetDTE']['DTE'])
        dicttoxml.set_debug(False)
        resp_dtes = dicttoxml.dicttoxml(recep, root=False,
                                        attr_type=False).replace(
                                            '<item>',
                                            '\n').replace('</item>', '\n')
        RecepcionEnvio = '''
<RecepcionEnvio>
    {0}
</RecepcionEnvio>
        '''.format(resp_dtes, )
        RutRecibe = envio['SetDTE']['Caratula']['RutEmisor']
        caratula_recepcion_envio = self._caratula_respuesta(
            self.env['account.invoice'].format_vat(company_id.vat),
            RutRecibe,
            IdRespuesta,
            NroDetalles,
        )
        caratula = dicttoxml.dicttoxml(
            caratula_recepcion_envio,
            root=False,
            attr_type=False,
        ).replace('<item>', '\n').replace('</item>', '\n')
        resp = self._RecepcionEnvio(caratula, RecepcionEnvio)
        respuesta = self.env['account.invoice'].sign_full_xml(
            resp, signature_d['priv_key'], certp, 'Flectra_resp', 'env_resp')
        if self.dte_id:
            att = self._create_attachment(
                respuesta, 'recepcion_envio_' +
                (self.filename or self.dte_id.name) + '_' + str(IdRespuesta),
                self.dte_id.id, 'mail.message.dte')

            if att:
                values = {
                    'model_id':
                    self.dte_id.id,
                    'email_from':
                    self.dte_id.company_id.dte_email,
                    'email_to':
                    self.dte_id.mail_id.email_from,
                    'auto_delete':
                    False,
                    'model':
                    "mail.message.dte",
                    'body':
                    'XML de Respuesta Envío, Estado: %s , Glosa: %s ' %
                    (recep['EstadoRecepEnv'], recep['RecepEnvGlosa']),
                    'subject':
                    'XML de Respuesta Envío',
                    'attachment_ids':
                    att.ids,
                }
                send_mail = self.env['mail.mail'].create(values)
                send_mail.send()
            self.dte_id.message_post(
                body='XML de Respuesta Envío, Estado: %s , Glosa: %s ' %
                (recep['EstadoRecepEnv'], recep['RecepEnvGlosa']),
                subject='XML de Respuesta Envío',
                attachment_ids=att.ids,
                message_type='comment',
                subtype='mt_comment',
            )
Exemplo n.º 20
0
    def do_dte_send_book(self):
        dicttoxml.set_debug(False)
        cant_doc_batch = 0
        company_id = self.company_id
        dte_service = company_id.dte_service_provider
        try:
            signature_d = self.get_digital_signature(company_id)
        except:
            raise Warning(
                _('''There is no Signer Person with an \
        authorized signature for you in the system. Please make sure that \
        'user_signature_key' module has been installed and enable a digital \
        signature, for you or make the signer to authorize you to use his \
        signature.'''))
        certp = signature_d['cert'].replace(BC,
                                            '').replace(EC,
                                                        '').replace('\n', '')
        resumenes = []
        resumenesPeriodo = {}
        for rec in self.with_context(lang='es_CL').move_ids:
            rec.sended = True
            resumen = self.getResumen(rec)
            resumenes.extend([{'Detalle': resumen}])
            TpoDoc = resumen['TpoDoc']
            if not TpoDoc in resumenesPeriodo:
                resumenesPeriodo[TpoDoc] = {}
            resumenesPeriodo[TpoDoc] = self._setResumenPeriodo(
                resumen, resumenesPeriodo[TpoDoc])
        lista = [
            'TpoDoc',
            'TpoImp',
            'TotDoc',
            'TotAnulado',
            'TotMntExe',
            'TotMntNeto',
            'TotOpIVARec',
            'TotMntIVA',
            'TotMntIVA',
            'TotOpActivoFijo',
            'TotMntIVAActivoFijo',
            'itemNoRec',
            'TotOpIVAUsoComun',
            'TotIVAUsoComun',
            'FctProp',
            'TotCredIVAUsoComun',
            'itemOtrosImp',
            'TotImpSinCredito',
            'TotIVARetTotal',
            'TotIVARetParcial',
            'TotMntTotal',
            'TotIVANoRetenido',
            'TotTabPuros',
            'TotTabCigarrillos',
            'TotTabElaborado',
            'TotImpVehiculo',
        ]
        ResumenPeriodo = []
        for r, value in resumenesPeriodo.iteritems():
            total = collections.OrderedDict()
            for v in lista:
                if v in value:
                    total[v] = value[v]
            ResumenPeriodo.extend([{'TotalesPeriodo': total}])
        dte = collections.OrderedDict()
        dte['ResumenPeriodo'] = collections.OrderedDict()
        dte['ResumenPeriodo'] = ResumenPeriodo
        dte['item'] = resumenes
        dte['TmstFirma'] = self.time_stamp()

        resol_data = self.get_resolution_data(company_id)
        RUTEmisor = self.format_vat(company_id.vat)
        RUTRecep = "60803000-K"  # RUT SII
        xml = dicttoxml.dicttoxml(dte, root=False, attr_type=False)
        doc_id = self.tipo_operacion + '_' + self.periodo_tributario
        libro = self.create_template_envio(RUTEmisor, self.periodo_tributario,
                                           resol_data['dte_resolution_date'],
                                           resol_data['dte_resolution_number'],
                                           xml, signature_d,
                                           self.tipo_operacion,
                                           self.tipo_libro, self.tipo_envio,
                                           self.folio_notificacion, doc_id)
        xml = self.create_template_env(libro)
        root = etree.XML(xml)
        xml_pret = etree.tostring(root, pretty_print=True).replace(
            '<item>',
            '\n').replace('</item>', '').replace('<itemNoRec>', '').replace(
                '</itemNoRec>',
                '\n').replace('<itemOtrosImp>',
                              '').replace('</itemOtrosImp>', '\n')
        envio_dte = self.convert_encoding(xml_pret, 'ISO-8859-1')
        envio_dte = self.sign_full_xml(envio_dte, signature_d['priv_key'],
                                       certp, doc_id, 'libro')
        result = self.send_xml_file(envio_dte, doc_id + '.xml', company_id)
        self.write({
            'sii_xml_response': result['sii_xml_response'],
            'sii_send_ident': result['sii_send_ident'],
            'state': result['sii_result'],
            'sii_xml_request': envio_dte
        })
Exemplo n.º 21
0
import re
import urllib2
import urlparse

from agsci.atlas.utilities import toISO, encode_blob, getAllSchemas

# Custom Atlas Schemas
from agsci.atlas.content import atlas_schemas
from agsci.atlas.content.behaviors import IAtlasMetadata
from agsci.atlas.content.event.cvent import ICventEvent
from agsci.atlas.content.publication import IPublication

from ..interfaces import IAPIDataAdapter

# Prevent debug messages in log
dicttoxml.set_debug(False)

first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')

class BaseView(BrowserView):

    implements(IPublishTraverse)

    data_format = None
    valid_data_formats = ['json', 'xml']
    default_data_format = 'xml'

    # Default window for listing updated items
    default_updated = 3600
Exemplo n.º 22
0
    def receive_merchandise(self):
        # date = pysiidte.time_stamp()
        inv_obj = self.env['account.invoice']

        for message_id in self.message_ids:
            for attachment_id in message_id.attachment_ids:
                # if not (attachment_id.mimetype in [
                #    'text/plain'] and attachment_id.name.lower().find('.xml')):
                #    _logger.info(u'El adjunto no es un XML. Revisando otro...')
                #     continue
                _logger.info('El adjunto es un XML')
                xml = self._get_xml_content(attachment_id.datas)
                soup = bs(xml, 'xml')  # se crea un arbol de xml
                libro_guia = soup.find_all('EnvioDTE')  # busqueda

                if libro_guia:
                    signature_d = inv_obj.get_digital_signature(
                        self.env.user.company_id)
                    certp = signature_d['cert'].replace(BC, '').replace(
                        EC, '').replace('\n', '')
                    date = pysiidte.time_stamp()
                    caratula = collections.OrderedDict()
                    caratula['RutResponde'] = '{}'.format(soup.RUTRecep.string)
                    caratula['RutRecibe'] = '{}'.format(soup.RUTEmisor.string)
                    caratula['NmbContacto'] = self.env.user.partner_id.name
                    caratula['FonoContacto'] = self.env.user.partner_id.phone
                    caratula['MailContacto'] = self.env.user.partner_id.email
                    caratula['TmstFirmaEnv'] = date
                    caratula_xml = dicttoxml.dicttoxml(caratula,
                                                       root=False,
                                                       attr_type=False)
                    merchandise = collections.OrderedDict()
                    merchandise['TipoDoc'] = int(soup.TipoDTE.string)
                    merchandise['Folio'] = int(soup.Folio.string)
                    merchandise['FchEmis'] = '{}'.format(soup.FchEmis.string)
                    merchandise['RUTEmisor'] = '{}'.format(
                        soup.RUTEmisor.string)
                    merchandise['RUTRecep'] = '{}'.format(soup.RUTRecep.string)
                    merchandise['MntTotal'] = int(soup.MntTotal.string)
                    merchandise['Recinto'] = self.env.user.company_id.street
                    merchandise['RutFirma'] = signature_d[
                        'subject_serial_number']
                    merchandise['Declaracion'] = '''El acuse de recibo que \
se declara en este acto, de acuerdo a lo dispuesto en la letra b) del Art. 4, \
y la letra c) del Art. 5 de la Ley 19.983, acredita que la entrega de \
mercaderias o servicio(s) prestado(s) ha(n) sido recibido(s).'''
                    merchandise['TmstFirmaRecibo'] = date
                    merchandise_xml = dicttoxml.dicttoxml(
                        merchandise,
                        root=False,
                        attr_type=False,
                    )
                    dicttoxml.set_debug(False)
                    id = "T" + str(soup.TipoDTE.string) + "F" + str(
                        soup.Folio.string)
                    doc = '''<Recibo version="1.0" \
xmlns="http://www.sii.cl/SiiDte" \
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \
xsi:schemaLocation="http://www.sii.cl/SiiDte Recibos_v10.xsd">
                        <DocumentoRecibo ID="{0}" >
                        {1}
                        </DocumentoRecibo>
                    </Recibo>
                    '''.format(id, merchandise_xml)
                    recibo_merca = inv_obj.sign_full_xml(
                        doc, signature_d['priv_key'],
                        inv_obj.split_cert(certp), 'Recibo', 'recep')
                    xml = '''<?xml version="1.0" encoding="ISO-8859-1"?>
                    <EnvioRecibos xmlns='http://www.sii.cl/SiiDte' \
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \
xsi:schemaLocation='http://www.sii.cl/SiiDte EnvioRecibos_v10.xsd' \
version="1.0">
                        <SetRecibos ID="SetDteRecibidos">
                            <Caratula version="1.0">
                            {0}
                            </Caratula>
                            {1}
                        </SetRecibos>
                    </EnvioRecibos>'''.format(caratula_xml, recibo_merca)
                    envio_dte = inv_obj.sign_full_xml(xml,
                                                      signature_d['priv_key'],
                                                      certp, 'SetDteRecibidos',
                                                      'env_recep')

                    self.save_xml_knowledge(envio_dte,
                                            'merchandise_{}'.format(id))
                    self.sii_xml_merchandise = envio_dte
Exemplo n.º 23
0
 def do_validar_comercial(self):
     id_seq = self.env.ref('l10n_cl_dte.response_sequence').id
     IdRespuesta = self.env['ir.sequence'].browse(id_seq).next_by_id()
     NroDetalles = 1
     dicttoxml.set_debug(False)
     for inv in self.invoice_ids:
         if inv.claim in ['ACD', 'RCD']:
             continue
         try:
             signature_d = inv.get_digital_signature(inv.company_id)
         except:
             raise UserError(
                 _('''There is no Signer Person with an \
         authorized signature for you in the system. Please make sure that \
         'user_signature_key' module has been installed and enable a digital \
         signature, for you or make the signer to authorize you to use his \
         signature.'''))
         certp = signature_d['cert'].replace(BC, '').replace(EC,
                                                             '').replace(
                                                                 '\n', '')
         dte = self._resultado(
             TipoDTE=inv.sii_document_class_id.sii_code,
             Folio=inv.reference,
             FchEmis=inv.date_invoice,
             RUTEmisor=inv.format_vat(inv.partner_id.vat),
             RUTRecep=inv.format_vat(inv.company_id.vat),
             MntTotal=int(round(inv.amount_total, 0)),
             IdRespuesta=IdRespuesta,
         )
         ResultadoDTE = dicttoxml.dicttoxml(
             dte,
             root=False,
             attr_type=False,
         ).replace('<item>', '\n').replace('</item>', '\n')
         RutRecibe = inv.format_vat(inv.partner_id.vat)
         caratula_validacion_comercial = self._caratula_respuesta(
             inv.format_vat(inv.company_id.vat),
             RutRecibe,
             IdRespuesta,
             NroDetalles,
         )
         caratula = dicttoxml.dicttoxml(
             caratula_validacion_comercial,
             root=False,
             attr_type=False,
         ).replace('<item>', '\n').replace('</item>', '\n')
         resp = self._ResultadoDTE(
             caratula,
             ResultadoDTE,
         )
         respuesta = inv.sign_full_xml(
             resp,
             signature_d['priv_key'],
             certp,
             'Odoo_resp',
             'env_resp',
         )
         inv.sii_message = respuesta
         att = self._create_attachment(
             respuesta,
             'validacion_comercial_' + str(IdRespuesta),
         )
         inv.message_post(
             body='XML de Validación Comercial, Estado: %s, Glosa: %s' %
             (dte['ResultadoDTE']['EstadoDTE'],
              dte['ResultadoDTE']['EstadoDTEGlosa']),
             subject='XML de Validación Comercial',
             partner_ids=[inv.partner_id.id],
             attachment_ids=[att.id],
             message_type='comment',
             subtype='mt_comment',
         )
         inv.claim = 'ACD'
         inv.set_dte_claim(rut_emisor=inv.format_vat(inv.partner_id.vat), )
Exemplo n.º 24
0
import json
import dicttoxml
import config  # TODO: Read config values from app.config
import socket
from os import path

from flask import Response
from dicttoxml import dicttoxml as output_xml
from geoip2.database import Reader
from geoip2.errors import AddressNotFoundError
from user_agents import parse

# Turn off log output for dicttoxml
dicttoxml.set_debug(config.DEBUG)


# Fetch GeoIP data from GeoLite2 database
def fetch_geoip(ip_address, language=None):
    # Prepare response object
    response = {}

    # Get hostname from IP address, pass if fail
    try:
        response['ip_address'] = ip_address
        response['hostname'] = socket.gethostbyaddr(ip_address)[0]
    except Exception as ex:
        pass

    # Load GeoLite2 City database
    geoip = Reader(path.join(config.MMDB_PATH, "GeoLite2-City.mmdb"))
Exemplo n.º 25
0
 def do_validar_comercial(self):
     id_seq = self.env.ref('l10n_cl_fe.response_sequence').id
     IdRespuesta = self.env['ir.sequence'].browse(id_seq).next_by_id()
     NroDetalles = 1
     dicttoxml.set_debug(False)
     for inv in self.invoice_ids:
         if inv.claim in ['ACD', 'RCD']:
             continue
         dte = self._resultado(
             TipoDTE=inv.sii_document_class_id.sii_code,
             Folio=inv.reference,
             FchEmis=inv.date_invoice,
             RUTEmisor=inv.format_vat(inv.partner_id.vat),
             RUTRecep=inv.format_vat(inv.company_id.vat),
             MntTotal=int(round(inv.amount_total, 0)),
             IdRespuesta=IdRespuesta,
         )
         ResultadoDTE = dicttoxml.dicttoxml(
             dte,
             root=False,
             attr_type=False,
         ).decode().replace('<item>', '\n').replace('</item>', '\n')
         RutRecibe = inv.format_vat(inv.partner_id.vat)
         caratula_validacion_comercial = self._caratula_respuesta(
             inv.format_vat(inv.company_id.vat),
             RutRecibe,
             IdRespuesta,
             NroDetalles,
         )
         caratula = dicttoxml.dicttoxml(
             caratula_validacion_comercial,
             root=False,
             attr_type=False,
         ).decode().replace('<item>', '\n').replace('</item>', '\n')
         resp = self._ResultadoDTE(
             caratula,
             ResultadoDTE,
         )
         respuesta = '<?xml version="1.0" encoding="ISO-8859-1"?>\n' + inv.sign_full_xml(
             resp.replace('<?xml version="1.0" encoding="ISO-8859-1"?>\n',
                          ''),
             'Odoo_resp',
             'env_resp',
         )
         inv.sii_message = respuesta
         att = self._create_attachment(
             respuesta,
             'validacion_comercial_' + str(IdRespuesta),
         )
         inv.message_post(
             body='XML de Validación Comercial, Estado: %s, Glosa: %s' %
             (dte['ResultadoDTE']['EstadoDTE'],
              dte['ResultadoDTE']['EstadoDTEGlosa']),
             subject='XML de Validación Comercial',
             partner_ids=[inv.partner_id.id],
             attachment_ids=[att.id],
             message_type='comment',
             subtype='mt_comment',
         )
         inv.claim = 'ACD'
         try:
             inv.set_dte_claim(rut_emisor=inv.format_vat(
                 inv.partner_id.vat), )
         except:
             _logger.warning("@TODO crear código que encole la respuesta")
Exemplo n.º 26
0
    def commercial_acceptance(self):
        date = pysiidte.time_stamp()
        inv_obj = self.env['account.invoice']

        for message_id in self.message_ids:
            for attachment_id in message_id.attachment_ids:
                # if not (attachment_id.mimetype in [
                #     'text/plain'] and attachment_id.name.lower().find(
                # '.xml')):
                #     _logger.info(u'El adjunto no es un XML.
                # Revisando otro...')
                #     continue
                _logger.info('El adjunto es un XML')
                xml = self._get_xml_content(attachment_id.datas)
                soup = bs(xml, 'xml')  # se crea un arbol de xml
                envio_dte = soup.find_all('EnvioDTE')  # busqueda

                if envio_dte:
                    signature_d = inv_obj.get_digital_signature(
                        self.env.user.company_id)

                    certp = signature_d['cert'].replace(BC, '').replace(
                        EC, '').replace('\n', '')

                    tz = pytz.timezone('America/Santiago')
                    day = datetime.now(tz).strftime('%y%d%H%M')
                    idrespuesta = day

                    caratula = collections.OrderedDict()
                    caratula['RutResponde'] = '{}'.format(
                        soup.RutReceptor.string)
                    caratula['RutRecibe'] = '{}'.format(soup.RUTEmisor.string)
                    caratula['IdRespuesta'] = idrespuesta
                    caratula['NroDetalles'] = 1
                    caratula['NmbContacto'] = self.env.user.name
                    caratula['FonoContacto'] = self.env.user.partner_id.phone
                    caratula['MailContacto'] = self.env.user.partner_id.email
                    caratula['TmstFirmaResp'] = date

                    caratula_xml = dicttoxml.dicttoxml(caratula,
                                                       root=False,
                                                       attr_type=False)
                    apectacionComercial = collections.OrderedDict()
                    apectacionComercial['TipoDTE'] = '{}'.format(
                        soup.TipoDTE.string)
                    apectacionComercial['Folio'] = '{}'.format(
                        soup.Folio.string)
                    apectacionComercial['FchEmis'] = '{}'.format(
                        soup.FchEmis.string)
                    apectacionComercial['RUTEmisor'] = '{}'.format(
                        soup.RUTEmisor.string)
                    apectacionComercial['RUTRecep'] = '{}'.format(
                        soup.RUTRecep.string)
                    apectacionComercial['MntTotal'] = int(soup.MntTotal.string)
                    apectacionComercial['CodEnvio'] = idrespuesta
                    apectacionComercial['EstadoDTE'] = 0
                    apectacionComercial['EstadoDTEGlosa'] = ''

                    _logger.info(apectacionComercial)

                    aceptacion_xml = dicttoxml.dicttoxml(
                        apectacionComercial,
                        root=False,
                        attr_type=False,
                    )

                    dicttoxml.set_debug(False)
                    xml = '''<?xml version="1.0" encoding="ISO-8859-1"?>
                    <RespuestaDTE xmlns="http://www.sii.cl/SiiDte" \
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \
version="1.0" xsi:schemaLocation="http://www.sii.cl/SiiDte \
RespuestaEnvioDTE_v10.xsd">
                        <Resultado ID="Odoo_resp">
                            <Caratula version="1.0">
                                {0}
                            </Caratula>
                            <ResultadoDTE>
                                {1}
                            </ResultadoDTE>
                        </Resultado>
                    </RespuestaDTE>
                    '''.format(caratula_xml, aceptacion_xml)

                    aceptacion_comercial = inv_obj.sign_full_xml(
                        xml, signature_d['priv_key'],
                        inv_obj.split_cert(certp), 'Odoo_resp', 'env_resp')

                    self.save_xml_knowledge(
                        aceptacion_comercial,
                        'acceptance_{}'.format(idrespuesta))
                    self.sii_xml_accept = aceptacion_comercial
                    attachment = self.env['ir.attachment'].search([
                        ('res_model', '=', 'sii.dte.incoming'),
                        ('res_id', '=', self.id)
                    ])
                    file_name = attachment[0].name
                    result = inv_obj.send_xml_file(aceptacion_comercial,
                                                   file_name,
                                                   self.env.user.company_id)
                    _logger.info('Enviado: %s' % result)
Exemplo n.º 27
0
try:
    import urllib3
except:
    pass

pool = urllib3.PoolManager()
import textwrap

try:
    import xmltodict
except ImportError:
    _logger.info('Cannot import xmltodict library')

try:
    import dicttoxml
    dicttoxml.set_debug(False)
except ImportError:
    _logger.info('Cannot import dicttoxml library')

try:
    import base64
except ImportError:
    _logger.info('Cannot import base64 library')

try:
    import hashlib
except ImportError:
    _logger.info('Cannot import hashlib library')

try:
    import cchardet
Exemplo n.º 28
0
 def _validar(self):
     dicttoxml.set_debug(False)
     company_id = self.company_id
     signature_id = self.env.user.get_digital_signature(self.company_id)
     if not signature_id:
         raise UserError(
             _('''There are not a Signature Cert Available for this user, pleaseupload your signature or tell to someelse.'''
               ))
     resumenes = []
     resumenesPeriodo = {}
     recs = self._get_moves()
     for rec in recs:
         TpoDoc = rec.document_class_id.sii_code
         if TpoDoc not in resumenesPeriodo:
             resumenesPeriodo[TpoDoc] = {}
         if self.tipo_operacion == 'BOLETA':
             resumen = self._get_resumen_boleta(rec)
             resumenesPeriodo[TpoDoc] = self._setResumenPeriodoBoleta(
                 resumen, resumenesPeriodo[TpoDoc])
             del (resumen['MntNeto'])
             del (resumen['MntIVA'])
             if resumen.get('TasaIVA'):
                 del (resumen['TasaIVA'])
             resumenes.extend([{'Detalle': resumen}])
         else:
             resumen = self.getResumen(rec)
             resumenes.extend([{'Detalle': resumen}])
             resumenesPeriodo[TpoDoc] = self._setResumenPeriodo(
                 resumen, resumenesPeriodo[TpoDoc])
     if self.boletas:  #no es el libro de boletas especial
         for boletas in self.boletas:
             resumenesPeriodo[boletas.tipo_boleta.id] = {}
             resumen = self._setResumenBoletas(boletas)
             del (resumen['TotDoc'])
             resumenesPeriodo[
                 boletas.tipo_boleta.id] = self._setResumenPeriodo(
                     resumen, resumenesPeriodo[boletas.tipo_boleta.id])
             #resumenes.extend([{'Detalle':resumen}])
     lista = [
         'TpoDoc',
         'TpoImp',
         'TotDoc',
         'TotAnulado',
         'TotMntExe',
         'TotMntNeto',
         'TotalesServicio',
         'TotOpIVARec',
         'TotMntIVA',
         'TotMntIVA',
         'TotOpActivoFijo',
         'TotMntIVAActivoFijo',
         'itemNoRec',
         'TotOpIVAUsoComun',
         'TotIVAUsoComun',
         'FctProp',
         'TotCredIVAUsoComun',
         'itemOtrosImp',
         'TotImpSinCredito',
         'TotIVARetTotal',
         'TotIVARetParcial',
         'TotMntTotal',
         'TotIVANoRetenido',
         'TotTabPuros',
         'TotTabCigarrillos',
         'TotTabElaborado',
         'TotImpVehiculo',
     ]
     ResumenPeriodo = []
     for r, value in resumenesPeriodo.items():
         total = collections.OrderedDict()
         if value:
             for v in lista:
                 if v in value:
                     total[v] = value[v]
             ResumenPeriodo.extend([{'TotalesPeriodo': total}])
     dte = collections.OrderedDict()
     if ResumenPeriodo:
         dte['ResumenPeriodo'] = ResumenPeriodo
         dte['item'] = resumenes
     dte['TmstFirma'] = self.time_stamp()
     resol_data = self.get_resolution_data(company_id)
     RUTEmisor = self.format_vat(company_id.vat)
     xml = dicttoxml.dicttoxml(dte, root=False, attr_type=False).decode()
     doc_id = '%s_%s' % (self.tipo_operacion, self.periodo_tributario)
     libro = self.create_template_envio(
         RUTEmisor, self.periodo_tributario,
         resol_data['dte_resolution_date'],
         resol_data['dte_resolution_number'], xml,
         signature_id.subject_serial_number, self.tipo_operacion,
         self.tipo_libro, self.tipo_envio, self.folio_notificacion, doc_id)
     xml = self.create_template_env(libro)
     env = 'libro'
     if self.tipo_operacion in ['BOLETA']:
         xml = self.create_template_env_boleta(libro)
         env = 'libro_boleta'
     root = etree.XML(xml)
     xml_pret = etree.tostring(root, pretty_print=True).decode('iso-8859-1')\
             .replace('<item/>', '\n')\
             .replace('<item>', '\n').replace('</item>', '')\
             .replace('<itemNoRec>', '').replace('</itemNoRec>', '\n')\
             .replace('<itemOtrosImp>', '').replace('</itemOtrosImp>', '\n')\
             .replace('<item_refs>', '').replace('</item_refs>', '\n')\
             .replace('_no_rec', '')
     envio_dte = self.sign_full_xml(xml_pret, doc_id, env)
     self.sii_xml_request = self.env['sii.xml.envio'].create({
         'xml_envio':
         envio_dte,
         'name':
         doc_id,
         'company_id':
         company_id.id,
     }).id