def testSoap(self): # test soap server implementation from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault url = 'http://127.0.0.1:8000/examples/soap_examples/call/soap?WSDL' client = SoapClient(wsdl=url) ret = client.SubIntegers(a=3, b=2) # check that the value returned is ok assert ('SubResult' in ret) assert (ret['SubResult'] == 1) try: ret = client.Division(a=3, b=0) except SoapFault as sf: # verify the exception value is ok # assert(sf.faultstring == "float division by zero") # true only in 2.7 assert (sf.faultcode == "Server.ZeroDivisionError") # store sent and received xml for low level test xml_request = client.xml_request xml_response = client.xml_response # do a low level raw soap request (using s = WebClient('http://127.0.0.1:8000/') try: s.post('examples/soap_examples/call/soap', data=xml_request, method="POST") except urllib2.HTTPError as e: assert (e.msg == 'INTERNAL SERVER ERROR') # check internal server error returned (issue 153) assert (s.status == 500) assert (s.text == xml_response)
def HacerPedido(): ID = request.vars.ID Fecha = request.vars.Fecha cantidad = request.vars.cantidad DNI = request.vars.DNI client = SoapClient( wsdl="http://localhost:8000/ServiciosSOAP/Servicios/call/soap?WSDL") result = client.HacerPedido(ID, Fecha, DNI, cantidad) return str(result['Status'])
def test_soap_sub(): from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault # build the url to the WSDL (web service description) # like "http://localhost:8000/webservices/sample/call/soap?WSDL" url = URL(f="call/soap", vars={"WSDL": ""}, scheme=True) # create a SOAP client client = SoapClient(wsdl="http://diegocunha.pythonanywhere.com/Helpy/webservices/call/soap?WSDL") # call the SOAP remote method try: ret = client.obterNomeDisciplina(codigo='MATC82') result = ret except SoapFault, sf: result = sf
def test_soap_sub(): from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault # build the url to the WSDL (web service description) # like "http://localhost:8000/webservices/sample/call/soap?WSDL" url = URL(f="call/soap", vars={"WSDL": ""}, scheme=True) # create a SOAP client client = SoapClient(wsdl=url) # call the SOAP remote method try: ret = client.SubIntegers(a=3, b=2) result = ret['SubResult'] except SoapFault, sf: result = sf
def test_dummy(): from gluon.contrib.pysimplesoap.client import SoapClient WSDL = "https://www.sistemasagiles.com.ar/simulador/wsfev1/call/soap?WSDL=None" client = SoapClient(wsdl=WSDL) try: ret = client.FEDummy() except: ret = client.xml_response response.view = "generic.html" return dict(ret=ret)
def test_soap_sub(): from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault #create a SOAP client client = SoapClient(wsdl="http://127.0.0.1:8000/webservices/sample/call/soap?WSDL=None") #call SOAP method response = client.listaOrgao(nome='orgao 1',endereco='',cidade='',uf='') #response = client.insereOrgao(cnpj='1223456',nome='Ministerio WEB',endereco='dfdf',cidade='dddd',uf='df') #response = client.insereEmpregado(nome='Empregado WEB',dt_contratacao='18/07/2013',dt_desligamento='',dt_nascimento='19/09/1989',nu_matricula='M123456',rg='123',cpf='123456',id_orgao='2',documentos='',dependentes='') try: #result = response['s'] result = response except SoapFault: result = None return dict(xml_request=client.xml_request,xml_response=client.xml_response,result=result)
def test_soap_sub(): from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault # build the url to the WSDL (web service description) # like "http://localhost:8000/webservices/sample/call/soap?WSDL" url = URL(f="call/soap", vars={"WSDL": ""}, scheme=True) # create a SOAP client client = SoapClient( wsdl= "http://diegocunha.pythonanywhere.com/Helpy/webservices/call/soap?WSDL" ) # call the SOAP remote method try: ret = client.obterNomeDisciplina(codigo='MATC82') result = ret except SoapFault, sf: result = sf
def testSoap(self): # test soap server implementation from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault url = 'http://127.0.0.1:8000/examples/soap_examples/call/soap?WSDL' client = SoapClient(wsdl=url) ret = client.SubIntegers(a=3, b=2) # check that the value returned is ok assert ('SubResult' in ret) assert (ret['SubResult'] == 1) try: ret = client.Division(a=3, b=0) except SoapFault, sf: # verify the exception value is ok # assert(sf.faultstring == "float division by zero") # true only in 2.7 assert (sf.faultcode == "Server.ZeroDivisionError")
def test_custom_response_element_name(): from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault # build the url to the WSDL (web service description) # like "http://localhost:8000/webservices/sample/call/soap?WSDL" url = URL(f="call/soap", vars={"WSDL": ""}, scheme=True) # create a SOAP client client = SoapClient(wsdl=url) # call the SOAP remote method try: ret = client.DummyCustomElement(in0="Hello World!") result = ret['out0'] except SoapFault as sf: result = sf response.view = "soap_examples/generic.html" return dict(xml_request=client.xml_request, xml_response=client.xml_response, result=result)
def test_soap_sub(): from gluon.contrib.pysimplesoap.client import SoapClient, SoapFault # create a SOAP client url = "http://" + request.wsgi.environ["HTTP_HOST"] + URL( c="sample", f="call", args=[ "soap", ]) + "?WSDL" client = SoapClient(wsdl=url) # call SOAP method response = client.SubIntegers(a=3, b=2) try: result = response['SubResult'] except SoapFault: result = None return dict(xml_request=client.xml_request, xml_response=client.xml_response, result=result)
def test_ult(): from gluon.contrib.pysimplesoap.client import SoapClient WSDL = "https://www.sistemasagiles.com.ar/simulador/wsfev1/call/soap?WSDL=None" client = SoapClient(wsdl=WSDL) try: ret = client.FECompUltimoAutorizado(Auth={ 'Token': 'token', 'Sign': 'sign', 'Cuit': '20267565393' }, PtoVta=1, CbteTipo=10) except: raise ret = client.xml_response response.view = "generic.html" return dict(ret=ret)
def newshop(): # if settings.prelaunch==True and not (auth.has_membership('administradores') or auth.has_membership('superadministradores')): # redirect(URL(request.application, 'communications','prelaunch')) from shops import Shop, DomainShop from gluon.contrib.pysimplesoap.client import SoapClient import time Shop(db), DomainShop(db) lenshops = db((db.shop.id > 0) & (db.shop.user == auth.user_id)).count() count = db.domainshops.id.count() countsdomainshops = int( db((db.shop.id > 0) & (db.shop.user == auth.user_id) & (db.domainshops.shop == db.shop.id)).select( count, left=[db.domainshops.on(db.domainshops.shop == db.shop.id) ]).first()['COUNT(domainshops.id)']) shopid = None if lenshops <= 10 + countsdomainshops: form = None from queuemail import Queuemail Queuemail(db) firstname = Field( 'first_name', 'string', length=128, notnull=True, requires=IS_NOT_EMPTY( error_message= 'Para dirigirnos a usted y para los clientes en su tienda')) lastname = Field( 'last_name', 'string', length=128, notnull=True, requires=IS_NOT_EMPTY( error_message= 'Para dirigirnos a usted y para los clientes en su tienda')) shopname = Field( 'name', 'string', length=80, notnull=True, unique=True, requires=[ IS_NOT_EMPTY( error_message='No olvide decirnos el nombre de su tienda'), IS_NOT_IN_DB(db, 'shop.name', error_message="Este nombre ya está siendo usado") ]) hostname = Field( 'host', 'string', length=45, notnull=True, unique=True, requires=[ IS_MATCH( '^\w+$', 'Sólo letras y números, ni espacios ni caracteres especiales' ), IS_NOT_EMPTY( error_message= 'Más adelante podrás poner tu propio dominio, pero ahora es importante este dato' ), IS_NOT_IN_DB(db, 'shop.host', error_message="Este nombre ya está siendo usado") ]) form = SQLFORM.factory(firstname, lastname, shopname, hostname, submit_button=T('Create new store')) if form.validate(): try: #almacena los datos dbdata = "%s" % str(time.time()).replace('.', '') shopid = db.shop.insert( user=auth.user_id, host=form.vars.host, db_name="gex%s" % dbdata, db_user="******" % dbdata, name=form.vars.name, email=auth.user.email, first_name=form.vars.first_name, last_name=form.vars.last_name, country='es', language='es', ip=__get_ip_address('wlan0'), ) client = SoapClient( wsdl= "http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None" ) if client.addShopSite(auth.user_id, shopid)['result'] == "0": db(db.shop.id == shopid).update(status="enabled") db.commit() else: db.rollback() response.flash = "Ocurrió un error al generar la tienda." session.shopname = form.vars.host except Exception as ex: logger.debug(ex) db.rollback() response.flash = "Ocurrió un error al generar la tienda." session.flash = "En unos minutos recibirá un correo con los datos de su nueva instancia de tienda" redirect(URL('account', 'index')) # if request.vars.priceplan: # plan=db.priceplans(request.vars.priceplan) # if plan.paymode=='free': # redirect(URL('index')) # else: # redirect(URL('setdomain', vars=dict(plan=request.vars.priceplan, shop=shopid))) # else: # redirect(URL('plans')) elif form.errors: response.flash = 'Revise los campos erróneos' else: session.flash = "Ńo puede crear más tiendas. Contrate alguno de los planes de pago" return dict(form=form, domainshops=countsdomainshops)
def InfoProducto(): ID = request.vars.ID client = SoapClient(wsdl="http://localhost:8000/ServiciosSOAP/Servicios/call/soap?WSDL") result = client.InformacionProducto(ID) return str(result['Producto'])
def createmanualshop(): if auth.has_membership('superadministradores') or auth.has_membership( 'administradores'): from shops import Shop from gluon.contrib.pysimplesoap.client import SoapClient import time Shop(db) if request.args(0): firstname = Field( 'first_name', 'string', length=128, notnull=True, requires=IS_NOT_EMPTY( error_message= 'Para configurar en la aplicación del Host el nombre del administrador' )) lastname = Field( 'last_name', 'string', length=128, notnull=True, requires=IS_NOT_EMPTY( error_message= 'Para configurar en la aplicación del Host el nombre del administrador' )) applicationtitle = Field( 'name', 'string', length=80, notnull=True, unique=True, requires=[ IS_NOT_EMPTY(error_message='Nombre de la web o tienda'), IS_NOT_IN_DB( db, 'shop.name', error_message="Este nombre ya está siendo usado") ]) hostname = Field( 'host', 'string', length=45, notnull=True, unique=True, requires=[ IS_MATCH( '^\w+$', 'Sólo letras y números, ni espacios ni caracteres especiales' ), IS_NOT_EMPTY( error_message= 'Más adelante podrás poner tu propio dominio, pero ahora es importante este dato' ), IS_NOT_IN_DB( db, 'shop.host', error_message="Este nombre ya está siendo usado") ]) form = SQLFORM.factory(firstname, lastname, applicationtitle, hostname, submit_button='Crear Tienda') if form.validate(keepvalues=True): try: #almacena los datos dbdata = "%s" % str(time.time()).replace('.', '') shopid = db.shop.insert( user=request.args(0), host=form.vars.host, db_name="gex%s" % dbdata, db_user="******" % dbdata, name=form.vars.name, email=auth.user.email, first_name=form.vars.first_name, last_name=form.vars.last_name, country='es', language='es', ) user = db.auth_user(request.args(0)) if not user.first_name or not user.last_name: user.update_record(first_name=form.vars.first_name, last_name=form.vars.last_name) client = SoapClient( wsdl= "http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None" ) if client.addShopSite(request.args(0), shopid)['result'] == "0": db(db.shop.id == shopid).update(status="enabled") db.commit() else: db.rollback() response.flash = "Ocurrió un error al generar la tienda." except Exception as ex: logger.debug(ex) db.rollback() response.flash = "Ocurrió un error al generar la tienda." elif form.errors: response.flash = 'Revise los campos erróneos' return dict(form=form) else: redirect(URL(request.application, 'administrator', 'users')) else: redirect(URL(request.application, 'default', 'user/login'))
def ConsultarProductos(): client = SoapClient(wsdl="http://localhost:8000/ServiciosSOAP/Servicios/call/soap?WSDL") result = client.ConsultaProductos() return str(result['Productos'])
def ConsultarPedidos(): dni = request.vars.dni client = SoapClient( wsdl="http://localhost:8000/ServiciosSOAP/Servicios/call/soap?WSDL") result = client.ConsultarPedidos(dni) return str(result['Pedidos'])
def check_student(check_carnet): svp=db(db.validate_student).select().first() if svp is not None: try: #CONSUME THE WEBSERVICE from gluon.contrib.pysimplesoap.client import SoapClient from gluon.contrib.pysimplesoap.client import SimpleXMLElement client = SoapClient( location = svp.supplier, action = svp.supplier+"/"+svp.action_service, namespace = svp.supplier, soap_ns=svp.type_service, trace = True, ns = False) import cpfecys year = cpfecys.current_year_period() sent="<"+svp.send+">" for svpf in db(db.validate_student_parameters).select(): sent +="<"+svpf.parameter_name_validate+">"+svpf.parameter_value_validate+"</"+svpf.parameter_name_validate+">" sent += "<CARNET>"+str(check_carnet)+"</CARNET><CICLO>"+str(year.yearp)+"</CICLO></"+svp.send+">" back = client.call(svp.action_service,xmlDatos=sent) #PREPARE FOR RETURNED XML WEB SERVICE xml = back.as_xml() xml=xml.replace('<','<') xml=xml.replace('>','>') inicio = xml.find("<"+svp.receive+">") final = xml.find("</"+svp.receive+">") xml = xml[inicio:(final+17)] import xml.etree.ElementTree as ET root = ET.fromstring(xml) xml = SimpleXMLElement(xml) #VARIABLE TO CHECK THE CORRECT FUNCTIONING CARNET = xml.CARNET NOMBRES = xml.NOMBRES APELLIDOS= xml.APELLIDOS CORREO = xml.CORREO #Unicode Nombres try: str(NOMBRES) except: apellidos_var = unicode(NOMBRES).split(' ') appellidos_return = None for apellido in apellidos_var: try: if appellidos_return is None: appellidos_return = str(apellido) else: appellidos_return = appellidos_return + " " + str(apellido) except: try: temp = unicode(apellido).encode('utf-8').replace('á','á').replace('é','é').replace('Ã','í').replace('ó','ó').replace('ú','ú').replace('ñ','ñ').replace('Ã','Á').replace('É','É').replace('Ã','Í').replace('Ó','Ó').replace('Ú','Ú').replace('Ñ','Ñ').replace('ü‘','ü') except: None apellido = temp if appellidos_return is None: appellidos_return = str(apellido) else: appellidos_return = appellidos_return + " " + str(apellido) NOMBRES = appellidos_return #Unicode APELLIDOS try: str(APELLIDOS) except: apellidos_var = unicode(APELLIDOS).split(' ') appellidos_return = None for apellido in apellidos_var: try: if appellidos_return is None: appellidos_return = str(apellido) else: appellidos_return = appellidos_return + " " + str(apellido) except: try: temp = unicode(apellido).encode('utf-8').replace('á','á').replace('é','é').replace('Ã','í').replace('ó','ó').replace('ú','ú').replace('ñ','ñ').replace('Ã','Á').replace('É','É').replace('Ã','Í').replace('Ó','Ó').replace('Ú','Ú').replace('Ñ','Ñ').replace('ü‘','ü') except: None apellido = temp if appellidos_return is None: appellidos_return = str(apellido) else: appellidos_return = appellidos_return + " " + str(apellido) APELLIDOS = appellidos_return if (CARNET is None or CARNET=='') and (NOMBRES is None or NOMBRES=='') and (APELLIDOS is None or APELLIDOS=='') and (CORREO is None or CORREO==''): return dict(flag=False,error=False,message=T('The record was removed because the user is not registered to the academic cycle')) else: isStuden=False for c in root.findall('CARRERA'): if c.find('UNIDAD').text=="08" and c.find('EXTENSION').text=="00" and (c.find('CARRERA').text=="05" or c.find('CARRERA').text=="09" or c.find('CARRERA').text=="07"): isStuden=True if isStuden==False: return dict(flag=False,error=False,message=T('The record was removed because students not enrolled in career allowed to use the system')) else: return dict(flag=True, carnet=int(str(CARNET)), nombres=(NOMBRES), apellidos=(APELLIDOS), correo=str(CORREO),error=False) except: return dict(flag=False,error=True,message=T('Error with web service validation')) else: return dict(flag=False,error=True,message=T('Error with web service validation'))
def managecontract(self, contract): # Atención, esta función es altamente complicada porque se concentran casi todos los objetos, situaciones y operaciones del sistema. # Dolor de cabeza que te cagas llena de condiciones. De todo menos KISS. ALGUNA VEZ SIMPLIFICARE SEMEJANTE MIERDA! from shops import PricePlan, Shop from invoices import CreditAccount, AccountingEntry from adminsettings import Adminsettings from dateutil.relativedelta import relativedelta from gluon.contrib.pysimplesoap.client import SoapClient db=self.db CreditAccount(db), Shop(db), Adminsettings(db) accounting=AccountingEntry(db) adm=db.adminsettings(1) logger.debug(contract) #comprueba si active if contract.contractedproducts.active: total=((contract.products.price * adm.tax)/100) + contract.products.price credit=0 c=db(db.creditaccounts.user==contract.contractedproducts.user).select().first() if c!=None: credit=c.balance try: now=datetime.datetime.now() if contract.contractedproducts.period=='hours': #no usado por ahora inc=datetime.timedelta(hours=contract.contractedproducts.quantity) elif contract.contractedproducts.period=='days': #no usado por ahora inc=datetime.timedelta(days=contract.contractedproducts.quantity) elif contract.contractedproducts.period=='week': #no usado por ahora inc=datetime.timedelta(weeks=contract.contractedproducts.quantity) elif contract.contractedproducts.period=='month': inc=relativedelta(months=contract.contractedproducts.quantity) horizon_date=15 #15 días elif contract.contractedproducts.period=='year': inc=relativedelta(years=contract.contractedproducts.quantity) horizon_date=30*11 #días. No tengo en cuenta febreros ni bisiestos porque es sólo para hacer algo en 11 meses aprox. else: inc=datetime.timedelta(hours=0) #si autorenove, if contract.contractedproducts.autorenove: #si expiration is None: if contract.contractedproducts.expiration==None: # cambiar status y plan del shop si contract.order.status=="Pagado" if contract.orders.status=='Pagado': #comprueba si saldo if credit>=total: #activar servicios if contract.contractedproducts.automatics_action: client = SoapClient(wsdl="http://*****:*****@gextiendas.es">[email protected]</a> indicándonos su cuenta de usuario (email con el que accede al sistema).</p> <p>Si lo desea puede realizar el pago mediante paypal o cambiar la forma de pago siguiendo este enlace:</p> <p><a href="%(url)s">%(url)s</a></p> <p>El equipo de GEXtiendas.</p> """ % { "ordered_at": contract.orders.ordered_at.strftime("%d-%m-%Y %H:%M"), "name": contract.contractedproducts.user.first_name, "date": contract.contractedproducts.expiration, "product": contract.products.name, "shop_hostname":contract.contractedproducts.shop.host, "shop_name":contract.contractedproducts.shop.name, "url": urlpayment, } logger.debug("LLEGO16") subject="[GEXtiendas] seguimiento de servicios" plaintext=""" www.gestionexperta.com/www.gextiendas.es\n \n \n \t\t\t\t Fuengirola (Málaga), a %(ordered_at)s \n Estimado %(name)s, el próximo %(date)s caduca el servicio contratado:\n\n %(product)s para su tienda %(shop_name)s (%(shop_hostname)s)\n\n pero no tenemos constancia de su transferencia bancaria. Si cree que es un error, puede enviarnos por correo electrónico el justificante del banco por fax al 912692914 o por correo electrónico a <a href="mailto:[email protected]">[email protected]</a> indicándonos su cuenta de usuario (email con el que accede al sistema).\n Si lo desea puede realizar el pago mediante paypal o cambiar la forma de pago siguiendo este enlace:\n\n %(url)s \n\n\n El equipo de gextiendas """ % { "ordered_at": contract.orders.ordered_at.strftime("%d-%m-%Y %H:%M"), "name": contract.contractedproducts.user.first_name, "date": contract.contractedproducts.expiration, "product": contract.products.name, "shop_hostname":contract.contractedproducts.shop.host, "shop_name":contract.contractedproducts.shop.name, "url": urlpayment, } logger.debug("LLEGO17") self.__expirationwarningmail(contract.contractedproducts.user, html, subject, plaintext) logger.debug("LLEGO18") logger.debug("LLEGO19") logger.debug("Transferencia Pendiente pago, no ha expirado, managed==True y pedido tiene más de horizon días") # managed==False y status=="Pagado" elif (contract.contractedproducts.managed==False) and (contract.orders.status=="Pagado"): logger.debug("LLEGO20") #comprobar que realmente hay saldo, if credit>=total: logger.debug("LLEGO21") # actualizar fechas de renove y expiration # actualizar managed=True db(db.contractedproducts.id==contract.contractedproducts.id).update(renove=now, expiration= contract.contractedproducts.expiration + inc, managed=True) #quitar saldo logger.debug("LLEGO22") if contract.contractedproducts.credit_annotation: accounting.annotation(contract.contractedproducts.orderlist, db.orders(contract.orders.id), positive=False) logger.debug("LLEGO23") logger.debug("Transferencia Pagada no ha expirado, managed==False y pedido tiene más de horizon días") logger.debug("LLEGO24") db.commit() #si expirado margen de 2 día, desactivar servicios elif contract.contractedproducts.expiration < (datetime.datetime.now() + datetime.timedelta(days=2)): logger.debug("LLEGO25") if contract.contractedproducts.automatics_action: logger.debug("LLEGO26") client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None") logger.debug("LLEGO27") if client.disableDomainShop(contract.contractedproducts.user, contract.contractedproducts.shop)['result']=="0": logger.debug("LLEGO28") db(db.shop.id==contract.contractedproducts.shop).update(status='enabled', priceplan=db(db.priceplans.paymode=="free").select().first()["id"]) logger.debug("LLEGO29") else: raise Exception("Imposible deshabilitar dominio userid: %s shopid: %s priceplan:%s" % (contract.contractedproducts.user, contract.contractedproducts.shop, db(db.priceplans.paymode=="free").select().first()["id"])) else: db(db.shop.id==contract.contractedproducts.shop).update(status='enabled', priceplan=db(db.priceplans.paymode=="free").select().first()["id"]) logger.debug("LLEGO30") db.commit() #si expirado margen de 7 día, desactivar servicios y borrar contrato elif contract.contractedproducts.expiration< (datetime.datetime.now() + datetime.timedelta(days=7)): if contract.contractedproducts.automatics_action: client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None") if client.disableDomainShop(contract.contractedproducts.user, contract.contractedproducts.shop)['result']=="0": db(db.shop.id==contract.contractedproducts.shop).update(status='enabled', priceplan=db(db.priceplans.paymode=="free").select().first()["id"]) logger.debug("LLEGO31") else: raise Exception("Imposible deshabilitar dominio userid: %s shopid: %s priceplan:%s" % (contract.contractedproducts.user, contract.contractedproducts.shop, db(db.priceplans.paymode=="free").select().first()["id"])) else: db(db.shop.id==contract.contractedproducts.shop).update(status='enabled', priceplan=db(db.priceplans.paymode=="free").select().first()["id"]) logger.debug("LLEGO32") db.commit(db) logger.debug("LLEGO34") # Si es paypal no hacer nada, que lo haga IPN #db(db.contractedproducts.id==contract.contractedproducts.id).update(renove=now, expiration= contract.contractedproducts.expiration+inc) #update fecha de renove a now y suma tiempo a expiration #si no autorenove, dos casos, que sean ifselling o comprobar que el producto no sea de suscripción, si no, pasados 7 días borrar contrato, cambiar a plan gratuito y desactivar servicios si no lo estuviesen ya. else: if contract.products.plan=='ifselling' or contract.products.suscription==False: logger.debug("LLEGO33") if contract.contractedproducts.start==None: logger.debug("LLEGO34") # cambiar status y plan del shop si contract.order.status=="Pagado" if contract.orders.status=='Pagado': logger.debug("LLEGO35") #comprueba si saldo if credit>=total: #activar servicios logger.debug("LLEGO36") if contract.contractedproducts.automatics_action: logger.debug("LLEGO37") client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None") logger.debug("LLEGO38") if client.enableDomainShop(contract.contractedproducts.user, contract.contractedproducts.shop)['result']=="0": logger.debug("LLEGO39") db(db.shop.id==contract.contractedproducts.shop).update(status='enabled', priceplan=contract.priceplans.id) logger.debug("LLEGO40") # cambiar de contractedproducts fecha de start y expiration db(db.contractedproducts.id==contract.contractedproducts.id).update(start=now, expiration= now+inc) logger.debug("LLEGO41") #quitar saldo if contract.contractedproducts.credit_annotation: logger.debug("LLEGO42") accounting.annotation(contract.contractedproducts.orderlist, db.orders(contract.orders.id), positive=False) logger.debug("LLEGO43") db.commit() logger.debug("LLEGO44") else: raise Exception("Imposible habilitar dominio userid: %s shopid: %s status:%s priceplan:%s" % (contract.contractedproducts.user, contract.contractedproducts.shop, 'enabled', contract.priceplans.id)) else: logger.debug("LLEGO45") db(db.shop.id==contract.contractedproducts.shop).update(status='enabled', priceplan=contract.priceplans.id) logger.debug("LLEGO46") # cambiar de contractedproducts fecha de start y expiration db(db.contractedproducts.id==contract.contractedproducts.id).update(start=now, expiration= now+inc) logger.debug("LLEGO47") #quitar saldo if contract.contractedproducts.credit_annotation: logger.debug("LLEGO48") accounting.annotation(contract.contractedproducts.orderlist, db.orders(contract.orders.id), positive=False) logger.debug("LLEGO49") db.commit() logger.debug("LLEGO50") #pasados 7 días borrar contrato, cambiar a plan gratuito y desactivar servicios si no lo estuviesen ya. elif contract.contractedproducts.expiration< (datetime.datetime.now() + datetime.timedelta(days=7)): logger.debug("LLEGO51") client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None") logger.debug("LLEGO52") if client.disableDomainShop(contract.contractedproducts.user, contract.contractedproducts.shop)['result']=="0": logger.debug("LLEGO53") db(db.shop.id==contract.contractedproducts.shop).update(status='enabled', priceplan=db(db.priceplans.paymode=="free").select().first()["id"]) logger.debug("LLEGO54") db.commit() else: raise Exception("Imposible habilitar dominio userid: %s shopid: %s status:%s priceplan:%s" % (contract.contractedproducts.user, contract.contractedproducts.shop, 'enabled', db(db.priceplans.paymode=="free").select().first()["id"])) except Exception as ex: db.rollback() logger.debug("Error manage_plans_and_status %s" % ex)
def index(): from shops import Shop from gluon.contrib.pysimplesoap.client import SoapClient import time Shop(db) shops = db((db.shop.id > 0) & (db.shop.user == auth.user_id)).select() form = None if not shops: from queuemail import Queuemail Queuemail(db) firstname = Field( 'first_name', 'string', length=128, notnull=True, requires=IS_NOT_EMPTY( error_message= 'Para dirigirnos a usted y para los clientes en su tienda')) lastname = Field( 'last_name', 'string', length=128, notnull=True, requires=IS_NOT_EMPTY( error_message= 'Para dirigirnos a usted y para los clientes en su tienda')) shopname = Field( 'name', 'string', length=80, notnull=True, unique=True, requires=[ IS_NOT_EMPTY( error_message='No olvide decirnos el nombre de su tienda'), IS_NOT_IN_DB(db, 'shop.name', error_message="Este nombre ya está siendo usado") ]) hostname = Field( 'host', 'string', length=45, notnull=True, unique=True, requires=[ IS_MATCH( '^\w+$', 'Sólo letras y números, ni espacios ni caracteres especiales' ), IS_NOT_EMPTY( error_message= 'Más adelante podrás poner tu propio dominio, pero ahora es importante este dato' ), IS_NOT_IN_DB(db, 'shop.host', error_message="Este nombre ya está siendo usado") ]) form = SQLFORM.factory(firstname, lastname, shopname, hostname, submit_button='Crear Tienda') if form.validate(): try: #almacena los datos dbdata = "%s" % str(time.time()).replace('.', '') shopid = db.shop.insert( user=auth.user_id, host=form.vars.host, db_name="gex%s" % dbdata, db_user="******" % dbdata, name=form.vars.name, email=auth.user.email, first_name=form.vars.first_name, last_name=form.vars.last_name, country='es', language='es', ) db(db.auth_user.id == auth.user).update( first_name=form.vars.first_name, last_name=form.vars.last_name) client = SoapClient( wsdl= "http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None" ) if client.addShopSite(auth.user_id, shopid)['result'] == "0": db(db.shop.id == shopid).update(status="enabled") db.commit() else: db.rollback() session.flash = "Ocurrió un error al generar la tienda." redirect(URL('index')) except Exception as ex: logger.debug(ex) db.rollback() session.flash = "Ocurrió un error al generar la tienda." redirect(URL('index')) session.flash = "En unos minutos recibirá un correo con los datos de su nueva tienda" redirect(URL('index')) elif form.errors: response.flash = 'Revise los campos erróneos' return dict(shops=shops, form=form)
def test(): from pysimplesoap.client import SoapClient WSDL = "https://www.sistemasagiles.com.ar/simulador/wsfev1/call/soap?WSDL=None" client = SoapClient(wsdl=WSDL) try: ret = client.FECAESolicitar( Auth={ 'Token': 'token', 'Sign': 'sign', 'Cuit': '20267565393' }, FeCAEReq={ 'FeCabReq': { 'CantReg': 1, 'PtoVta': 1, 'CbteTipo': 10 }, 'FeDetReq': [{ 'FECAEDetRequest': { 'Concepto': 1, 'DocTipo': 80, 'DocNro': 20111111119, 'CbteDesde': 1, 'CbteHasta': 2, 'CbteFch': '20101006', 'ImpTotal': '1000.10', 'ImpTotConc': "10.00", 'ImpNeto': "100.00", 'ImpOpEx': "0.00", 'ImpTrib': "1.00", 'ImpIVA': "21.00", 'FchServDesde': '20101101', 'FchServHasta': '20101130', 'FchVtoPago': '20101014', 'MonId': 'DOL', 'MonCotiz': '3.985', 'CbtesAsoc': [{ 'CbteAsoc': { 'Tipo': 19, 'PtoVta': 2, 'Nro': 1234 } }], 'Tributos': [{ 'Tributo': { 'Id': 0, 'Desc': 'Impuesto Municipal Matanza', 'BaseImp': 150, 'Alic': 5.2, 'Importe': 5.8, } }], 'Iva': [{ 'AlicIva': { 'Id': 5, 'BaseImp': 100, 'Importe': 21, } }], } }] }) except Exception, e: #ret = client.xml_response ret = repr(e) # # e.faultstring