Exemplo n.º 1
0
def orders():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from shops import Shop, ContractedProduct
		from invoices import Order, Orderlist
		from pagination import Pagination
		Order(db), Orderlist(db), Shop(db), ContractedProduct(db)
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		records=db(db.orders.status!="CreandoAdmin").count()
		items_per_page=settings.orderlistitems
		pag=Pagination(records, items_per_page)
		#orders = db(db.orders.status!="CreandoAdmin").select(db.orders.ALL, orderby=~db.orders.id, limitby=pag.limitby())

		orders=db(db.orders.status!="CreandoAdmin").select(db.orders.ALL, 
													
													db.shop.host,
													left=[	db.orderlist.on(db.orderlist.g_order==db.orders.id),
															db.contractedproducts.on(db.contractedproducts.orderlist==db.orderlist.id),
															db.shop.on(db.shop.id==db.contractedproducts.shop)],
													orderby=~db.orders.id,
													groupby=db.orders.id, 
													limitby=pag.limitby())




		return dict(orders=orders, pagination=pag, records=records, items_per_page=items_per_page)

	else:
		redirect(URL(request.application,'default','user/login'))
Exemplo n.º 2
0
def datashop():
    from shops import Shop, DomainShop, ContractedProduct, Product
    from invoices import Order
    Shop(db), DomainShop(db), ContractedProduct(db), Product(db), Order(db)
    #store=db((db.shop.user==auth.user_id) & (db.shop.host==request.vars.host)).select()
    stores = db((db.shop.host == request.vars.host)
                & (db.shop.user == auth.user_id)).select(
                    db.shop.ALL,
                    db.domainshops.ALL,
                    db.priceplans.ALL,
                    left=[
                        db.domainshops.on(db.domainshops.shop == db.shop.id),
                        db.priceplans.on(db.priceplans.id == db.shop.priceplan)
                    ])

    contractedproducts = db(
        (db.contractedproducts.user == auth.user_id)
        & (db.contractedproducts.shop == stores[0].shop) &
        (db.contractedproducts.expiration <= datetime.datetime.now())).select(
            db.contractedproducts.ALL,
            db.products.ALL,
            left=[
                db.products.on(db.products.id == db.contractedproducts.product)
            ])
    return dict(stores=stores,
                host=stores[0].shop.host,
                ip=stores[0].shop.ip,
                contractedproducts=contractedproducts)
Exemplo n.º 3
0
def contractedproducts():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):

		from shops import ContractedProduct, Product, Shop
		from invoices import Order, Orderlist
		from pagination import Pagination
		ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db)
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		records=db(db.contractedproducts.id>0).count()
		items_per_page=settings.orderlistitems
		pag=Pagination(records, items_per_page)
		contractedproducts = db(db.contractedproducts.id>0).select(	db.contractedproducts.ALL,
														db.products.ALL,
														db.shop.ALL,
														db.auth_user.ALL,
														db.fiscals.ALL,
														left=[	db.products.on(db.products.id==db.contractedproducts.product),
																db.shop.on(db.shop.id==db.contractedproducts.shop),
																db.auth_user.on(db.auth_user.id==db.contractedproducts.user),
																db.fiscals.on(db.fiscals.user==db.auth_user.id)],
														orderby=~db.contractedproducts.expiration, limitby=pag.limitby())

		return dict(contractedproducts=contractedproducts, pagination=pag, records=records, items_per_page=items_per_page)

	else:
		redirect(URL(request.application,'default','user/login'))
Exemplo n.º 4
0
def myservices():
    from shops import ContractedProduct, Product, Shop
    from invoices import Order, Orderlist
    from pagination import Pagination
    from adminsettings import Adminsettings
    Adminsettings(db)
    ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db)
    settings = db(db.adminsettings.id > 0).select(db.adminsettings.ALL).first()
    records = db((db.contractedproducts.id > 0)
                 & (db.contractedproducts.user == auth.user_id)).count()
    items_per_page = settings.orderlistitems
    pag = Pagination(records, items_per_page)
    contractedproducts = db((db.contractedproducts.id > 0) & (
        db.contractedproducts.user == auth.user_id)).select(
            db.contractedproducts.ALL,
            db.products.ALL,
            db.shop.ALL,
            db.auth_user.ALL,
            db.fiscals.ALL,
            left=[
                db.products.on(
                    db.products.id == db.contractedproducts.product),
                db.shop.on(db.shop.id == db.contractedproducts.shop),
                db.auth_user.on(db.auth_user.id == db.contractedproducts.user),
                db.fiscals.on(db.fiscals.user == db.auth_user.id)
            ],
            orderby=~db.contractedproducts.expiration,
            limitby=pag.limitby())

    return dict(contractedproducts=contractedproducts,
                pagination=pag,
                records=records,
                items_per_page=items_per_page)
Exemplo n.º 5
0
	def __init__(self, db):
		from invoices import Order, Invoice
		self.db=db
		Product(db), Order(db), Invoice(db), Shop(db)
		try:
			self.define_tables()
		except:
			pass
Exemplo n.º 6
0
	def __init__(self, db):
		self.db=db
		PricePlan(db)
		Shop(db)
		try:

			self.define_tables()
		except:
			pass
Exemplo n.º 7
0
def enabledomain():
    from shops import Shop, DomainShop, PricePlan, ContractedProduct, Product
    Shop(db), DomainShop(db), PricePlan(db), ContractedProduct(db), Product(db)

    shop = db((db.shop.host == request.vars.host)
              & (db.shop.user == auth.user_id)).select().first()

    if shop:
        if shop.priceplan.paymode == 'free':
            #hay que pasar por caja, pero antes comprobar si hay algún pedido en planes distintos a free para esta tienda pendiente de ser aprobado
            pending = db((db.contractedproducts.shop == shop.id)
                         & (db.contractedproducts.user == auth.user_id)
                         & (db.contractedproducts.start == None)
                         & ((db.priceplans.paymode != None)
                            & (db.priceplans.paymode != 'free'))).select(
                                db.contractedproducts.id,
                                join=[
                                    db.products.on(db.products.id == db.
                                                   contractedproducts.product),
                                    db.priceplans.on(
                                        db.priceplans.id == db.products.plan)
                                ]).first()
            logger.debug(
                db((db.contractedproducts.shop == shop.id)
                   & (db.contractedproducts.user == auth.user_id)
                   & (db.contractedproducts.start == None)
                   & ((db.priceplans.paymode != None)
                      & (db.priceplans.paymode != 'free')))._select(
                          db.contractedproducts.id,
                          join=[
                              db.products.on(db.products.id ==
                                             db.contractedproducts.product),
                              db.priceplans.on(
                                  db.priceplans.id == db.products.plan)
                          ]))

            if pending == None:
                if request.vars.host:
                    redirect(
                        URL(request.application,
                            'plans',
                            'index',
                            vars=dict(host=request.vars.host)))
            else:
                session.flash = "Este pedido para cambiar de plan, estaba pendiente de confirmación pago"
                redirect(URL('payment', 'index'))

        else:
            #este dominio está en shop con un priceplan de pago, así que se puede llamar al api de internalgexcommerce para configurar el apache
            logger.debug("de pagoooo")
    else:
        session.flash = "No podemos encontrar la tienda %s" % request.vars.host
        redirect(URL('index'))
Exemplo n.º 8
0
def index():
    from shops import Shop, DomainShop, PricePlan
    Shop(db), DomainShop(db), PricePlan(db)

    shop = db((db.shop.host == request.vars.host)
              & (db.shop.user == auth.user_id)).select().first()

    if shop:

        return dict(host=shop.host)
    else:
        session.flash = "No podemos encontrar la tienda %s" % request.vars.host
        redirect(URL('index'))
Exemplo n.º 9
0
def createcontracts():
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        from shops import ContractedProduct, Product, Shop
        from invoices import Order, Orderlist
        Product(db), ContractedProduct(db), Order(db), Orderlist(db), Shop(db)
        if not request.vars.invoice == 'None' and not request.vars.invoice == None:
            g_order = db(db.orders.invoice ==
                         request.vars.invoice).select().first()["id"]
        else:
            g_order = request.vars.order

        if not request.vars.shop:
            shop = db(db.shop.user == request.args(0)).select()
        else:
            shopid = request.vars.shop

        if not shop:
            redirect(
                URL('contracts',
                    'createmanualshop',
                    args=request.args(0),
                    vars=dict(invoice=request.vars.invoice,
                              order=request.vars.order)))
        else:
            shopid = shop[0].id

        contractedproducts = db(
            (db.orderlist.g_order == g_order)
            & (db.orders.user == request.args(0))
            & ((db.contractedproducts.shop == shopid)
               | (db.contractedproducts.shop == None))).select(
                   db.orders.ALL,
                   db.orderlist.ALL,
                   db.contractedproducts.ALL,
                   db.products.ALL,
                   left=[
                       db.orderlist.on(db.orders.id == db.orderlist.g_order),
                       db.products.on(db.products.id == db.orderlist.product),
                       db.contractedproducts.on(
                           db.contractedproducts.product == db.products.id)
                   ],
                   groupby=db.orderlist.id)

        session.usercontract = request.args(0)
        return dict(contractedproducts=contractedproducts,
                    shop=shop,
                    shopid=shopid)
    else:
        redirect(URL(request.application, 'default', 'user/login'))
Exemplo n.º 10
0
def deletedomain():
    from shops import Shop, DomainShop, PricePlan
    Shop(db), DomainShop(db), PricePlan(db)
    shophost = request.vars.host
    shop = db((db.shop.host == request.vars.host)
              & (db.shop.user == auth.user_id)).select().first()
    redirection = False
    ip = shop.ip
    if shop:
        try:
            db((db.domainshops.shop == shop.id)
               & (db.domainshops.host == request.vars.hostname)
               & (db.domainshops.domain == request.vars.domain)).delete()

            session.flash = "Dominio borrado con éxito"
            return "ok"
        except Exception as ex:
            return ex
    else:
        session.flash = "No podemos encontrar la tienda %s" % request.vars.host
        redirect(URL('index'))
Exemplo n.º 11
0
def modifydomain():
    from shops import Shop, DomainShop, PricePlan
    Shop(db), DomainShop(db), PricePlan(db)
    shophost = request.vars.host
    shop = db((db.shop.host == request.vars.host)
              & (db.shop.user == auth.user_id)).select().first()
    redirection = False
    ip = shop.ip
    if shop:
        try:
            db((db.domainshops.shop == shop.id)
               & (db.domainshops.host == request.vars.o_hostname)
               & (db.domainshops.domain == request.vars.o_domain)).update(
                   domain=request.vars.domain,
                   host=request.vars.hostname,
                   active='modifying')
            db.commit()
            session.flash = "Modificación realizada con éxito"
            return "ok"
        except Exception as ex:
            return ex
    else:
        session.flash = "No podemos encontrar la tienda %s" % request.vars.host
        redirect(URL('index'))
Exemplo n.º 12
0
def postcontracts():
    import simplejson
    from dateutil.relativedelta import relativedelta
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        from shops import ContractedProduct, Product, Shop
        from invoices import Order, Orderlist, CreditAccount, AccountingEntry
        Order(db), Orderlist(db), Product(db), ContractedProduct(db), Shop(db)
        accounting = AccountingEntry(db)
        logger.debug(request.post_vars)
        data = simplejson.loads(request.post_vars.datacontracts)
        shopid = request.post_vars.shopid
        try:
            for d in data:
                #NO SE PUEDE HACER EL INSERT DIRECTAMENTE. HAY QUE VER SI EL SHOP YA TIENE CONTRATADO EL PRODUCTO. SI NO TIENE se hace un INSERT, si no, no hace nada.
                #Sólo se va a poder contratar una unidad y la recursividad y duración de la periodicidad  harán el resto.
                orderlist = db(db.orderlist.id == int(d['orderlist'])).select(
                    db.orderlist.ALL,
                    db.products.ALL,
                    db.orders.ALL,
                    join=[
                        db.products.on(db.products.id == db.orderlist.product),
                        db.orders.on(db.orders.id == db.orderlist.g_order)
                    ]).first()

                contracted = db(
                    (db.contractedproducts.shop == shopid)
                    & (db.contractedproducts.user == session.usercontract)
                    & (db.contractedproducts.product ==
                       orderlist.orderlist.product)).select().first()

                if not contracted:
                    db.contractedproducts.insert(
                        user=session.usercontract,
                        product=orderlist.orderlist.product,
                        period=orderlist.products.
                        min_period,  #optimizar para evitar más consultas
                        autorenove=d['autorenove'],
                        shop=shopid,
                        orderlist=orderlist.orderlist.id,
                        paymentmethod=orderlist.orders.payment_method,
                        automatics_action=d['automatics_action'],
                        notifications=d['notifications'],
                        credit_annotation=d['credit_annotation'],
                        invoice=request.vars.invoice)

                else:
                    contracted.update_record(
                        autorenove=d['autorenove'],
                        automatics_action=d['automatics_action'],
                        notifications=d['notifications'],
                        credit_annotation=d['credit_annotation'],
                    )

                logger.debug("LLegoogoo1")
                #anotar crédito si orders pagado y si credit_annotation==True y si not in accountingentries
                if orderlist.orders.status == "Pagado" and d[
                        'credit_annotation']:
                    if not db((db.accountingentries.orderlist ==
                               orderlist.orderlist.id)
                              & (db.accountingentries.active == True)).select(
                              ).first():
                        logger.debug("LLegoogoo2")
                        if not accounting.annotation(
                                db.orderlist(orderlist.orderlist.id),
                                db.orders(orderlist.orders.id),
                                positive=True):
                            raise Exception(
                                "Ocurrió un error al hacer la anotación en postcontracts"
                            )
                        logger.debug("LLegoogoo3")
                        if contracted:
                            if request.vars.invoice and contracted.invoice:
                                if int(request.vars.invoice) > int(
                                        contracted.invoice):
                                    expiration = contracted.expiration
                                    if contracted.period == 'hours':  #no usado por ahora
                                        inc = datetime.timedelta(
                                            hours=contracted.quantity)
                                    elif contracted.period == 'days':  #no usado por ahora
                                        inc = datetime.timedelta(
                                            days=contracted.quantity)
                                    elif contracted.period == 'week':  #no usado por ahora
                                        inc = datetime.timedelta(
                                            weeks=contracted.quantity)
                                    elif contracted.period == 'month':
                                        inc = relativedelta(
                                            months=contracted.quantity)
                                        horizon_date = 15  #15 días
                                    elif contracted.period == 'year':
                                        inc = relativedelta(
                                            years=contracted.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)
                                    if not accounting.annotation(
                                            db.orderlist(
                                                orderlist.orderlist.id),
                                            db.orders(orderlist.orders.id),
                                            positive=False):
                                        raise Exception(
                                            "Ocurrió un error al hacer la anotación en postcontracts"
                                        )
                                    contracted.update_record(
                                        expiration=expiration + inc,
                                        invoice=request.vars.invoice)

            db.commit()
            session.flash = "Contratos creados correctamente"
        except Exception as ex:
            logger.debug("Se produjo un error en postcontracts %s" % ex)
            db.rollback()
            raise HTTP(500, ex)

        session.usercontract = None
        return "ok"
    else:
        return "no authorized"
Exemplo n.º 13
0
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)
Exemplo n.º 14
0
def setdomain():
    from shops import Shop, DomainShop, PricePlan
    from auxiliartools import IS_NOT_IN_DB_OR_OWNERSHOP
    Shop(db), DomainShop(db), PricePlan(db)

    shophost = request.vars.shop
    shop = db((db.shop.host == request.vars.shop)
              & (db.shop.user == auth.user_id)).select(
                  db.shop.ALL,
                  db.priceplans.ALL,
                  join=[
                      db.priceplans.on(db.priceplans.id == db.shop.priceplan)
                  ]).first()

    redirection = False
    ip = shop.shop.ip
    if shop:
        domain = Field(
            'domain',
            'string',
            length=45,
            notnull=True,
            requires=[
                IS_NOT_EMPTY(error_message='¿olvidaste decirnos el dominio?'),
                IS_NOT_IN_DB_OR_OWNERSHOP(
                    db,
                    shop.shop.id,
                    error_message=
                    "Este dominio ya está siendo usado. Contacta con nosotros si crees que es un error por nuestra parte."
                ),
                IS_URL(error_message="ejemplo de formato: gextiendas.es")
            ])
        host = Field('host',
                     'string',
                     length=45,
                     notnull=False,
                     requires=[IS_MATCH('^\w+$', 'Sólo letras y números')])
        form = SQLFORM.factory(domain,
                               host,
                               submit_button='establecer dominio')
        if form.validate():
            try:
                if ((db((db.domainshops.host == form.vars.host)
                        & (db.domainshops.domain == form.vars.domain.replace(
                            "http://", ""))).select().first() == None)
                        and (form.vars.domain.replace("http://", "") not in [
                            "gextiendas.es", "gextiendas.com",
                            "gestionexperta.com", "gestionexperta.es"
                        ])):
                    if shop.priceplans.paymode == 'ifselling' or shop.priceplans.paymode == 'flatrate':
                        db.domainshops.insert(shop=shop.shop.id,
                                              host=form.vars.host,
                                              domain=form.vars.domain.replace(
                                                  "http://", ""),
                                              active="enabling")
                    elif shop.priceplans.paymode == 'free':
                        db.domainshops.insert(shop=shop.shop.id,
                                              host=form.vars.host,
                                              domain=form.vars.domain.replace(
                                                  "http://", ""),
                                              active="disabled")
                    db.commit()
                else:
                    session.flash = "%s.%s ya está siendo utilizado" % (
                        form.vars.host, form.vars.domain.replace(
                            "http://", ""))
                redirection = True
            except Exception as ex:
                logger.debug("Error en account/setdomain %s" % ex)
                db.rollback()
                response.flash = "Ocurrió un error al establecer el nombre de dominio."
        elif form.errors:
            response.flash = "Ocurrió algún error"
        if redirection:
            redirect(URL('index'))
        return dict(form=form, ip=ip)
    else:
        redirect(URL('index'))
Exemplo n.º 15
0
	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)
Exemplo n.º 16
0
def editcustomer():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		if request.args(0):
			from invoices import Fiscal, Order, Orderlist, Invoice, Budget, AccountingEntry, CreditAccount
			from shops import ContractedProduct, Product, Shop
			from cities import Cities
			from province import Province
			Fiscal(db),	Province(db), Cities(db), ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db), AccountingEntry(db), CreditAccount(db),  Invoice(db), Budget(db)
			
			customer=db(db.auth_user.id==request.args(0)).select(	db.auth_user.id,
																	db.auth_user.first_name,
																	db.auth_user.last_name,
																	db.auth_user.email,
																	db.fiscals.ALL,
																	left=[db.fiscals.on(db.fiscals.user==db.auth_user.id)]).first()
			
			wpoblacion = SQLFORM.widgets.autocomplete(request, db.cities.poblacion, limitby=(0,10), min_length=2)
			wprovincia = SQLFORM.widgets.autocomplete(request, db.province.provincia, limitby=(0,10), min_length=2)


			inc=datetime.timedelta(days=30)
			
			contractedproducts = db((db.contractedproducts.user==request.args(0)) & 
									(	(db.contractedproducts.expiration+inc>=datetime.datetime.now()) | 
										(db.contractedproducts.expiration==None)	)).select(	db.contractedproducts.ALL,
																							db.products.ALL,
																							db.shop.ALL,
																							db.auth_user.ALL,
																							db.fiscals.ALL,
																							left=[	db.products.on(db.products.id==db.contractedproducts.product),
																									db.shop.on(db.shop.id==db.contractedproducts.shop),
																									db.auth_user.on(db.auth_user.id==db.contractedproducts.user),
																									db.fiscals.on(db.fiscals.user==db.auth_user.id)],
																							orderby=~db.contractedproducts.expiration)

			invoices = db( db.invoices.user==request.args(0)).select(db.invoices.ALL,
																	db.orders.id,
																	db.orders.status,
																	left=[  db.orders.on(db.orders.invoice==db.invoices.id)],
																	orderby=~db.invoices.id,
																	groupby=db.orders.id
																	)
			

			budgets = db((db.budgets.user==request.args(0)) & (db.budgets.status!="Creando")).select(db.budgets.ALL, orderby=~db.budgets.id)

			orders= db((db.orders.invoice==None) & (db.orders.user==request.args(0))).select(orderby=~db.orders.id)

			if customer!=None:

				first_name= Field('first_name', 'string', label=XML("<strong>Nombre</strong>"), length=128, notnull=True, default=customer.auth_user.first_name, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				last_name= Field('last_name', 'string', label=XML("<strong>Apellidos</strong>"), length=128, notnull=True, default=customer.auth_user.last_name, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				email=Field('email',  label=XML('<strong>Email</strong>'), length=128,  writable=False, notnull=True, default=customer.auth_user.email, requires=[IS_NOT_EMPTY(), IS_EMAIL(error_message='No puede estar vacío.')])
				tax_identification = Field('tax_identification', 'string', label=XML("<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"),length=45, notnull=True, default=customer.fiscals.tax_identification, requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
				fiscalname=Field('fiscalname', 'string', label=XML("<strong>Nombre empresa</strong>") ,length =128, notnull=False, default=customer.fiscals.fiscalname)
				address=Field('address', 'string', label=XML("<strong>Dirección</strong>"), length =196, notnull=True, default=customer.fiscals.address, requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
				city= Field('city', 'string',   label=XML("<strong>Ciudad/Población</strong>"), length=45, notnull=True, default=customer.fiscals.city, requires=IS_NOT_EMPTY(error_message="no olvide este dato"), widget=wpoblacion)
				province = Field('province', 'string',   label=XML("<strong>Provincia</strong>"), length=45, notnull=True, default=customer.fiscals.province, requires=IS_NOT_EMPTY(error_message="no olvide este dato"), widget=wprovincia)
				country=Field('country', 'string', label=XML("<strong>Pais</strong>"), length =45, notnull=True, default=customer.fiscals.country, requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
				postalcode=Field('postal_code', 'string', label=XML("<strong>Código postal</strong>"), length=10, notnull=False, default=customer.fiscals.postal_code)
				phone=Field('phone', 'string', label=XML("<strong>Teléfono</strong>"), length=20, notnull=False, default=customer.fiscals.phone)

				form = SQLFORM.factory(first_name, last_name, email, tax_identification, fiscalname, address, city, province, country, postalcode, phone, submit_button = 'enviar datos', formstyle='bootstrap3_inline')



				if form.validate(keepvalues=True):

					try:
						db(db.auth_user.id==customer.auth_user.id).update(first_name=form.vars.first_name,
																		  last_name=form.vars.last_name)
						db(db.fiscals.id==customer.fiscals.id).update(tax_identification=form.vars.tax_identification, 
															fiscalname=form.vars.fiscalname,
															address=form.vars.address, 
															city=form.vars.city,
															province=form.vars.province,
															country=form.vars.country, 
															postal_code=form.vars.postal_code,
															phone=form.vars.phone)
						db.commit()
					except Exception, ex:
						logger.debug("No se pudo modificar los datos del usuario/fiscal: %s" % ex)
						db.rollback()
						response.flash = 'Hubo un error: %s' % ex				
					response.flash="Datos enviados correctamente"
				elif form.errors:
					response.flash = 'Hay errores'

				
				form.element('input[name=city]')['_class']='form-control'
				form.element('input[name=province]')['_class']='form-control'


				creditaccount=db(db.creditaccounts.user==customer.auth_user.id).select().first()
				accountingentries=None

				if creditaccount:
					accountingentries = db(	(db.accountingentries.creditaccount==creditaccount.id) &
											(db.accountingentries.active==True) ).select(	db.accountingentries.ALL, 
																							db.orders.ALL,
																							db.invoices.ALL,
																							db.products.name,
																							join=[	db.orderlist.on(db.accountingentries.orderlist==db.orderlist.id),
																									db.products.on(db.products.id==db.orderlist.product),
																									db.orders.on(db.orders.id==db.orderlist.g_order),
																									db.invoices.on(db.invoices.id==db.orders.invoice)],
																							orderby=~db.accountingentries.id)




				return dict(form=form, contractedproducts=contractedproducts, invoices=invoices, budgets=budgets, orders=orders, userid=customer.auth_user.id, accountingentries=accountingentries, creditaccount=creditaccount)

			else:
				redirect(URL('administrator','newcustomer'))
		else:
			redirect(URL('administrator','users'))
Exemplo n.º 17
0
def order_approving():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from shops import ContractedProduct, Product, Shop
		from invoices import Order, Orderlist, Invoice, CreditAccount, AccountingEntry
		from queuemail import Queuemail
		from gluon.contrib.pysimplesoap.client import SoapClient
		queue=Queuemail(db)
		ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db),  AccountingEntry(db)
		order=db.orders(request.vars.order)
		
		# order=db.orders(orderid)
		try:
			if order:
				#crear factura
				invoice=Invoice(db)
				invoiceid=invoice.makeinvoice(order.id) #aquí se hace además la anotación positiva en creditaccount
				if invoiceid!=None:
					# notificar recepción del pago
					subject="[gextiendas] Factura Nº %s" % db.invoices(invoiceid).invoice_number
					queuedata=[]

					urlinvoice= '%(scheme)s://%(host)s%(url)s' % {'scheme':request.env.wsgi_url_scheme,'host':request.env.http_host, 'url':URL('payment','code',args=[order.payment_code.code])}
					data={	"now": datetime.datetime.now().strftime("%d-%m-%Y %H:%M"),
									"name": order.user.first_name, 
									"code": order.payment_code.code,
									"url": urlinvoice,
						}
					plaintext="""
							\t\t\t\t Fuengirola (Málaga), a %(now)s \n
							Estimado %(name)s, hemos recibido un pago mediante transferencia correspondiente a la referencia de pago: %(code)s \n
							Puede descargarse la factura siguiendo este enlace:\n
							%(url)s \n
							El equipo de GEXtiendas.\n

								""" % data	
					html="""
							<p>Fuengirola (Málaga), a %(now)s</p>
							<p>Estimado %(name)s, hemos recibido un pago mediante transferencia correspondiente a la referencia de pago: %(code)s</p>
							<p>Puede descargarse la factura siguiendo este enlace:</p>
							<p><a href='%(url)s'>%(url)s</a></p>
							<p>El equipo de GEXtiendas.</p>
						""" % data


					queuedata.append({	'to': '%s'%order.user.email,
										'subject':subject,
										'message':plaintext,
										'html':XML(html),
										'template':'communications/paymentreceived_template.html',
										'title':'Pago recibido: %s' % subject,
										'unsubscribe':''
									})
					queue.queuemessage(queuedata)

					#
					# client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None")
					# logger.debug(client.enableDomainShop())
					# buscar si hay dominios que estén esperando ser habilitados en una tienda del productocontratado en la lista de ese pedido
					# activar dominio
					# anotar accountinentry negativo
					# actualizar crédito

					session.flash="Operación realizada con éxito"
				else:
					session.flash="Hubo un error y no se pudo aprobar el pedido"
			else:
				session.flash="Hubo un error. No se pudo aprobar el pedido"

		except Exception as ex:

			logger.debug(ex)
			session.flash="Ocurrió un error %s " % ex

		redirect(URL('administrator','orders'))
	else:

		redirect(URL(request.application,'default','user/login'))
Exemplo n.º 18
0
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'))
Exemplo n.º 19
0
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)
Exemplo n.º 20
0
def payment():
    from invoices import Order, Orderlist
    from shops import Product, Shop, DomainShop, ContractedProduct
    from adminsettings import Adminsettings
    from auxiliartools import AuxiliarTools
    Adminsettings(db)
    settings = db(db.adminsettings.id > 0).select(db.adminsettings.ALL).first()
    Shop(db), Order(db), Orderlist(db), Product(db), DomainShop(
        db), ContractedProduct(db)
    external = AuxiliarTools(db)

    host = request.vars.host
    plan = request.vars.plan
    cert = request.vars.cert
    if host and plan and cert:  #hay que comprobar que viene por request un plan asignado a una tienda con el dato del cert
        try:
            db((db.orders.status == 'Creando')
               & (db.orders.user == auth.user_id)).delete(
               )  #sólo puede haber un pedido en estado de creación.
            plan = db(db.priceplans.id == request.vars.plan).select().first()
            shop = db((db.shop.host == request.vars.host)
                      & (db.shop.user == auth.user_id)).select().first()
            if shop and plan:  #comprobar que existe y es suyo (siempre por seguridad)
                profileplans = db(db.profileplans.priceplan == plan).select()
                total = float(0)
                for profileplan in profileplans:
                    if profileplan.active:
                        product = db(db.products.id ==
                                     profileplan.product).select().first()

                        if product.name.find("SSL") != -1 and cert == "false":
                            continue
                        total = total + float(product.price)

                orderid = db.orders.insert(
                    user=auth.user_id,
                    total=total,
                    totaltax="%.2f" % float(
                        ((total * float(settings.tax)) / 100)),
                    status="Creando",
                    payment_code=db.paymentcodes.insert(
                        code=external.generatecode()),
                    payment_method=None)
                for profileplan in profileplans:
                    if profileplan.active:
                        product = db(db.products.id ==
                                     profileplan.product).select().first()
                        if product.name.find("SSL") != -1 and cert == "false":
                            continue
                        orderlistid = db.orderlist.insert(
                            product=product.id,
                            g_order=orderid,
                            quantity=1,
                            price=product.price,
                            price_wdto=product.price,
                            tax=settings.tax)

                        #NO SE PUEDE HACER EL INSERT DIRECTAMENTE. HAY QUE VER SI EL SHOP YA TIENE CONTRATADO EL PRODUCTO. SI NO TIENE se hace un INSERT, si no, no hace nada.
                        #En realidad esta comprobación no hace falta porque no se va a dar este caso, pero sí en contracts.postcontracts por ser una generación de contratos manual .
                        #Sólo se va a poder contratar una unidad y la recursividad y duración de la periodicidad harán el resto.

                        contracted = db(
                            (db.contractedproducts.shop == shop.id)
                            & (db.contractedproducts.user == auth.user_id)
                            & (db.contractedproducts.product == product.id)
                        ).select().first()

                        if not contracted:
                            db.contractedproducts.insert(
                                user=auth.user_id,
                                product=product.id,
                                period=product.min_period,
                                autorenove=product.suscription,
                                start=None,
                                renove=None,  #fecha de la renovación.
                                expiration=None,
                                shop=shop.id,
                                orderlist=orderlistid,
                                paymentmethod=None)

                db.commit()
                return "OK"
        except Exception as ex:
            session.flash = "Ocurrió un error al crear el pedido %s" % ex
            redirect(request.env.http_referer)

    else:
        session.flash = "Disculpen la molestias. No podemos encontrar la información requerida"
        redirect(request.application, 'account', 'index')
Exemplo n.º 21
0
#*/1 * * * * cd /home/gextiendas/web2py && /usr/bin/python web2py.py -S gextiendas -M -R applications/gextiendas/private/managetools/managedomains_contracts.py >> /tmp/manage_domains_contracts.out 2>&1

#este cron busca dominios para activar/desactivar en tiendas

# client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None")

# client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None")
# logger.debug(client.addShopSite(auth.user_id))

#buscar contratos cuya fecha de expiración sea NULL o >= CURRENT_DATE() y plan distinto de NULL o free

from gluon import *
from shops import ContractedProduct, Product, PricePlan, Shop
from invoices import Order, Orderlist
contract = ContractedProduct(db)
Product(db), PricePlan(db), Shop(db), Orderlist(db), Order(db)

mcontracts = db(
    ((db.contractedproducts.expiration == None)
     | (db.contractedproducts.expiration >= datetime.datetime.now()))
    & ((db.profileplans.active == True) & (db.priceplans.planname != "free")
       & (db.contractedproducts.active == True))).select(
           db.contractedproducts.ALL,
           db.products.plan,
           db.products.price,
           db.products.suscription,
           db.products.name,
           db.priceplans.planname,
           db.priceplans.id,
           db.profileplans.ALL,
           db.orders.ALL,
Exemplo n.º 22
0
def _get_and_store_shop_id(installation):
    shop_id = get_shop_id(installation)
    shop = Shop(shop_id, installation.hostname)
    SHOPS.create_or_update_shop(shop)
Exemplo n.º 23
0
import os
import socket
import datetime
import copy
import gluon.contenttype
import gluon.fileutils

from blog import Blog, Draft, Images
from shops import Shop, DomainShop, PricePlan, Product, ContractedProduct, ProfilePlan, PricePlan, CustomerAgreement, Agreement
from invoices import Invoice, Order, Orderlist, Fiscal, CreditAccount, AccountingEntry, Budget, Budgetlist
from regnews import Regnews
from province import Province
from cities import Cities
Images(db), Blog(db, ckeditor), Draft(
    db, ckeditor), Regnews(db), Province(db), Cities(db)
Shop(db), PricePlan(db), DomainShop(db), Product(db)
ProfilePlan(db), PricePlan(db), CustomerAgreement(db), Agreement(db)
Invoice(db), Order(db), Orderlist(db), Budget(db), Budgetlist(db), Fiscal(
    db), ContractedProduct(db), CreditAccount(db), AccountingEntry(db)

try:
    import pygraphviz as pgv
except ImportError:
    pgv = None

# ## critical --- make a copy of the environment

global_env = copy.copy(globals())
global_env['datetime'] = datetime

http_host = request.env.http_host.split(':')[0]
Exemplo n.º 24
0
	def __init__(self, db, shopid, error_message="Este dominio ya está siendo usado en otra tienda"):
		self.error_message=error_message
		self.shopid=shopid
		self.db=db
		Shop(self.db), DomainShop(self.db)