def PackNsend(self, dict_parse): self.dict_parse['MessageHeader'] = Raw(self.dataMH) self.dict_parse['UtilitiesDevice'] = Raw(self.dataUtil) sendingData = self.client.service.UtilitiesDeviceERPSmartMeterCreateRequest_In( self.dict_parse['MessageHeader'], self.dict_parse['UtilitiesDevice']) print("Parsed and sent the data to webservice...")
def _get_manifest(self, date_from): """Get shipping manifest for a given range date :param str date_from -- date in format "%d/%m&Y" :returns: list of dicts with format { 'codplaza_pag': 771, 'codcli': 601, 'cliente': Pruebas WS 'codplaza_org': 771, 'codexp': 468644476, 'codservicio': 74, 'servicio': EUROBUSINESS PARCEL, 'codhorario': 3, 'horario': BusinessParcel, 'codestado': -10, 'estado': GRABADO, 'bultos': 1, 'kgs': 7,0, 'nombre_dst': TEST USER, 'calle_dst': direccion, 'localidad_dst': Fontenay-Trésigny, 'cp_dst': 77610, 'departamento_dst': , 'pais_dst': FR, } """ xml = Raw( self._prepare__get_manifest_docin( uidcustomer=self.uidcustomer, date_from=date_from ) ) _logger.debug(xml) try: res = self.client.service.GetManifiesto(docIn=xml) _logger.debug(res) except Exception as e: raise UserError( _( "No response from server getting manifisto for GLS.\n" "Traceback:\n{}" ).format(e) ) res = self._recursive_asdict(res.Servicios.Envios).get("Envio", []) return res
def chang_org_assign(self,worker,position,costcenter): #date = time.strftime("%Y-%m-%d") xmlstring = ''' <ns0:Position_Reference> <ns0:ID ns0:type="Position_ID">{position}</ns0:ID> </ns0:Position_Reference> <ns0:Worker_Reference> <ns0:ID ns0:type="wid">{worker}</ns0:ID> </ns0:Worker_Reference> <ns0:Position_Organization_Assignments_Data> <ns0:Cost_Center_Assignments_Reference> <ns0:ID ns0:type="Cost_Center_Reference_ID">{costcenter}</ns0:ID> </ns0:Cost_Center_Assignments_Reference> </ns0:Position_Organization_Assignments_Data> '''.format(position=position,worker=worker, costcenter=costcenter) ww_service = 'Change_Organization_Assignment' xml = Raw(xmlstring) try: result = self.client1.service.Change_Organization_Assignments(None,xml) except WebFault as e: print self.client1.last_sent() print(e) sys.exit() #result = self._launch_head(ww_service, xmlstring) dict = recursive_asdict(result) return dict
def gen_xml_borrado_3en1_fr(self, cr, uid, fondo_rotatorio, nro_carga, tipo_doc_grp, nro_modif_grp, nro_obl_sist_aux=False): _tipo_registracion= '24' _tipo_registro = '01' root = etree.Element('MovimientosSIIF') etree.SubElement(root, 'nro_carga').text = nro_carga e_movimientos = etree.SubElement(root, 'movimientos') e_movimiento_presup = etree.SubElement(e_movimientos, 'MovimientoPresupuestalSIIF') etree.SubElement(e_movimiento_presup, 'tipo_registro').text = _tipo_registro etree.SubElement(e_movimiento_presup, 'tipo_registracion').text = _tipo_registracion etree.SubElement(e_movimiento_presup, 'ano_fiscal').text = fondo_rotatorio.fiscal_year_id.name etree.SubElement(e_movimiento_presup, 'inciso').text = fondo_rotatorio.inciso_siif_llp_id.inciso etree.SubElement(e_movimiento_presup, 'unidad_ejecutora').text = fondo_rotatorio.ue_siif_llp_id.ue etree.SubElement(e_movimiento_presup, 'tipo_doc_sist_aux').text = tipo_doc_grp etree.SubElement(e_movimiento_presup, 'nro_afect_sist_aux').text = nro_obl_sist_aux etree.SubElement(e_movimiento_presup, 'nro_comp_sist_aux').text = nro_obl_sist_aux etree.SubElement(e_movimiento_presup, 'nro_obl_sist_aux').text = nro_obl_sist_aux etree.SubElement(e_movimiento_presup, 'nro_modif_sist_aux').text = str(nro_modif_grp) etree.SubElement(e_movimiento_presup, 'nro_afectacion').text= str(fondo_rotatorio.nro_afectacion) etree.SubElement(e_movimiento_presup, 'financiamiento').text = fondo_rotatorio.siif_financiamiento.codigo etree.SubElement(e_movimiento_presup, 'nro_compromiso').text = str(fondo_rotatorio.nro_compromiso) etree.SubElement(e_movimiento_presup, 'nro_obligacion').text = str(fondo_rotatorio.nro_obligacion) etree.SubElement(e_movimiento_presup, 'sec_obligacion').text = fondo_rotatorio.siif_sec_obligacion or '' xml = etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='UTF-8', standalone="no") xml2 = Raw(u'<![CDATA[' + xml.decode('utf-8') + u']]>') return xml2
def get_brickset_sets(username, api_key, get_owned): print 'Getting Brickset list of sets...' brickset_wsdl_url = 'http://brickset.com/api/v2.asmx?WSDL' client = Client(brickset_wsdl_url) if get_owned: # we want the owned sets xml_input = """<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://brickset.com/api/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ><SOAP-ENV:Body><tns:getSets xmlns:tns="http://brickset.com/api/"><tns:apiKey>%s</tns:apiKey><tns:userHash></tns:userHash><tns:userHash></tns:userHash><tns:query></tns:query><tns:query></tns:query><tns:theme></tns:theme><tns:theme></tns:theme><tns:subtheme></tns:subtheme><tns:subtheme></tns:subtheme><tns:setNumber></tns:setNumber><tns:setNumber></tns:setNumber><tns:year></tns:year><tns:year></tns:year><tns:owned>1</tns:owned><tns:wanted></tns:wanted><tns:wanted></tns:wanted><tns:orderBy></tns:orderBy><tns:orderBy></tns:orderBy><tns:pageSize>1000</tns:pageSize><tns:pageNumber></tns:pageNumber><tns:pageNumber></tns:pageNumber><tns:userName>%s</tns:userName></tns:getSets></SOAP-ENV:Body></SOAP-ENV:Envelope>""" % ( api_key, username) else: # we want the wanted sets xml_input = """<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://brickset.com/api/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ><SOAP-ENV:Body><tns:getSets xmlns:tns="http://brickset.com/api/"><tns:apiKey>%s</tns:apiKey><tns:userHash></tns:userHash><tns:userHash></tns:userHash><tns:query></tns:query><tns:query></tns:query><tns:theme></tns:theme><tns:theme></tns:theme><tns:subtheme></tns:subtheme><tns:subtheme></tns:subtheme><tns:setNumber></tns:setNumber><tns:setNumber></tns:setNumber><tns:year></tns:year><tns:year></tns:year><tns:owned></tns:owned><tns:owned></tns:owned><tns:wanted>1</tns:wanted><tns:orderBy></tns:orderBy><tns:orderBy></tns:orderBy><tns:pageSize>1000</tns:pageSize><tns:pageNumber></tns:pageNumber><tns:pageNumber></tns:pageNumber><tns:userName>%s</tns:userName></tns:getSets></SOAP-ENV:Body></SOAP-ENV:Envelope>""" % ( api_key, username) xml = Raw(xml_input) response = client.service.getSets(__inject={'msg': xml}) # print response return_sets = response.sets #for set in return_sets: # print set.number return return_sets
def organization_add_update(self,type,name,org_id): xmlstring = ''' <ns0:Organization_Reference_ID>{org_id}</ns0:Organization_Reference_ID> <ns0:Organization_Name>{name}</ns0:Organization_Name> <ns0:Availability_Date>2004-02-14</ns0:Availability_Date> <ns0:Position_Management_Enabled>false</ns0:Position_Management_Enabled> <ns0:Organization_Type_Reference> <ns0:Organization_Type_Name>{type}</ns0:Organization_Type_Name> </ns0:Organization_Type_Reference> <ns0:Organization_Subtype_Reference> <ns0:Organization_Subtype_Name>Cost Center</ns0:Organization_Subtype_Name> </ns0:Organization_Subtype_Reference> <ns0:Organization_Visibility_Reference> <ns0:Organization_Visibility_Name>Everyone</ns0:Organization_Visibility_Name> </ns0:Organization_Visibility_Reference> '''.format(type=type,name=name,org_id=org_id) xml = Raw(xmlstring) #ww_service = 'Add_Update_Organization' #self._launch_head(ww_service, xmlstring) try: self.client1.service.Add_Update_Organization(xml) except WebFault as e: print self.client1.last_sent() print(e) sys.exit()
def _cancel_pickup(self, reference=False): """Cancel shipment for a given reference :param str reference -- shipping reference to cancel :returns: dict -- result of operation with format { 'value': str - response message, '_return': int - response status } Possible response values: 0 -> Recogida anulada -1 -> No existe recogida -2 -> Tiene tracking operativo """ xml = Raw( self._prepare_cancel_pickup_docin( uidcustomer=self.uidcustomer, referencia=reference ) ) _logger.debug(xml) try: response = self.client.service.Anula(docIn=xml) _logger.debug(response) except Exception as e: _logger.error( "No response from server canceling GLS ref {}.\n" "Traceback:\n{}".format(reference, e) ) return {} response = self._recursive_asdict(response.Servicios.Recogida.Resultado) response["gls_sent_xml"] = xml response["_return"] = int(response["_return"]) return response
def readProject(self): niku = NikuDataBus("http://www-dprojetos/niku/wsdl/Object/Projects", "d339954", "foobar", "Auth") ser = niku.webServiceAuth() rp = ser.service.ReadProject(Raw(self.generateXML())) tasks = rp.Projects.Project.Tasks.Task return tasks ser.service.Logout(id)
def PackNsend(self, dict_parse): self.dict_parse['MessageHeader'] = Raw( '''<UUID>SUDS8999124-8c76-61c2345612317212</UUID><CreationDateTime>2017-01-04T17:39:24Z</CreationDateTime> <SenderBusinessSystemID>SapDefaultSystem</SenderBusinessSystemID> ''' ) self.dict_parse['UtilitiesDevice'] = Raw('''<ID>SUDS_meterX4</ID> <StartDate>2000-01-01</StartDate> <EndDate>9999-12-31</EndDate> <SerialID>MRR2111256234</SerialID> <MaterialID>M616523456243</MaterialID> <ProductUniqueItemID>MFin011234</ProductUniqueItemID> <SmartMeter> <UtilitiesAdvancedMeteringSystemID>I210</UtilitiesAdvancedMeteringSystemID> </SmartMeter> ''') sendingData = self.client.service.UtilitiesDeviceERPSmartMeterCreateRequest_In( self.dict_parse['MessageHeader'], self.dict_parse['UtilitiesDevice']) print("Parsed and sent the data to webservice...")
def _sendAuthorizeRequest(self, options_comercio, options_operacion): payload = self._get_payload(options_operacion) options_comercio['Payload'] = payload xml = self._parse_to_service(options_comercio, 'SendAuthorizeRequest') xmlFormat = Raw(xml) self._getClientSoap('Authorize') return self.cliente.service.SendAuthorizeRequest(xmlFormat)
def gen_xml_estado_solicitud(self, anio_fiscal, inciso, unidad_ejecutora, nro_carga): root = etree.Element('ConsultaWS') e_movimiento = etree.SubElement(root, 'movimiento') etree.SubElement(e_movimiento, 'nro_carga').text = nro_carga etree.SubElement(e_movimiento, 'ano_fiscal').text = anio_fiscal.name etree.SubElement(e_movimiento, 'inciso').text = inciso etree.SubElement(e_movimiento, 'unidad_ejecutora').text = unidad_ejecutora xml = etree.tostring(root, pretty_print=False, xml_declaration=True, encoding='UTF-8', standalone="no") xml2 = Raw(u'<![CDATA[' + xml.decode('utf-8') + u']]>') return xml2
def put_document_attachment(client_custom, xml_data): #Load Worker Documents result = None try: result = client_custom.service.Put_Worker_Document("", Raw(xml_data)) except WebFault as e: print(e) sys.exit() return "Successful"
def _get_pickup_info(self, reference=False): xml = Raw( """ <Servicios uidcliente="{uidcustomer}" xmlns="http://www.asmred.com/"> <Recogida codrecogida="{codrecogida}" /> </Servicios> """.format( uidcustomer=self.uidcustomer, codrecogida=reference ) ) res = self.client.service.Tracking(docIn=xml) _logger.debug(res) return self._recursive_asdict(res)
def get_report(iin): client = get_authenticated_client() xml = Raw(""" <keyValue> <idNumber>""" + str(iin) + """</idNumber> <idNumberType>14</idNumberType> <reportImportCode>6</reportImportCode> </keyValue> """) result = client.service.GetReport(200004, xml) root = result['CigResult']['Result']['Root'] existing_credits = root['ExistingContracts']['Contract'] if hasattr( root['ExistingContracts'], 'Contract') else [] terminated_credits = root['TerminatedContracts']['Contract'] if hasattr( root['TerminatedContracts'], 'Contract') else [] if not hasattr(existing_credits, 'count'): existing_credits = [existing_credits] if not hasattr(terminated_credits, 'count'): terminated_credits = [terminated_credits] overdue_for_existing = map( lambda x: { 'non_used': x['OutstandingAmount']['_value'] or None, 'overdue_days': x['NumberOfOverdueInstalments']['_value'], }, existing_credits) overdue_for_terminated = map( lambda x: { 'credit_amount': x['TotalAmount']['_value'] or None, 'overdue_days': x['NumberOfOverdueInstalments']['_value'], 'close_date_with_overdue': x['DateOfCreditEnd']['_value'] if x['NumberOfOverdueInstalments']['_value'] != '0' else None }, terminated_credits) mvd_criminal = root['PublicSources']['MvdCriminalInvestigations'][ 'Status']['_id'] mvd_missing = root['PublicSources']['MvdMissingInvestigations']['Status'][ '_id'] return { 'existing_credits': overdue_for_existing, 'terminated_credits': overdue_for_terminated, 'mvd_criminal': mvd_criminal != '2', # 2 - means not found 'mvd_missing': mvd_missing != '2', # 2 - means not found }
def get_worker(self, employee_id): xmlstring = ''' <ns0:Worker_Reference> <ns0:ID ns0:type="wid">{id}</ns0:ID> </ns0:Worker_Reference> '''.format(id=employee_id) xml =Raw(xmlstring) #ww_service = 'Get_Worker' #result = self._launch_head(ww_service, xmlstring) try: result = self.client1.service.Get_Worker(xml) except WebFault as e: print self.client1.last_sent() print(e) sys.exit() worker_dict = recursive_asdict(result) return worker_dict
def rescind_bp(self, event_id): #not tested xmlstring = ''' <ns0:Event_Reference> <ns0:ID ns0:type="wid">{id}</ns0:ID> </ns0:Event_Reference> '''.format(id=event_id) xml = Raw(xmlstring) try: result = self.client1.service.Rescind_Business_Process(xml) except WebFault as e: print self.client1.last_sent() print(e) sys.exit() worker_dict = recursive_asdict(result) # need to fix later to return Integration event wid or extend method in another object or continue to build method out to return completed event url return worker_dict
def get_int_event(self, int_wid): #not tested xmlstring = ''' <ns0:Request_References> <ns0:Integration_Event_Reference> <ns0:ID ns0:type="wid">{id}</ns0:ID> </ns0:Integration_Event_Reference> </ns0:Request_References> '''.format(id=int_wid) xml = Raw(xmlstring) try: result = self.client1.service.Get_Integration_Event(xml) except WebFault as e: print self.client1.last_sent() print(e) sys.exit() worker_dict = recursive_asdict(result) return worker_dict
def _send_shipping(self, vals): """Create new shipment :params vals dict of needed values :returns dict with GLS response containing the shipping codes, labels, an other relevant data """ vals.update({"uidcustomer": self.uidcustomer}) xml = Raw(self._prepare_send_shipping_docin(**vals)) _logger.debug(xml) try: res = self.client.service.GrabaServicios(docIn=xml) except Exception as e: raise UserError( _( "No response from server recording GLS delivery {}.\n" "Traceback:\n{}" ).format(vals.get("referencia_c", ""), e) ) # Convert result suds object to dict and set the root conveniently # GLS API Errors have codes below 0 so we have to # convert to int as well res = self._recursive_asdict(res)["Servicios"]["Envio"] res["gls_sent_xml"] = xml _logger.debug(res) res["_return"] = int(res["Resultado"]["_return"]) if res["_return"] < 0: raise UserError( _( "GLS returned an error trying to record the shipping for {}.\n" "Error:\n{}" ).format( vals.get("referencia_c", ""), GLS_SHIPMENT_ERROR_CODES.get(res["_return"], res["_return"]), ) ) if res.get("Etiquetas", {}).get("Etiqueta", {}).get("value"): res["gls_label"] = binascii.a2b_base64( res["Etiquetas"]["Etiqueta"]["value"] ) return res
def generateRequestXML(self, recipient, sender, document, track_id, page_template='maileva_connection'): recipient_address_line_list = self._generateAddressLineList(recipient) sender_address_line_list = self._generateAddressLineList(sender) source_section_career_results = self.getPortalObject().portal_catalog( portal_type='Career', parent_uid=recipient.getUid(), subordination_uid=sender.getUid(), validation_state='open') source_section_career = (source_section_career_results[0].getObject() if len(source_section_career_results) else recipient.getDefaultCareerValue() or '') if not source_section_career.getReference(): raise ValueError('%s has no employee number defined' % source_section_career.getRelativeUrl()) xml = getattr(document, page_template)( user=self.getUserId(), password=self.getPassword(), career_start_date=source_section_career.getStartDate().strftime( '%Y-%m-%d'), employee_number=source_section_career.getReference(), recipient_region=recipient.getDefaultAddress().getRegionValue(), recipient=recipient, recipient_address_line_list=recipient_address_line_list, sender_region=sender.getDefaultAddress().getRegionValue(), sender_address_line_list=sender_address_line_list, content=base64.b64encode(document.getData()), track_id=track_id) non_empty_lines = [ line for line in xml.split('\n') if line.strip() != "" ] xml = "" for line in non_empty_lines: xml += line + "\n" return Raw(xml).encode("UTF-8")
def request_p0(url, user, password, xml_str): t = HttpAuthenticated(username=user, password=password) base64string = base64.encodestring('%s:%s' % (user, password)).replace( '\n', '') auth_header = {"Authorization": "Basic %s" % base64string} try: client = Client(url, retxml=True, transport=t, cache=NoCache()) except urllib2.URLError as e: import ssl ssl._create_default_https_context = ssl._create_unverified_context client = Client(url, retxml=True, transport=t, cache=NoCache()) client.set_options(headers=auth_header) # Clean XML xml_str = xml_str.strip() xml_str = xml_str.replace("'utf-8'", "'UTF-8'") xml_str = xml_str.replace("<?xml version='1.0' encoding='UTF-8'?>", "") xml_str = Raw(xml_str) # Send request res = client.service.sync(xml_str) try: def find_child(element, child_name): res = None if child_name in element.tag: return element for child in element: res = find_child(child, child_name) if res is not None: break return res aux = etree.fromstring(res) aux_res = find_child(aux, "MensajeEnvioInformacionPS") res = etree.tostring(aux_res) except Exception: pass return res
def launch_int(self, int_wid): # The workflow is, generate an XML element containing the employee ID, then post # that element to the Launch_Integration() method in the WSDL as an argument. # We could do this with two suds calls, having it generate the XML from the schema, # but here I'm creating the POST XML manually and submitting it via suds's `Raw()` function. xmlstring = ''' <ns0:ID ns0:type="wid">{id}</ns0:ID> '''.format(id=int_wid) xml = Raw(xmlstring) try: result = self.client1.service.Launch_Integration(xml) except WebFault as e: print self.client1.last_sent() print(e) sys.exit() worker_dict = recursive_asdict(result) event = worker_dict['Launch_Integration_Event_Data']['Parent_Event_Reference'] eventwid = event['ID'][0]['value'] print eventwid return eventwid
security = Security() token = UsernameToken(username, password) security.tokens.append(token) client.set_options(wsse=security) # The workflow is, generate an XML element containing the employee ID, then post # that element to the Get_Workers() method in the WSDL as an argument. # We could do this with two suds calls, having it generate the XML from the schema, # but here I'm creating the POST XML manually and submitting it via suds's `Raw()` function. xmlstring = ''' <ns0:Worker_Reference> <ns0:ID ns0:type="Employee_ID">{id}</ns0:ID> </ns0:Worker_Reference> '''.format(id=Employee_ID) xml = Raw(xmlstring) try: result = client.service.Get_Workers(xml) except WebFault as e: # Employee ID probably doesn't exist. print(e) sys.exit() # =================== # That's essentially all you need. Everything below is just response parsing. # =================== # Converts the unusually formatted response object to standard Python dictionary. # You'll probably want to move this into a utils.py and import it.
def voidRequest(self, optionsVoid): self._getClientSoap('Authorize') xml = self._parse_to_service(optionsVoid, 'VoidRequest') xmlFormat = Raw(xml) return dict(self.cliente.service.VoidRequest(xmlFormat))
def returnRequest(self, optionsReturn): self._getClientSoap('Authorize') xml = self._parse_to_service(optionsReturn, 'ReturnRequest') xmlFormat = Raw(xml) return dict(self.cliente.service.ReturnRequest(xmlFormat))
def _getAuthorizeAnswer(self, optionsAnwser): self._getClientSoap('Authorize') xml = self._parse_to_service(optionsAnwser, 'GetAuthorizeAnswer') xmlFormat = Raw(xml) return self.cliente.service.GetAuthorizeAnswer(xmlFormat)
def getStatus(self, optionsGS): self._getClientSoap('Operations') xml = self._parse_to_service(optionsGS, 'GetByOperationId') xmlFormat = Raw(xml) return self.cliente.service.GetByOperationId(xmlFormat)
def getSiteData(self, site_name, url_prefix, libraries): if (libraries != None): self.logger().info('Running getSiteData for site: [' + site_name + '], for [' + str(libraries.length) + '] libraries') else: self.logger().info('Running Initial Traversal for site: [' + site_name + ']') lib_dict = [] ntlm = WindowsHttpAuthenticated(username=self.SP_DOMAIN + '\\' + self.SP_USER, password=self.SP_PASSWORD) url = url_prefix + '/_vti_bin/SiteData.asmx?WSDL' client = suds.client.Client(url, transport=ntlm) # First get the FolderID number for that site resp = client.service.GetListCollection() for _sList in resp.vLists._sList: if _sList.BaseType == "DocumentLibrary": folder_id = _sList.InternalName self.logger().info('Found [' + _sList.Title + '] of type [' + _sList.BaseType + ']' + ' with Folder ID: ' + folder_id) # get ready to refeed all the doc URLs feed_type = 'metadata-and-url' feed = connector.Feed(feed_type) last_sync = None # See if there is a change token for the current site if (libraries != None): for lib in libraries: if (lib.attributes['id'].value == folder_id): last_sync = lib.attributes['last_sync'].value self.logger().info( 'Retrieved LastChangeToken from file [' + last_sync + ']') # then use that ID to get the document lists ntlm = WindowsHttpAuthenticated(username=self.SP_DOMAIN + '\\' + self.SP_USER, password=self.SP_PASSWORD) url = url_prefix + '/_vti_bin/Lists.asmx?WSDL' client = suds.client.Client(url, transport=ntlm) # attribute used for paging ListItemCollectionPositionNext = '' while (ListItemCollectionPositionNext != None): query = ( '<Query><OrderBy><FieldRef Name="Created" Ascending="TRUE" /></OrderBy></Query>' ) viewfields = '<ViewFields Properties="TRUE"/>' # get 100 rows now per cursor... rowlimit = 100 if (ListItemCollectionPositionNext != ''): queryoptions = ( '<QueryOptions><IncludeMandatoryColumns>true</IncludeMandatoryColumns>' + '<DateInUtc>TRUE</DateInUtc><ViewAttributes Scope="Recursive"/>' + '<Paging ListItemCollectionPositionNext="%s"/>' + '<OptimizeFor>ItemIds</OptimizeFor></QueryOptions>' ) % (escape(ListItemCollectionPositionNext)) else: queryoptions = ( '<QueryOptions><IncludeMandatoryColumns>true</IncludeMandatoryColumns>' + '<DateInUtc>TRUE</DateInUtc><ViewAttributes Scope="Recursive"/>' + '<OptimizeFor>ItemIds</OptimizeFor></QueryOptions>' ) contains = ( '<Contains><FieldRef Name="Status"/><Value Type="Text">Complete</Value></Contains>' ) client.service.GetListItemChangesSinceToken( folder_id, '', Raw(query), Raw(viewfields), rowlimit, Raw(queryoptions), last_sync, Raw(contains)) li = client.last_received().getChild( "soap:Envelope").getChild("soap:Body").getChild( "GetListItemChangesSinceTokenResponse").getChild( "GetListItemChangesSinceTokenResult").getChild( "listitems") # Read the last change token from Sharepoint changes = li.getChild('Changes') if (changes != None): if (changes.getAttribute("LastChangeToken") != None): changeid = changes.getAttribute( "LastChangeToken").getValue() self.logger().info('Found new LastChangeToken [' + changeid + ']') else: self.logger().info('LastChangeToken is None') else: self.logger().info('LastChangeToken is None') rsd = li.getChild("rs:data") # extract out the cursor ListItemCollectionPositionNext if (rsd.getAttribute('ListItemCollectionPositionNext') != None): ListItemCollectionPositionNext = rsd.getAttribute( 'ListItemCollectionPositionNext').getValue() self.logger().info( 'Found response cursor ListItemCollectionPositionNext [' + ListItemCollectionPositionNext + ']') else: ListItemCollectionPositionNext = None # now for each row returned, add that to the feed set for zrow in rsd: if zrow != None: my_url = zrow.getAttribute( "ows_EncodedAbsUrl").getValue() my_last_modified = zrow.getAttribute( "ows_Last_x0020_Modified").getValue() self.logger().debug('Found URL [' + my_url + ']') # set all the attributes for this feed (TODO: set the security SPI parameters) feed.addRecord(url=my_url, displayurl=my_url, action='add', mimetype='text/html') else: break # Finally, save the library name and change token so that the next time, we know where we left off... lib_dict.append('<library id="' + folder_id + '" name="' + _sList.Title + '" last_sync="' + changeid + '" />') # flush the records to the GSA self.logger().info('Transmitting [' + str(len(rsd)) + '] documents.') self.pushFeed(feed) feed.clear() # return the last sync time return lib_dict
def gen_xml_obligacion_3en1_fr(self, cr, uid, fondo_rotatorio, llaves_presupuestales, importe, nro_carga, tipo_doc_grp, nro_modif_grp, tipo_modificacion, es_modif=False, retenciones=False, motivo=False, enviar_datos_sice=True, nro_obl_sist_aux=False): _tipo_registro = '01' _tipo_registracion = '04' if es_modif is False else '14' _concepto_gasto = fondo_rotatorio.siif_concepto_gasto.concepto _monto = str(int(round(importe, 0))) company = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid).company_id estructura_obj = self.pool.get('presupuesto.estructura') root = etree.Element('MovimientosSIIF') etree.SubElement(root, 'nro_carga').text = nro_carga e_movimientos = etree.SubElement(root, 'movimientos') estructura = estructura_obj.obtener_estructura( cr, uid, fondo_rotatorio.fiscal_year_id.id, fondo_rotatorio.inciso_siif_llp_id.inciso, fondo_rotatorio.ue_siif_llp_id.ue, llaves_presupuestales[0].programa, llaves_presupuestales[0].proyecto, llaves_presupuestales[0].mon, llaves_presupuestales[0].tc, llaves_presupuestales[0].fin, llaves_presupuestales[0].odg, llaves_presupuestales[0].auxiliar) e_movimiento_presup = etree.SubElement(e_movimientos, 'MovimientoPresupuestalSIIF') etree.SubElement(e_movimiento_presup, 'tipo_registro').text = _tipo_registro etree.SubElement(e_movimiento_presup, 'tipo_registracion').text = _tipo_registracion etree.SubElement(e_movimiento_presup, 'desc_tipo_mov').text = 'OBL_ORIG_Y_MODIF_GRP' etree.SubElement( e_movimiento_presup, 'ano_fiscal').text = fondo_rotatorio.fiscal_year_id.name etree.SubElement( e_movimiento_presup, 'inciso').text = fondo_rotatorio.inciso_siif_llp_id.inciso or '' etree.SubElement( e_movimiento_presup, 'unidad_ejecutora').text = fondo_rotatorio.ue_siif_llp_id.ue or '' etree.SubElement(e_movimiento_presup, 'tipo_doc_sist_aux').text = tipo_doc_grp # En 3en1 nro_afect_sist_aux, nro_comp_sist_aux y nro_obl_sist_aux son nro_obl_sist_aux etree.SubElement(e_movimiento_presup, 'nro_afect_sist_aux').text = nro_obl_sist_aux etree.SubElement(e_movimiento_presup, 'nro_comp_sist_aux').text = nro_obl_sist_aux etree.SubElement(e_movimiento_presup, 'nro_obl_sist_aux').text = nro_obl_sist_aux etree.SubElement(e_movimiento_presup, 'nro_modif_sist_aux').text = str(nro_modif_grp) etree.SubElement(e_movimiento_presup, 'nro_afectacion').text = str( fondo_rotatorio.nro_afectacion) if es_modif else '' etree.SubElement(e_movimiento_presup, 'nro_compromiso').text = str( fondo_rotatorio.nro_compromiso) if es_modif else '' etree.SubElement(e_movimiento_presup, 'nro_obligacion').text = str( fondo_rotatorio.nro_obligacion ) if es_modif or tipo_modificacion == 'N' else '' etree.SubElement(e_movimiento_presup, 'sec_obligacion') etree.SubElement(e_movimiento_presup, 'tipo_modificacion').text = tipo_modificacion etree.SubElement(e_movimiento_presup, 'fecha_elaboracion').text = time.strftime('%Y%m%d') if fondo_rotatorio.currency_id.name <> 'UYU' and fondo_rotatorio.send_currency2siif: monto_obligacion = fondo_rotatorio.total_reponer else: monto_obligacion = fondo_rotatorio.total_nominal_comprobantes_manual etree.SubElement(e_movimiento_presup, 'monto_obligacion').text = str( int(round(monto_obligacion, 0))) if not es_modif else _monto etree.SubElement(e_movimiento_presup, 'total_retenciones').text = str( int(round(fondo_rotatorio.total_retenciones_currency_manual, 0))) if fondo_rotatorio.currency_id.name <> 'UYU' and fondo_rotatorio.send_currency2siif: liquido_pagable = fondo_rotatorio.liquido_pagable else: liquido_pagable = fondo_rotatorio.total_liquido_pagable_manual etree.SubElement(e_movimiento_presup, 'liquido_pagable').text = str( int(round(liquido_pagable, 0))) if not es_modif else _monto etree.SubElement( e_movimiento_presup, 'partidas_mon_ext' ).text = 'N' if llaves_presupuestales[0].mon == '0' else 'S' # if fondo_rotatorio.currency_id.name <> 'UYU' and fondo_rotatorio.send_currency2siif: # monto_mon_ext = str(round(fondo_rotatorio.liquido_pagable / fondo_rotatorio.currency_rate_presupuesto)) # else: # monto_mon_ext = '' etree.SubElement(e_movimiento_presup, 'monto_mon_ext').text = str( int( round(fondo_rotatorio.liquido_pagable / fondo_rotatorio.currency_rate_presupuesto))) if ( fondo_rotatorio.currency_id.name <> 'UYU' and fondo_rotatorio.send_currency2siif) else '' etree.SubElement( e_movimiento_presup, 'tipo_ejecucion').text = fondo_rotatorio.siif_tipo_ejecucion.codigo etree.SubElement(e_movimiento_presup, 'tipo_programa').text = 'T' etree.SubElement( e_movimiento_presup, 'tipo_documento' ).text = fondo_rotatorio.siif_tipo_documento.codigo or '' etree.SubElement(e_movimiento_presup, 'numero_documento') etree.SubElement(e_movimiento_presup, 'ano_doc_respaldo') etree.SubElement(e_movimiento_presup, 'fecha_doc_respaldo') etree.SubElement(e_movimiento_presup, 'serie_documento') etree.SubElement(e_movimiento_presup, 'secuencia_documento') etree.SubElement(e_movimiento_presup, 'fecha_recepcion').text = datetime.strptime( fondo_rotatorio.date_invoice, '%Y-%m-%d').strftime('%Y%m%d') etree.SubElement(e_movimiento_presup, 'fecha_vencimiento').text = datetime.strptime( fondo_rotatorio.fecha_vencimiento, '%Y-%m-%d').strftime('%Y%m%d') etree.SubElement(e_movimiento_presup, 'clase_doc_benef').text = 'T' inciso = company and int(company.inciso) # u_e = company and int(company.u_e) if fondo_rotatorio.unidad_ejecutora_id.codigo: u_e = fondo_rotatorio.unidad_ejecutora_id.codigo else: u_e = int(fondo_rotatorio.operating_unit_id.unidad_ejecutora) etree.SubElement( e_movimiento_presup, 'num_doc_benef').text = '%s%s' % (str(inciso).zfill(2), str(u_e).zfill(3)) if fondo_rotatorio.res_partner_bank_id: if not fondo_rotatorio.res_partner_bank_id.bank_bic: raise osv.except_osv( ('Error'), (u'Debe especificar el código de la cuenta bancaria.')) etree.SubElement( e_movimiento_presup, 'banco_cta_benef' ).text = fondo_rotatorio.res_partner_bank_id.bank_bic etree.SubElement( e_movimiento_presup, 'agencia_cta_benef' ).text = fondo_rotatorio.res_partner_bank_id.agencia or '' etree.SubElement( e_movimiento_presup, 'nro_cta_benef' ).text = fondo_rotatorio.res_partner_bank_id.acc_number.replace( '-', '').replace(' ', '') etree.SubElement( e_movimiento_presup, 'tipo_cta_benef' ).text = 'A' if fondo_rotatorio.res_partner_bank_id.state == 'caja de ahorros' else 'C' etree.SubElement( e_movimiento_presup, 'moneda_cta_benef' ).text = '0' if not fondo_rotatorio.res_partner_bank_id.currency_id else '1' else: raise osv.except_osv(('Error'), (u'No se especificó la cuenta bancaria.')) etree.SubElement(e_movimiento_presup, 'concepto_gasto').text = _concepto_gasto etree.SubElement( e_movimiento_presup, 'financiamiento').text = fondo_rotatorio.siif_financiamiento.codigo etree.SubElement( e_movimiento_presup, 'codigo_sir').text = fondo_rotatorio.siif_codigo_sir.codigo # FR envia vacio los siguientes datos etree.SubElement(e_movimiento_presup, 'ano_proc_compra') etree.SubElement(e_movimiento_presup, 'inciso_proc_compra') etree.SubElement(e_movimiento_presup, 'unidad_ejec_proc_compra') etree.SubElement(e_movimiento_presup, 'tipo_proc_compra') etree.SubElement(e_movimiento_presup, 'subtipo_proc_compra') etree.SubElement(e_movimiento_presup, 'nro_proc_compra') etree.SubElement(e_movimiento_presup, 'nro_amp_proc_compra') if fondo_rotatorio.currency_id.name <> 'UYU' and fondo_rotatorio.send_currency2siif: monto_cambio = int( round(fondo_rotatorio.currency_rate_presupuesto * 10000)) tipo_cambio = str(monto_cambio) else: tipo_cambio = '' etree.SubElement(e_movimiento_presup, 'tipo_cambio').text = tipo_cambio etree.SubElement(e_movimiento_presup, 'anticipo').text = 'N' if fondo_rotatorio.currency_id.name == 'UYU' or ( fondo_rotatorio.currency_id.name <> 'UYU' and fondo_rotatorio.send_currency2siif): _moneda = str(fondo_rotatorio.currency_id.codigo_siif) else: _moneda = '0' etree.SubElement(e_movimiento_presup, 'moneda').text = _moneda etree.SubElement( e_movimiento_presup, 'resumen' ).text = fondo_rotatorio.siif_descripcion or '' if not es_modif else motivo etree.SubElement(e_movimiento_presup, 'nro_doc_fondo_rotatorio' ).text = fondo_rotatorio.siif_nro_fondo_rot.name or '' etree.SubElement(e_movimiento_presup, 'inciso_doc_optgn') etree.SubElement(e_movimiento_presup, 'unidad_ejec_doc_optgn') etree.SubElement(e_movimiento_presup, 'nro_doc_optgn') etree.SubElement(e_movimiento_presup, 'nro_doc_transferencia') etree.SubElement(e_movimiento_presup, 'monto_compromiso') etree.SubElement(e_movimiento_presup, 'nro_doc_transf_monto_iva') etree.SubElement(e_movimiento_presup, 'monto_iva') etree.SubElement(e_movimiento_presup, 'monto_iva_mon_ext') etree.SubElement(e_movimiento_presup, 'monto_serv_pers') etree.SubElement(e_movimiento_presup, 'monto_serv_pers_mon_ext') etree.SubElement(e_movimiento_presup, 'sec_compromiso') e_detalle = etree.SubElement(e_movimiento_presup, 'Detalle') for llave in llaves_presupuestales: if llave.importe: estructura = estructura_obj.obtener_estructura( cr, uid, fondo_rotatorio.fiscal_year_id.id, fondo_rotatorio.inciso_siif_llp_id.inciso, fondo_rotatorio.ue_siif_llp_id.ue, llave.programa, llave.proyecto, llave.mon, llave.tc, llave.fin, llave.odg, llave.auxiliar) e_detalle_siif = etree.SubElement(e_detalle, 'DetalleSIIF') if estructura: etree.SubElement(e_detalle_siif, 'tipo_registro').text = '02' etree.SubElement( e_detalle_siif, 'tipo_registracion').text = _tipo_registracion etree.SubElement( e_detalle_siif, 'programa').text = estructura.linea_programa etree.SubElement( e_detalle_siif, 'desc_tipo_mov').text = 'PART_OBL_ORIG_Y_MODIF_GRP' etree.SubElement( e_detalle_siif, 'proyecto').text = estructura.linea_proyecto etree.SubElement(e_detalle_siif, 'objeto_gasto').text = estructura.linea_og etree.SubElement(e_detalle_siif, 'auxiliar').text = estructura.linea_aux etree.SubElement( e_detalle_siif, 'financiamiento').text = estructura.linea_ff etree.SubElement(e_detalle_siif, 'moneda').text = estructura.linea_moneda etree.SubElement(e_detalle_siif, 'tipo_credito').text = estructura.linea_tc if es_modif: if tipo_modificacion == 'N': monto = str(int(-llave.importe)) else: monto = _monto else: monto = str(int(llave.importe)) etree.SubElement(e_detalle_siif, 'importe').text = monto e_retencion = etree.SubElement(e_movimiento_presup, 'Retenciones') for retencion in retenciones: if retencion['monto'] != 0: e_retencion_siif = etree.SubElement(e_retencion, 'RetencionSIIF') etree.SubElement(e_retencion_siif, 'tipo_registro').text = '03' etree.SubElement(e_retencion_siif, 'tipo_registracion').text = _tipo_registracion etree.SubElement( e_retencion_siif, 'grupo_acreedor').text = retencion['grupo'] and str( retencion['grupo']) or '' etree.SubElement( e_retencion_siif, 'acreedor').text = retencion['acreedor'] and str( retencion['acreedor']) or '' etree.SubElement(e_retencion_siif, 'importe').text = str( int(round(retencion['monto'], 0))) e_impuestos = etree.SubElement(e_movimiento_presup, 'Impuestos') # MVARELA 04/12/2018: Los FR no deben enviar Impuestos # for retencion in retenciones: # if not retencion['es_manual']: # e_impuesto_siif = etree.SubElement(e_impuestos, 'ImpuestoSIIF') # etree.SubElement(e_impuesto_siif, 'tipo_registro').text = '05' # etree.SubElement(e_impuesto_siif, 'tipo_registracion').text = _tipo_registracion # etree.SubElement(e_impuesto_siif, 'tipo_impuesto').text = str(retencion['acreedor']) # # if 'base_impuesto' in retencion: # etree.SubElement(e_impuesto_siif, 'monto_calculo').text = str(int(round(retencion['base_impuesto']))) if tipo_modificacion != 'N' else str(-int(round(retencion['base_impuesto']))) # # if 'base_impuesto_mont_ext' in retencion: # # etree.SubElement(e_impuesto_siif, 'monto_calculo_mon_ext').text = str(int(round(retencion['base_impuesto_mont_ext']))) if tipo_modificacion != 'N' else str(-int(round(retencion['base_impuesto_mont_ext']))) e_ces_o_emb = etree.SubElement(e_movimiento_presup, 'CesionesOEmbargos') xml = etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='UTF-8', standalone="no") xml2 = Raw(u'<![CDATA[' + xml.decode('utf-8') + u']]>') return xml2
for attr in self.payload_cols: if hasattr(pat.patient, attr): en_out[self.payload_cols[attr]] = getattr( pat.patient, attr) elif hasattr(pat, attr): en_out[self.payload_cols[attr]] = getattr( pat, attr) elif hasattr(pat.patient, 'address'): if len(pat.patient.address) > 0: if hasattr(pat.patient.address[0], attr): en_out[ self.payload_cols[attr]] = getattr( pat.patient.address[0], attr) lids = None xml_lid = Raw('%s' % pat.EUID) try: lids = self.client.service.getLIDs(xml_lid) except WebFault, f: sys.stderr.write(f) sys.exit(f.fault) except Exception, e: sys.stderr.write(e) sys.exit(e.errno) if not lids: self.serializer.writerow(en_out_lid) else:
def poll(self): rc = readConfig() from suds.client import Client #logging.basicConfig(level=logging.INFO) #logging.getLogger('suds.client').setLevel(logging.DEBUG) #logging.getLogger('suds.transport').setLevel(logging.DEBUG) print('creating client ws for DS Check') client = Client(rc.WSDLEndpoint, username = rc.userName, password = rc.password, retxml=True, faults=False) #self.ucmid='UCMFA225638' global UCMContentID paramStr = 'ContentId=' + UCMContentID print("paramStr" + paramStr) #paramStr = 'ContentId=' + 'UCMFA225638' while 1: print('Invoke WS for DS Check..') result = client.service.getDataSetStatusAsync(Parameters=''+paramStr) root = ET.fromstring(result) statusStr = '(the status will refresh every ' + rc.refreshTime + ' seconds..) \n' overallStatus = '' self.gui.textDSStatus.configure(state='normal') self.gui.textDSStatus.delete('1.0','end') self.gui.textDSStatus.configure(state='disabled') for child in root.iter(): if child.tag == '{http://xmlns.oracle.com/apps/hcm/common/dataLoader/core/dataLoaderIntegrationService/types/}result' : xml = ET.fromstring(child.text.lstrip().rstrip()) break for node in xml.findall('DATA_SET/STATUS'): overallStatus = node.text statusStr = statusStr + 'Overall Status: ' + node.text + '\n' #print('Overall Status:' + node.text) for node in xml.findall('DATA_SET/IMPORT/'): if node.tag == 'STATUS': statusStr = statusStr + 'Import Status: ' + node.text + '\n' #print('IMPORT Status:' + node.text) if node.tag == 'PERCENTAGE_COMPLETE': statusStr = statusStr + 'Import Percentage Completion: ' + node.text + '\n' #print('Percentage complete:' + node.text) for node in xml.findall('DATA_SET/LOAD/'): if node.tag == 'STATUS': statusStr = statusStr + 'Load Status: ' + node.text + '\n' #print('EXPORT Status:' + node.text) if node.tag == 'PERCENTAGE_COMPLETE': statusStr = statusStr + 'Load Percentage Completion: ' + node.text + '\n' #print('Percentage complete:' + node.text) self.gui.textDSStatus.configure(state='normal') self.gui.textDSStatus.insert('1.0',statusStr) self.gui.textDSStatus.configure(state='disabled') print("OverallStatus: " + overallStatus) if overallStatus == 'COMPLETED': print('Load Complete..') #send BI request to the server for the report print('Calling the BI report WS..') from suds.client import Client BIclient = Client(rc.BIWSDL, username = rc.userName, password = rc.password, retxml=True, faults=False) rrStr = ' ' #rrStr = rrStr + ' <ns0:reportRequest>' rrStr = rrStr + ' <ns0:attributeFormat>'+ rc.reportFormat +'</ns0:attributeFormat>' rrStr = rrStr + ' <ns0:parameterNameValues>' rrStr = rrStr + ' <ns0:item>' rrStr = rrStr + ' <ns0:name>CON</ns0:name>' rrStr = rrStr + ' <ns0:values>' rrStr = rrStr + ' <ns0:item>' + UCMContentID + '</ns0:item>' rrStr = rrStr + ' </ns0:values>' rrStr = rrStr + ' </ns0:item>' rrStr = rrStr + ' </ns0:parameterNameValues>' rrStr = rrStr + ' <ns0:reportAbsolutePath>'+ rc.reportPath +'</ns0:reportAbsolutePath>' rrStr = rrStr + ' <ns0:sizeOfDataChunkDownload>-1</ns0:sizeOfDataChunkDownload>' #rrStr = rrStr + ' </ns0:reportRequest>' from suds.sax.text import Raw rrStr = Raw(rrStr) result = BIclient.service.runReport(rrStr,userID = rc.userName,password = rc.password) rootBI = ET.fromstring(result) print('Results fetched from BI Service..') for child in rootBI.iter(): if child.tag == '{http://xmlns.oracle.com/oxp/service/PublicReportService}reportBytes' : rawBytes = child.text print('Log File Created at - C:\\temp\HDLLOader\Logs\\' + UCMContentID + '.' + rc.reportFormat) statusStr = statusStr + 'Log File Created at - C:\\temp\HDLLOader\Logs\\' + UCMContentID + '.' + rc.reportFormat + '\n' self.gui.textDSStatus.configure(state='normal') self.gui.textDSStatus.delete('1.0','end') self.gui.textDSStatus.insert('1.0',statusStr) self.gui.textDSStatus.configure(state='disabled') open('C:\\temp\\HDLLOader\\Logs\\' + UCMContentID + '.' + rc.reportFormat ,'wb').write(base64.b64decode(rawBytes)) self.gui.btnSubmit.config(state='normal') self.queue.put("Task Finished") break break else: print('Load running..sleeping for '+ rc.refreshTime + ' seconds') time.sleep(int(rc.refreshTime))