def create_oseo_delivery_options(instance): """Create an OSEO DeliveryOptionsType""" ModelClass = models.OrderDeliveryOption if isinstance( instance, models.Order) else models.ItemSpecificationDeliveryOption try: instance_delivery = instance.selected_delivery_option except ModelClass.DoesNotExist: delivery_options = None else: delivery_options = oseo.DeliveryOptionsType( numberOfCopies=_n(instance_delivery.copies), productAnnotation=_n(instance_delivery.annotation), specialInstructions=_n(instance_delivery.special_instructions), ) if instance_delivery.delivery_type == ( models.BaseDeliveryOption.ONLINE_DATA_ACCESS): delivery_options.onlineDataAccess = BIND( protocol=instance_delivery.delivery_details) elif instance_delivery.delivery_type == ( models.BaseDeliveryOption.ONLINE_DATA_DELIVERY): delivery_options.onlineDataDelivery = BIND( protocol=instance_delivery.delivery_details) else: # media delivery medium, shipping = instance_delivery.delivery_details.partition( ",")[::2] delivery_options.mediaDelivery = BIND( packageMedium=medium, shippingInstructions=_n(shipping)) return delivery_options
def testShallowCTOR (self): w = shallow(BIND(5)) self.assertTrue(isinstance(w.optional.value(), xs.int)) self.assertEqual(w.optional.value(), 5) w = shallow(6) self.assertTrue(isinstance(w.optional.value(), xs.int)) self.assertEqual(w.optional.value(), 6) self.assertRaises(pyxb.UnrecognizedContentError, shallow, BIND('string'))
def testCode (self): myobj = B.b1(BIND('a2m-value', 'legal'), 'legal') self.assertEqual('a2m-value', myobj.a2elt.a2member) self.assertEqual(B.bst.legal, myobj.a2elt.a2b) myobj.a2elt = BIND('anotherValue', 'legal') self.assertEqual('anotherValue', myobj.a2elt.a2member) self.assertEqual(B.bst.legal, myobj.a2elt.a2b)
def testDeep(self): w = wrapper(BIND(BIND(4, deep=4), BIND('hi'))) self.assertEqual( '<wrapper><holding><optional deep="4">4</optional><required>hi</required></holding></wrapper>', w.toxml(root_only=True)) w = wrapper(BIND(BIND('hi', deep=2))) self.assertEqual( '<wrapper><holding><required deep="2">hi</required></holding></wrapper>', w.toxml(root_only=True))
def testDeep(self): w = wrapper(BIND(BIND(4, deep=4), BIND('hi'))) xmlt = u'<wrapper><holding><optional deep="4">4</optional><required>hi</required></holding></wrapper>' xmld = xmlt.encode('utf-8') self.assertEqual(w.toxml("utf-8", root_only=True), xmld) w = wrapper(BIND(BIND('hi', deep=2))) xmlt = u'<wrapper><holding><required deep="2">hi</required></holding></wrapper>' xmld = xmlt.encode('utf-8') self.assertEqual(w.toxml("utf-8", root_only=True), xmld)
def test_process_order_specification(self, settings): col_id = "fake collection id" col_name = "fake collection name" online_data_access_option = "http" option_name = "fakeoption" option_value = "fakevalue" settings.OSEOSERVER_PROCESSING_OPTIONS = [{"name": option_name}] settings.OSEOSERVER_PRODUCT_ORDER = { "enabled": True, "item_processor": "oseoserver.orderpreparation." "exampleorderprocessor.ExampleOrderProcessor" } settings.OSEOSERVER_ONLINE_DATA_ACCESS_OPTIONS = [ online_data_access_option ] settings.OSEOSERVER_COLLECTIONS = [{ "name": col_name, "collection_identifier": col_id, "product_order": { "enabled": True, "options": [option_name], "online_data_access_options": [online_data_access_option] } }] order_spec = oseo.OrderSpecification( orderReference="dummy reference", orderRemark="dummy remark", packaging="zip", option=[ BIND( oseo.ParameterData(encoding="XMLEncoding", values=xsd.anyType())), ], deliveryOptions=oseo.deliveryOptions(onlineDataAccess=BIND( protocol="http")), priority="STANDARD", orderType="PRODUCT_ORDER", orderItem=[ oseo.CommonOrderItemType( itemId="dummy item id1", productOrderOptionsId="dummy productorderoptionsid1", orderItemRemark="dumm item remark1", productId=oseo.ProductIdType( identifier="dummy catalog identifier1", collectionId=col_id)), ], ) order_spec = _add_order_specification_options( order_spec, "oseo:option[1]/oseo:ParameterData/oseo:values", **{option_name: option_value}) op = submit.Submit() result = op.process_order_specification(order_spec) print("result: {}".format(result))
def testShallowSet(self): w = shallow() self.assertRaises(pyxb.BadTypeValueError, SET_optional, w, 5) w.optional = BIND(5) self.assertTrue(w.optional.deep is None) self.assertTrue(isinstance(w.optional.value(), xs.int)) self.assertRaises(pyxb.BadTypeValueError, SET_optional, w, BIND('string')) w.optional = BIND(6, deep=1) self.assertEqual(w.optional.value(), 6) self.assertEqual(w.optional.deep, 1)
def build_operations_metadata(): op_meta = ows.OperationsMetadata() for op_name in requestprocessor.OPERATION_CALLABLES.keys(): op = ows.Operation(name=op_name) op.DCP.append(BIND()) op.DCP[0].HTTP = BIND() op.DCP[0].HTTP.Post.append(BIND()) op.DCP[0].HTTP.Post[0].href = "http://{}{}".format( django_settings.SITE_DOMAIN, reverse("oseo_endpoint")) op_meta.Operation.append(op) return op_meta
def main(): create_loggers() log.info('Dummy XML Encoder') tt = bindings.tt(sequenceIdentifier='testSequence001', sequenceNumber='1', timeBase='smpte', lang='en-GB', head=bindings.head_type( metadata.headMetadata_type( metadata.documentMetadata()), bindings.styling(bindings.style(id='ID001')), bindings.layout()), body=BIND( bindings.div_type( bindings.p_type( bindings.span_type('Some example text...'), bindings.br_type(), bindings.span_type('And another line'), id='ID005', begin='00:00:00:50', end='00:00:03:24', )))) print( tt.toDOM(bds=BindingDOMSupport( default_namespace=bindings.Namespace)).toprettyxml(indent=' ')) log.info('XML output printed')
def __init__(self, time_base, sequence_number, sequence_identifier, lang, clock_mode=None): if not clock_mode and time_base is TimeBase.CLOCK: clock_mode = 'local' self._ebutt3_content = bindings.tt( timeBase=time_base, clockMode=clock_mode, sequenceIdentifier=sequence_identifier, sequenceNumber=sequence_number, lang=lang, head=BIND( metadata.headMetadata_type( metadata.documentMetadata() ) ), body=BIND() ) self.validate()
def __init__(self, time_base, sequence_number, sequence_identifier, lang, clock_mode=None, availability_time=None, authors_group_identifier=None): if not clock_mode and time_base is TimeBase.CLOCK: clock_mode = 'local' self._ebutt3_content = bindings.tt( timeBase=time_base, clockMode=clock_mode, sequenceIdentifier=sequence_identifier, authorsGroupIdentifier=authors_group_identifier, sequenceNumber=sequence_number, lang=lang, head=BIND(metadata.headMetadata_type(metadata.documentMetadata())), body=BIND()) if availability_time is not None: self._availability_time = availability_time self.validate()
def consulta_nfse_por_data(prestador, data_inicial, data_final): consulta = nfse_schema.ConsultarNfseEnvio() consulta.Prestador = _serial_prestador(prestador) consulta.PeriodoEmissao = BIND() consulta.PeriodoEmissao.DataInicial = data_inicial consulta.PeriodoEmissao.DataFinal = data_final xml = consulta.toxml() xml = _limpeza_xml(xml) return xml
def get_collection_id(self, item_id): """Determine the collection identifier for the specified item. This method is used when the requested order item does not provide the optional 'collectionId' element. It searched all of the defined catalogue endpoints and determines the collection for the specified item. The example shown here assumes that the input `item_id` is the identifier for a record in a CSW catalogue. Parameters ---------- item_id: str Identifier of an order item that belongs to the collection to find Returns ------- str Identifier of the collection """ request_headers = {"Content-Type": "application/xml"} ns = { "gmd": gmd.Namespace.uri(), "gco": gco.Namespace.uri(), } req = csw.GetRecordById(service="CSW", version="2.0.2", ElementSetName="summary", outputSchema=ns["gmd"], Id=[BIND(item_id)]) query_path = ("gmd:MD_Metadata/gmd:parentIdentifier/" "gco:CharacterString/text()") for collection in settings.get_collections(): response = requests.post(collection["catalogue_endpoint"], data=req.toxml(), headers=request_headers) if response.status_code == 200: r = etree.fromstring(response.text.encode(constants.ENCODING)) id_container = r.xpath(query_path, namespaces=ns) if any(id_container): collection_id = id_container[0] break else: raise errors.OseoServerError("Could not retrieve collection " "id for item {!r}".format(item_id)) return collection_id
def create_oseo_delivery_address(delivery_address): return oseo.DeliveryAddressType( firstName=_n(delivery_address.first_name), lastName=_n(delivery_address.last_name), companyRef=_n(delivery_address.company_ref), postalAddress=BIND( streetAddress=_n(delivery_address.street_address), city=_n(delivery_address.city), state=_n(delivery_address.state), postalCode=_n(delivery_address.postal_code), country=_n(delivery_address.country), postBox=_n(delivery_address.post_box), ), telephoneNumber=_n(delivery_address.telephone), facsimileTelephoneNumber=_n(delivery_address.fax), )
def consultar_nfse(self, emitente, numero=None, inicio=None, fim=None): # Prestador id_prestador = _tipos.tcIdentificacaoPrestador() id_prestador.Cnpj = emitente.cnpj id_prestador.InscricaoMunicipal = emitente.inscricao_municipal consulta = servico_consultar_nfse_envio_v03.ConsultarNfseEnvio() consulta.Prestador = id_prestador # Consulta por Numero if numero is not None: consulta.NumeroNfse = numero else: # consulta por Data consulta.PeriodoEmissao = BIND() consulta.PeriodoEmissao.DataInicial = inicio consulta.PeriodoEmissao.DataFinal = fim return consulta.toxml(element_name='ns1:ConsultarNfseEnvio')
def envio_lote_rps(lote_rps): serial_lote_rps = nfse_schema.tcLoteRps() serial_lote_rps.NumeroLote = lote_rps.numero_lote serial_lote_rps.id = lote_rps.identificador serial_lote_rps.Cnpj = lote_rps.cnpj serial_lote_rps.InscricaoMunicipal = lote_rps.inscricao_municipal serial_lote_rps.QuantidadeRps = len(lote_rps.lista_rps) serial_lote_rps.ListaRps = BIND() for rps in lote_rps.lista_rps: serial_lote_rps.ListaRps.append(_serial_rps(rps)) serial_enviar_lote = nfse_schema.EnviarLoteRpsEnvio() serial_enviar_lote.LoteRps = serial_lote_rps xml = serial_enviar_lote.toxml() xml = _limpeza_xml(xml) return xml
def test_get_delivery_address_postal_address(street, city, state, code, country, po): delivery_address_type = oseo.DeliveryAddressType( postalAddress=BIND( streetAddress=street, city=city, state=state, postalCode=code, country=country, postBox=po ) ) result = submit._get_delivery_address(delivery_address_type) assert result["postal_address"]["street_address"] == _c(street) assert result["postal_address"]["city"] == _c(city) assert result["postal_address"]["state"] == _c(state) assert result["postal_address"]["postal_code"] == _c(code) assert result["postal_address"]["country"] == _c(country) assert result["postal_address"]["post_box"] == _c(po)
def create_oseo_delivery_information(delivery_information): """Create an OSEO DeliveryInformationType""" information = oseo.DeliveryInformationType() optional_attrs = [ delivery_information.first_name, delivery_information.last_name, delivery_information.company_ref, delivery_information.street_address, delivery_information.city, delivery_information.state, delivery_information.postal_code, delivery_information.country, delivery_information.post_box, delivery_information.telephone, delivery_information.fax ] if any(optional_attrs): information.mailAddress = oseo.DeliveryAddressType() information.mailAddress.firstName = _n(delivery_information.first_name) information.mailAddress.lastName = _n(delivery_information.last_name) information.mailAddress.companyRef = _n( delivery_information.company_ref) information.mailAddress.postalAddress = BIND() information.mailAddress.postalAddress.streetAddress = _n( delivery_information.street_address) information.mailAddress.postalAddress.city = _n( delivery_information.city) information.mailAddress.postalAddress.state = _n( delivery_information.state) information.mailAddress.postalAddress.postalCode = _n( delivery_information.postal_code) information.mailAddress.postalAddress.country = _n( delivery_information.country) information.mailAddress.postalAddress.postBox = _n( delivery_information.post_box) information.mailAddress.telephoneNumber = _n( delivery_information.telephone) information.mailAddress.facsimileTelephoneNumber = _n( delivery_information.fax) for oa in delivery_information.onlineaddress_set.all(): information.onlineAddress.append(oseo.OnlineAddressType()) information.onlineAddress[-1].protocol = oa.protocol information.onlineAddress[-1].serverAddress = oa.server_address information.onlineAddress[-1].userName = _n(oa.user_name) information.onlineAddress[-1].userPassword = _n(oa.user_password) information.onlineAddress[-1].path = _n(oa.path) return information
def consultar_faixa(self, emitente, inicio, fim, pagina): """Retorna string de um XML gerado a partir do XML Schema (XSD). Binding gerado pelo modulo PyXB.""" # Prestador id_prestador = nfse_schema.tcIdentificacaoPrestador() id_prestador.CpfCnpj = emitente.cnpj id_prestador.InscricaoMunicipal = emitente.inscricao_municipal consulta = nfse_schema.ConsultarNfseFaixaEnvio() consulta.Prestador = id_prestador consulta.Pagina = pagina # É necessário BIND antes de atribuir numero final e numero inicial consulta.Faixa = BIND() consulta.Faixa.NumeroNfseInicial = inicio consulta.Faixa.NumeroNfseFinal = fim consulta = consulta.toxml( element_name='ConsultarNfseFaixaEnvio').replace( 'ns1:', '').replace(':ns1', '').replace('<?xml version="1.0" ?>', '') return consulta
import GeoCoder from pyxb import BIND import sys import pyxb.utils.domutils as domutils import pyxb.bundles.wssplat.soap11 as soapenv import pyxb.bundles.wssplat.soapenc as soapenc import urllib2 address = '1600 Pennsylvania Ave., Washington, DC' if 1 < len(sys.argv): address = sys.argv[1] env = soapenv.Envelope(Body=BIND(GeoCoder.geocode(address))) uri = urllib2.Request( 'http://rpc.geocoder.us/service/soap/', env.toxml(), { 'SOAPAction': "http://rpc.geocoder.us/Geo/Coder/US#geocode", 'Content-Type': 'text/xml' }) rxml = urllib2.urlopen(uri).read() #file('response.xml', 'w').write(rxml) #rxml = file('response.xml').read() response = soapenv.CreateFromDocument(rxml) # OK, here we get into ugliness due to WSDL's concept of schema in the # SOAP encoding not being consistent with XML Schema, even though it # uses the same namespace. See # http://tech.groups.yahoo.com/group/soapbuilders/message/5879. In # short, the WSDL spec shows an example using soapenc:Array where a # restriction was used to set the value of the wsdl:arrayType
def serializar_lote_assincrono(self, nfse): "Serializa lote de envio, baseado no servico_enviar_lote_rps_envio_v03.xsd" servico = _tipos.tcDadosServico() valores_servico = _tipos.tcValores() valores_servico.ValorServicos = nfse.servico.valor_servico #valores_servico.ValorServicos = str(Decimal(nfse.servico.valor_servico.quantize(Decimal('.01'), rounding=ROUND_HALF_UP))) valores_servico.IssRetido = nfse.servico.iss_retido # Dados opcionais if nfse.servico.valor_deducoes: valores_servico.ValorDeducoes = nfse.servico.valor_deducoes if nfse.servico.valor_pis: valores_servico.ValorPis = nfse.servico.valor_pis if nfse.servico.valor_confins: valores_servico.ValorCofins = nfse.servico.valor_confins if nfse.servico.valor_inss: valores_servico.ValorInss = nfse.servico.valor_inss if nfse.servico.valor_ir: valores_servico.ValorIr = nfse.servico.valor_ir if nfse.servico.valor_csll: valores_servico.ValorCsll = nfse.servico.valor_csll if nfse.servico.valor_iss: valores_servico.ValorIss = nfse.servico.valor_iss if nfse.servico.valor_iss_retido: valores_servico.ValorIssRetido = nfse.servico.valor_iss_retido if nfse.servico.valor_liquido: valores_servico.ValorLiquidoNfse = nfse.servico.valor_liquido if nfse.servico.outras_retencoes: valores_servico.OutrasRetencoes = nfse.servico.outras_retencoes if nfse.servico.base_calculo: valores_servico.BaseCalculo = nfse.servico.base_calculo if nfse.servico.aliquota: valores_servico.Aliquota = nfse.servico.aliquota if nfse.servico.desconto_incondicionado: valores_servico.DescontoIncondicionado = nfse.servico.desconto_incondicionado if nfse.servico.desconto_condicionado: valores_servico.DescontoCondicionado = nfse.servico.desconto_condicionado servico.Valores = valores_servico servico.ItemListaServico = nfse.servico.item_lista # opcionais if nfse.servico.codigo_cnae: servico.CodigoCnae = nfse.servico.codigo_cnae if nfse.servico.codigo_tributacao_municipio: servico.CodigoTributacaoMunicipio = nfse.servico.codigo_tributacao_municipio # obrigatórios servico.Discriminacao = nfse.servico.discriminacao servico.CodigoMunicipio = nfse.servico.codigo_municipio # endereco tomador endereco_tomador = _tipos.tcEndereco() endereco_tomador.Endereco = nfse.cliente.endereco_logradouro if nfse.cliente.endereco_complemento: endereco_tomador.Complemento = nfse.cliente.endereco_complemento endereco_tomador.Numero = nfse.cliente.endereco_numero endereco_tomador.Bairro = nfse.cliente.endereco_bairro if nfse.cliente.endereco_cod_municipio: endereco_tomador.CodigoMunicipio = nfse.cliente.endereco_cod_municipio endereco_tomador.Uf = nfse.cliente.endereco_uf endereco_tomador.Cep = nfse.cliente.endereco_cep # identificacao Tomador id_tomador = _tipos.tcIdentificacaoTomador() id_tomador.CpfCnpj = nfse.cliente.numero_documento if nfse.cliente.inscricao_municipal: id_tomador.InscricaoMunicipal = nfse.cliente.inscricao_municipal # Tomador tomador = _tipos.tcDadosTomador() tomador.IdentificacaoTomador = id_tomador tomador.RazaoSocial = nfse.cliente.razao_social tomador.Endereco = endereco_tomador # opcional if nfse.cliente.endereco_telefone or nfse.cliente.email: tomador.Contato = _tipos.tcContato() if nfse.cliente.endereco_telefone: tomador.Contato.Telefone = nfse.cliente.endereco_telefone if nfse.cliente.email: tomador.Contato.Email = nfse.cliente.email # Prestador id_prestador = _tipos.tcIdentificacaoPrestador() id_prestador.Cnpj = nfse.emitente.cnpj id_prestador.InscricaoMunicipal = nfse.emitente.inscricao_municipal # identificacao rps id_rps = _tipos.tcIdentificacaoRps() id_rps.Numero = nfse.identificador id_rps.Serie = nfse.serie id_rps.Tipo = nfse.tipo # inf rps inf_rps = _tipos.tcInfRps() inf_rps.IdentificacaoRps = id_rps inf_rps.DataEmissao = nfse.data_emissao.strftime('%Y-%m-%dT%H:%M:%S') # Natureza da Operação # 1 – Tributação no município # 2 - Tributação fora do município # 3 - Isenção # 4 - Imune # 5 –Exigibilidade suspensa por decisão judicial # 6 – Exigibilidade suspensa por procedimento administrativo inf_rps.NaturezaOperacao = nfse.natureza_operacao # Regime Especial de Tributação # 1 – Microempresa municipal # 2 - Estimativa # 3 – Sociedade de profissionais # 4 – Cooperativa # 5 - Microempresário Individual (MEI) # 6 - Microempresário e Empresa de Pequeno Porte (ME EPP) if nfse.regime_especial: inf_rps.RegimeEspecialTributacao = nfse.regime_especial inf_rps.OptanteSimplesNacional = nfse.simples # 1-sim 2-nao inf_rps.IncentivadorCultural = nfse.incentivo # 1-sim 2-nao # Código de status da NFS-e inf_rps.Status = 1 # 1 – Normal 2 – Cancelado (sempre 1, pois a nota não pode ser enviada como cancelada) inf_rps.RpsSubstituido = None # opcional inf_rps.Servico = servico inf_rps.Prestador = id_prestador inf_rps.Tomador = tomador inf_rps.IntermediarioServico = None # opcional inf_rps.ConstrucaoCivil = None # opcional inf_rps.Id = nfse.identificador rps = _tipos.tcRps() rps.InfRps = inf_rps lote = _tipos.tcLoteRps() lote.NumeroLote = 1 lote.Id = 1 lote.Cnpj = nfse.emitente.cnpj lote.InscricaoMunicipal = nfse.emitente.inscricao_municipal lote.QuantidadeRps = 1 lote.ListaRps = BIND() lote.ListaRps.append(rps) enviarLote = servico_enviar_lote_rps_envio_v03.EnviarLoteRpsEnvio() enviarLote.LoteRps = lote return enviarLote.toxml(element_name='ns1:EnviarLoteRpsEnvio')
def build_contents(): product_order_type = settings.get_product_order() subscription_order_type = settings.get_subscription_order() tasking_order_type = settings.get_tasking_order() logger.debug("before creating OrderingServiceContentsType...") contents = oseo.OrderingServiceContentsType( ProductOrders=BIND(supported=product_order_type["enabled"]), SubscriptionOrders=BIND(supported=subscription_order_type["enabled"]), ProgrammingOrders=BIND(supported=tasking_order_type["enabled"]), GetQuotationCapabilities=BIND(supported=False, synchronous=False, asynchronous=False, monitoring=False, off_line=False), SubmitCapabilities=BIND( asynchronous=False, maxNumberOfProducts=settings.get_max_order_items(), globalDeliveryOptions=True, localDeliveryOptions=True, globalOrderOptions=True, localOrderOptions=True), GetStatusCapabilities=BIND(orderSearch=True, orderRetrieve=True, full=True), DescribeResultAccessCapabilities=BIND(supported=True), CancelCapabilities=BIND(supported=True, asynchronous=False), ) logger.debug("before adding CollectionCapability...") for collection in settings.get_collections(): c = oseo.CollectionCapability( collectionId=collection["collection_identifier"], ProductOrders=BIND(supported=collection.get( "product_order", {"enabled": False})["enabled"]), SubscriptionOrders=BIND(supported=collection.get( "subscription_order", {"enabled": False})["enabled"]), DescribeResultAccessCapabilities=BIND(supported=True), CancelCapabilities=BIND(supported=True, asynchronous=False), ) contents.SupportedCollection.append(c) contents.ContentsType.append( oseo.EncodingType(supportedEncoding=["XMLEncoding", "TextEncoding"])) return contents
def testShallowCTOR(self): w = shallow(BIND(5)) self.assertTrue(isinstance(w.optional.value(), xs.int)) self.assertRaises(pyxb.UnexpectedNonElementContentError, shallow, 5) self.assertRaises(pyxb.UnexpectedNonElementContentError, shallow, BIND('string'))
def setUp(self): self.prestador = { 'cnpj': '12345678000123', 'inscricao_municipal': '0987654321' } self.tomador = { 'razao_social': 'Nome Cliente', 'numero_documento': '12345678000123', 'endereco': 'Rua Cliente', 'endereco_numero': '1234', 'bairro': 'Bairro Cliente', 'codigo_municipio': '4106902', 'uf': 'PR', 'cep': '80000000', 'telefone': '4132221122', 'email': '*****@*****.**' } self.servico = { 'valor_servico': Decimal('1000.00'), 'iss_retido': 2, # 1 - Sim, 2 - Não 'item_lista': '1401', 'discriminacao': 'Descrição do Serviço Prestado', 'codigo_municipio': '4106902', 'codigo_cnae': 9511800, 'codigo_tributacao_municipio': '1401', 'aliquota': Decimal('0.02') } self.rps = { 'identificador': 'N1', 'data_emissao': datetime(2016, 12, 12, 17, 22, 39, 960610), 'servico': self.servico, 'prestador': self.prestador, 'tomador': self.tomador, 'simples': 1, 'incentivo': 2, 'numero': 1, 'serie': 'A1', 'tipo': '1', 'natureza_operacao': 1, 'regime_especial': 6 } self.lote_rps = { 'identificador': 'L1', 'numero_lote': 1, 'cnpj': self.rps['prestador']['cnpj'], 'inscricao_municipal': self.rps['prestador']['inscricao_municipal'], 'quantidade_rps': 1, 'lista_rps': [ self.rps, ] } self.pedido_cancelamento_nfse = { 'identificador': 'C1', 'prestador': self.prestador, 'numero_nota': 192, 'codigo_municipio': '4106902', 'codigo_cancelamento': '1' } # Necessário para "serializar" os objetos antes do lote completo. self.tc_inf_rps = nfse_schema.tcInfRps() self.tc_lote_rps = nfse_schema.tcLoteRps() self.tc_lote_rps.ListaRps = BIND()
def setUp(self): self.prestador = Prestador(**{ "cnpj": "12345678000123", "inscricao_municipal": "0987654321" }) self.tomador = Tomador( **{ "razao_social": "Nome Cliente", "tipo_documento": "CNPJ", "numero_documento": "12345678000123", "endereco": "Rua Cliente", "endereco_numero": "1234", "bairro": "Bairro Cliente", "codigo_municipio": "4106902", "uf": "PR", "cep": "80000000", "telefone": "4132221122", "email": "*****@*****.**", }) self.servico = Servico( **{ "valor_servico": Decimal("1000.00"), "iss_retido": 2, # 1 - Sim, 2 - Não "item_lista": "1401", "discriminacao": "Descrição do Serviço Prestado", "codigo_municipio": "4106902", "codigo_cnae": 9511800, "codigo_tributacao_municipio": "1401", "aliquota": Decimal("0.02"), }) self.rps = RPS( **{ "identificador": "N1", "data_emissao": datetime(2016, 12, 12, 17, 22, 39, 960610), "servico": self.servico, "prestador": self.prestador, "tomador": self.tomador, "simples": 1, "incentivo": 2, "numero": 1, "serie": "A1", "tipo": "1", "natureza_operacao": 1, }) self.lote_rps = LoteRPS( **{ "identificador": "L1", "numero_lote": 1, "cnpj": self.prestador.cnpj, "inscricao_municipal": self.prestador.inscricao_municipal, "quantidade_rps": 1, "lista_rps": [self.rps], }) self.pedido_cancelamento_nfse = PedidoCancelamentoNFSe( **{ "identificador": "C1", "prestador": self.prestador, "numero_nota": 192, "codigo_municipio": "4106902", "codigo_cancelamento": "1", }) # Necessário para "serializar" os objetos antes do lote completo. self.tc_inf_rps = nfse_schema.tcInfRps() self.tc_lote_rps = nfse_schema.tcLoteRps() self.tc_lote_rps.ListaRps = BIND()
def serializar_lote_sincrono(self, nfse): """Retorna string de um XML gerado a partir do XML Schema (XSD). Binding gerado pelo modulo PyXB.""" servico = nfse_schema.tcDadosServico() valores_servico = nfse_schema.tcValoresDeclaracaoServico() valores_servico.ValorServicos = nfse.servico.valor_servico servico.IssRetido = nfse.servico.iss_retido servico.ItemListaServico = nfse.servico.item_lista servico.Discriminacao = nfse.servico.discriminacao servico.CodigoMunicipio = nfse.servico.codigo_municipio servico.ExigibilidadeISS = nfse.servico.exigibilidade servico.MunicipioIncidencia = nfse.servico.municipio_incidencia servico.Valores = valores_servico # Prestador id_prestador = nfse_schema.tcIdentificacaoPrestador() id_prestador.CpfCnpj = nfse.emitente.cnpj id_prestador.InscricaoMunicipal = nfse.emitente.inscricao_municipal # Cliente id_tomador = nfse_schema.tcIdentificacaoTomador() id_tomador.CpfCnpj = nfse.cliente.numero_documento if nfse.cliente.inscricao_municipal: id_tomador.InscricaoMunicipal = nfse.cliente.inscricao_municipal endereco_tomador = nfse_schema.tcEndereco() endereco_tomador.Endereco = nfse.cliente.endereco_logradouro endereco_tomador.Numero = nfse.cliente.endereco_numero endereco_tomador.Bairro = nfse.cliente.endereco_bairro endereco_tomador.CodigoMunicipio = nfse.cliente.endereco_cod_municipio endereco_tomador.Uf = nfse.cliente.endereco_uf endereco_tomador.CodigoPais = nfse.cliente.endereco_pais endereco_tomador.Cep = nfse.cliente.endereco_cep tomador = nfse_schema.tcDadosTomador() tomador.IdentificacaoPrestador = id_tomador tomador.RazaoSocial = nfse.cliente.razao_social tomador.Endereco = endereco_tomador id_rps = nfse_schema.tcIdentificacaoRps() id_rps.Numero = nfse.identificador id_rps.Serie = nfse.serie id_rps.Tipo = nfse.tipo rps = nfse_schema.tcInfRps() rps.IdentificacaoRps = id_rps rps.DataEmissao = nfse.data_emissao.strftime('%Y-%m-%d') rps.Status = 1 inf_declaracao_servico = nfse_schema.tcInfDeclaracaoPrestacaoServico() inf_declaracao_servico.Competencia = nfse.data_emissao.strftime( '%Y-%m-%d') inf_declaracao_servico.Servico = servico inf_declaracao_servico.Prestador = id_prestador inf_declaracao_servico.Tomador = tomador inf_declaracao_servico.OptanteSimplesNacional = nfse.simples inf_declaracao_servico.IncentivoFiscal = nfse.incentivo inf_declaracao_servico.Id = nfse.identificador inf_declaracao_servico.Rps = rps declaracao_servico = nfse_schema.tcDeclaracaoPrestacaoServico() declaracao_servico.InfDeclaracaoPrestacaoServico = inf_declaracao_servico lote = nfse_schema.tcLoteRps() lote.NumeroLote = 1 lote.Id = 1 lote.CpfCnpj = nfse.emitente.cnpj lote.InscricaoMunicipal = nfse.emitente.inscricao_municipal lote.QuantidadeRps = 1 if nfse.autorizador.upper() == 'BETHA': lote.versao = '2.02' lote.ListaRps = BIND(declaracao_servico) gnfse = nfse_schema.EnviarLoteRpsSincronoEnvio() gnfse.LoteRps = lote return gnfse.toxml(element_name='EnviarLoteRpsSincronoEnvio')
def test_validate_order_item(self, settings, collection, options, delivery_protocol): settings.DEBUG = True settings.OSEOSERVER_ONLINE_DATA_ACCESS_OPTIONS = [] if delivery_protocol is not None: settings.OSEOSERVER_ONLINE_DATA_ACCESS_OPTIONS.append( {"protocol": delivery_protocol}) settings.OSEOSERVER_PROCESSING_OPTIONS = [{ "name": opt["name"] } for opt in options] settings.OSEOSERVER_PRODUCT_ORDER = { "item_processor": "oseoserver.orderpreparation." "exampleorderprocessor.ExampleOrderProcessor" } settings.OSEOSERVER_COLLECTIONS = [{ "name": collection["name"], "collection_identifier": collection["id"], "product_order": { "enabled": True, "options": [opt["name"] for opt in options], "online_data_access_options": [delivery_protocol], } }] requested_item = oseo.CommonOrderItemType( itemId="dummy item id1", productOrderOptionsId="dummy productorderoptionsid1", orderItemRemark="dummy item remark1", productId=oseo.ProductIdType( identifier="dummy catalog identifier1", collectionId=collection["id"]), option=[ BIND( oseo.ParameterData(encoding="XMLEncoding", values=xsd.anyType())) ], ) if delivery_protocol is not None: requested_item.deliveryOptions = oseo.DeliveryOptionsType( onlineDataAccess=BIND(protocol=delivery_protocol)) for index in range(len(options)): xpath_expression = ("oseo:option[{0}]/oseo:ParameterData/" "oseo:values".format(index + 1)) requested_item = _add_item_options(requested_item, xpath_expression, options[index]) order_type = Order.PRODUCT_ORDER operation = submit.Submit() item_spec = operation.validate_order_item(requested_item, order_type) print("item_spec: {}".format(item_spec)) assert item_spec["item_id"] == requested_item.itemId assert item_spec["collection"] == collection["name"] assert item_spec["identifier"] == requested_item.productId.identifier assert len(item_spec["option"]) == len(options) for item in options: assert item["value"] == item_spec["option"][item["name"]] if delivery_protocol is None: assert item_spec["delivery_options"] is None else: assert item_spec["delivery_options"]["protocol"].value == ( delivery_protocol)
from __future__ import print_function from pyxb import BIND import content v = content.numbers(1, BIND(2), attribute=3) v.complex.style = "decimal" print(v.toxml("utf-8").decode('utf-8')) print(3 * v.simple) print(4 * v.complex.value()) print(5 * v.attribute)
pytest.raises(errors.InvalidParameterValueError): mock_get_order_config.return_value = ( fake_collection_config) submit.check_delivery_protocol( protocol=protocol, delivery_type=delivery_type, order_type=order_type, collection="fake" ) @pytest.mark.parametrize("oseo_delivery, expected", [ ( oseo.DeliveryOptionsType( mediaDelivery=BIND( packageMedium="DVD", shippingInstructions="other" ) ), models.OrderDeliveryOption( delivery_type=OrderDeliveryOption.MEDIA_DELIVERY, delivery_details="DVD, other", copies=1 ) ), ( oseo.DeliveryOptionsType( onlineDataAccess=BIND(protocol="ftp") ), models.OrderDeliveryOption( delivery_type=OrderDeliveryOption.ONLINE_DATA_ACCESS, delivery_details="ftp",