예제 #1
0
def delitem():
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        from invoices import Invoice, Order, Orderlist
        from shops import Product
        from adminsettings import Adminsettings
        Adminsettings(db), Invoice(db), Order(db), Orderlist(db), Product(db)
        settings = db(db.adminsettings.id > 0).select(
            db.adminsettings.ALL).first()

        order = db((db.orders.user == request.vars.customer)
                   & (db.orders.id == request.vars.orderid)).select().first()
        try:
            db((db.orderlist.id == request.vars.id)
               & (db.orderlist.g_order == order.id)).delete()
            db.commit()
        except:
            db.rollback()

        return db((db.orderlist.g_order == order.id)).select(
            db.orderlist.ALL,
            db.products.name,
            db.products.id,
            join=[db.products.on(db.products.id == db.orderlist.product)
                  ]).as_list()
    else:
        return dict()
예제 #2
0
def viewinvoice():

	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from invoices import Invoice, Order, Orderlist, Budget, AccountingEntry, CreditAccount
		Invoice(db), Order(db), Orderlist(db), Budget(db), AccountingEntry(db), CreditAccount(db)
		invoice= db(db.invoices.id==request.args(0)).select(db.invoices.ALL, 
															db.auth_user.id,
															db.auth_user.first_name,
															db.auth_user.last_name,  
															db.fiscals.ALL,
															left=[	db.auth_user.on(db.auth_user.id==db.invoices.user),
																	db.fiscals.on(db.fiscals.user==db.auth_user.id)]).first()



		orderlist= db(db.orders.invoice==invoice.invoices.id).select(	db.orders.ALL, 
																		db.orderlist.ALL,
																		db.products.ALL,
																		left=[	db.orderlist.on(db.orderlist.g_order==db.orders.id),
																				db.products.on(db.products.id==db.orderlist.product)])

		order=db(db.orders.invoice==invoice.invoices.id).select(db.orders.ALL).first()

		return dict(invoice=invoice, orderlist=orderlist, order=order)
	else:
		redirect(URL(request.application,'default','user/login'))
예제 #3
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'))
예제 #4
0
def vieworder():
    if auth.has_membership('administradores') or auth.has_membership(
            'superadministradores'):
        from invoices import Order, Orderlist
        from shops import Product
        Order(db), Orderlist(db), Product(db)
        order = db(db.orders.id == request.args(0)).select(
            db.orders.ALL,
            db.auth_user.id,
            db.auth_user.first_name,
            db.auth_user.last_name,
            db.fiscals.ALL,
            left=[
                db.auth_user.on(db.auth_user.id == db.orders.user),
                db.fiscals.on(db.fiscals.user == db.auth_user.id)
            ]).first()

        if order:
            orderlist = db(db.orderlist.g_order == order.orders.id).select(
                db.orderlist.ALL,
                db.products.ALL,
                left=[db.products.on(db.products.id == db.orderlist.product)])

            return dict(order=order, orderlist=orderlist)
        else:
            redirect(URL(request.application, 'administrator', 'users'))
    else:
        redirect(URL(request.application, 'default', 'user/login'))
예제 #5
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'))
예제 #6
0
def cancelinvoice():
    from invoices import Order
    Order(db)
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        try:
            if request.vars.budget != 'None' and request.vars.budget != None:
                db((db.orders.user == request.vars.customer)
                   & (db.orders.status == "CreandoAdmin")
                   & (db.orders.budget == request.vars.budget)).delete()
            else:
                db((db.orders.user == request.vars.customer)
                   & (db.orders.status == "CreandoAdmin")).delete()

        except Exception as ex:
            logger.debug(
                "Ocurrió un error al borrar una orden de pedido desde billing: %s"
                % ex)
            response.flash = "Ocurrió un error: %s" % ex

        redirect(
            URL(request.application,
                'administrator',
                'editcustomer',
                args=request.vars.customer))
        return dict()
예제 #7
0
def index():
	from invoices import Fiscal, Order, Orderlist
	from shops import Product, PricePlan
	Fiscal(db), Product(db), PricePlan(db), Order(db), Orderlist(db)
	fiscal=db(db.fiscals.user==auth.user_id).select().first()
	order=None
	orderlist=None
	if fiscal:
		order=db((db.orders.user==auth.user_id) & (db.orders.status=="Creando")).select().first()
		if order:
			orderlist=db(db.orderlist.g_order==order.id).select()
			flatrate=False
			for item in orderlist:
				if item.product.plan:
					if item.product.plan.paymode=="flatrate":
						flatrate=True
		else:
			redirect(URL(c='account',f='index'))

	else:
		redirect(URL('myaccount', 'fiscal', vars=dict(wizard=True)))

	form=FORM(	INPUT(_type='radio', _name='paypal', _id='paypal', _value='paypal', value='yes').xml(),
				INPUT(_type='radio', _name='bank', _id='bank', _value='bank', value='no').xml(),
				INPUT(_name="confirm", _type='submit', _class="btn btn-grove-two btn-xlg"), _action=URL('confirm_order') )

	return dict(form=form, fiscal=fiscal, orderlist=orderlist, order=order, flatrate=flatrate)
예제 #8
0
def viewinvoice():
    from invoices import Invoice, Order, Orderlist, Budget, AccountingEntry, CreditAccount
    Invoice(db), Order(db), Orderlist(db), Budget(db), AccountingEntry(
        db), CreditAccount(db)
    invoice = db((db.invoices.invoice_number == request.args(0))
                 & (db.invoices.user == auth.user_id)).select(
                     db.invoices.ALL,
                     db.auth_user.id,
                     db.auth_user.first_name,
                     db.auth_user.last_name,
                     db.fiscals.ALL,
                     left=[
                         db.auth_user.on(db.auth_user.id == db.invoices.user),
                         db.fiscals.on(db.fiscals.user == db.auth_user.id)
                     ]).first()

    orderlist = db(db.orders.invoice == invoice.invoices.id).select(
        db.orders.ALL,
        db.orderlist.ALL,
        db.products.ALL,
        left=[
            db.orderlist.on(db.orderlist.g_order == db.orders.id),
            db.products.on(db.products.id == db.orderlist.product)
        ])

    order = db(db.orders.invoice == invoice.invoices.id).select(
        db.orders.ALL).first()

    return dict(invoice=invoice, orderlist=orderlist, order=order)
예제 #9
0
def mycredit():
    from invoices import CreditAccount, AccountingEntry, Order, Orderlist
    Order(db), CreditAccount(db), AccountingEntry(db), Orderlist(db)
    creditaccount = db(db.creditaccounts.user == 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(creditaccount=creditaccount,
                accountingentries=accountingentries,
                invoices=db(db.invoices.user == auth.user_id).select())
예제 #10
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)
예제 #11
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)
예제 #12
0
파일: shops.py 프로젝트: FreeMEM/gextiendas
	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
예제 #13
0
def items():
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        from invoices import Invoice, Order, Orderlist
        from shops import Product
        from adminsettings import Adminsettings
        from auxiliartools import AuxiliarTools
        external = AuxiliarTools(db)
        Adminsettings(db), Invoice(db), Order(db), Orderlist(db), Product(db)
        settings = db(db.adminsettings.id > 0).select(
            db.adminsettings.ALL).first()
        #entrada: data: { 'product': int, 'quantity': int, 'rate': int, 'operation': ['add','del','set'] }
        #salida: (json)sales
        #begin
        #comprobar si tiene un order abierta y si no crearla

        if request.vars.budget != 'None' and request.vars.budget != None:

            order = db(
                (db.orders.user == request.vars.customer)
                & (db.orders.status == "CreandoAdmin")
                & (db.orders.budget == request.vars.budget)).select().first()
        elif request.vars.order != 'None' and request.vars.order != None:
            order = db((db.orders.user == request.vars.customer) &
                       (db.orders.id == request.vars.order)).select().first()

        else:

            order = db((db.orders.user == request.vars.customer) &
                       (db.orders.status == "CreandoAdmin")).select().first()

        try:
            if not order:
                orderid = db.orders.insert(
                    status="CreandoAdmin",
                    user=request.vars.customer,
                    payment_method='Domiciliación',
                    tax=settings.tax,
                    budget=(
                        None,
                        request.vars.budget)[request.vars.budget != 'None'],
                    manual_operation=True)
                order = db.orders(orderid).first()

            orderlist = db((db.orderlist.g_order == order.id)).select(
                db.orderlist.ALL,
                db.products.name,
                db.products.id,
                join=[db.products.on(db.products.id == db.orderlist.product)
                      ]).as_list()

            return orderlist

        except Exception as ex:
            logger.debug(ex)
            db.rollback()
    else:
        return dict()
예제 #14
0
def bankcheckout():
	from queuemail import Queuemail
	from invoices import Order, Orderlist
	from adminsettings import Adminsettings
	Order(db), Orderlist(db), Adminsettings(db)
	settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
	logger.debug(settings)
	queue=Queuemail(db)
	
	try:
		queuedata=[]		
		order=db((db.orders.user==auth.user_id) & (db.orders.status=="Creando")).select().first()

		if order!=None:
			
		 	db((db.orders.user==auth.user_id) & (db.orders.status=="Creando")).update(status='Pendiente pago', ordered_at=datetime.datetime.now(), payment_method="Transferencia")
		 	queuedata.append({'to': '%s'%auth.user.email,
					'subject':'[gextiendas] Confirmación pedido',
					'message':'Estimado %s,\nen cuanto realice su transferencia, en un plazo de 24/72 horas (según el tiempo de gestíón entre entidades bancarias) podremos verificarla y el servicio se activará. Es muy importante que no olvide detallar como concepto en la transferencia la referencia %s.\n\nSi tiene cualquier duda, le rogamos se ponga en contacto con nosotros. Muchas gracias por confiar en nuestro equipo.\n\nReciba un cordial saludo.\n--\nGextiendas' % (auth.user.first_name,order.payment_code.code)
					})
		 	
			#y ahora notificación a cada uno de los administradores
			logger.debug(db(db.auth_membership.group_id== db(db.auth_group.role=="administradores").select().first()['id'])._select(db.auth_membership.ALL, db.auth_user.ALL, left=db.auth_user.on(db.auth_membership.user_id==db.auth_user.id)))			
			mails=db(db.auth_membership.group_id==db((db.auth_group.role=="administradores") | (db.auth_group.role=="superadministradores") ).select().first()['id']).select(db.auth_membership.ALL, db.auth_user.ALL, left=db.auth_user.on(db.auth_membership.user_id==db.auth_user.id))
			
			for m in mails:
			
				url = "%(scheme)s://%(host)s%(urlrequest)s" % {	'scheme':request.env.wsgi_url_scheme,
																'host':request.env.http_host,
																'urlrequest':URL(	request.application, 
																					'administrator', 
																					'orders', 
																					vars=dict(id=order.id))}
			
				queuedata.append({'to':'%s' % m.auth_user.email,
								'subject':'Aviso de pago mediante transferencia para %s'%order.payment_code.code,
								'message':'El usuario %s ha solicitado pagar mediante transferencia bancaria los servicios . Desde el momento que el cliente haga la misma, tendrá entre 24/48 horas para verificar la recepción de la misma:\n\n %s\n\n' % (auth.user.email, url)
								})
			
				queue.queuemessage(queuedata)
			

			
			db.commit()
			
			session.flash="Pedido confirmado. Le hemos enviado un correo electrónico"
			return dict(bank_account=settings.bank_account, beneficiary=settings.beneficiary, bank=settings.bank, ref=order.payment_code.code, total="%.2f" % (float(order.total) + float(order.totaltax)), redirect=False)
		else:
			return dict(redirect=True)

	except Exception as ex:
		session.flash="Ocurrió un error al hacer el pedido. Inténtelo de nuevo"
		db.rollback()
		
		return dict(bank_account=settings.bank_account, beneficiary=settings.beneficiary, bank=settings.bank, ref=order.payment_code, total="%.2f" % (float(order.total) + float(order.totaltax)), redirect=False)
예제 #15
0
def confirm_payment():
    if auth.has_membership('administradores') or auth.has_membership(
            'superadministradores'):
        from invoices import Order
        Order(db)
        db((db.orders.invoice == request.vars.invoice)
           & (db.orders.user == request.args(0))).update(status="Pagado")
        db.commit()
        session.flash = "La factura se ha marcado como pagada"
        redirect(
            URL('administrator', 'viewinvoice', args=[request.vars.invoice]))
        return dict()
    else:
        redirect(URL(request.application, 'default', 'user/login'))
예제 #16
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'))
예제 #17
0
def updating_paymethod():
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        from invoices import Order
        Order(db)
        try:
            db((db.orders.user == request.vars.customer)
               & (db.orders.id == request.vars.orderid)).update(
                   payment_method=request.vars.paymentmethod)
            db.commit()
            return dict(callback="OK")
        except Exception as ex:
            db.rollback()
            logger.debug("Ocurrió un error al modificar el método de pago %s" %
                         ex)
            return dict(callback="Fail")
예제 #18
0
def confirmorder():
    from invoices import Order, Orderlist
    from adminsettings import Adminsettings
    Adminsettings(db), Order(db), Orderlist(db)
    settings = db(db.adminsettings.id > 0).select(db.adminsettings.ALL).first()
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        try:
            order = db((db.orders.user == request.vars.customer) & (
                db.orders.id == request.vars.orderid)).select().first()

            total = float(0)
            totaltax = float(0)
            orderlist = db(db.orderlist.g_order == order.id).select()

            if orderlist:
                for row in orderlist:
                    total = total + (float(row.quantity) * float(row.price))

                totaltax = (total * float(settings.tax)) / 100
                if request.args(0) == "onlycreate":
                    db(db.orders.id == order.id).update(
                        total="%.2f" % total,
                        totaltax="%.2f" % totaltax,
                        status="Pendiente pago")

                else:
                    db(db.orders.id == order.id).update(
                        total="%.2f" % total,
                        totaltax="%.2f" % totaltax,
                        status="Pendiente pago",
                        confirmed_at=datetime.datetime.now(),
                        confirmed_by=auth_user)

                db.commit()

        except Exception as ex:
            db.rollback()
            logger.debug("Ocurrió un error al generar la factura %s" % ex)
            session.flash = "Se produjo un error al generar la factura: %s" % ex
            redirect(URL('order', 'neworder', args=order.id))

        redirect(URL(request.application, 'orders', 'vieworder',
                     args=order.id))
        return dict()
예제 #19
0
def cancelorder():
    from invoices import Order
    Order(db)
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        try:
            db((db.orders.user == request.vars.customer)
               & (db.orders.id == request.vars.orderid)).delete()

        except Exception as ex:
            logger.debug(
                "OCurrió un error al borrar una orden de pedido desde billing: %s"
                % ex)
            response.flash = "Ocurrió un error: %s" % ex

        redirect(
            URL(request.application,
                'administrator',
                'editcustomer',
                args=request.vars.customer))
        return dict()
예제 #20
0
def billing():
	
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from invoices import Fiscal, Invoice,Order
		from pagination import Pagination
		Fiscal(db), Invoice(db), Order(db)
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		count=db.invoices.id.count()
		records=db((db.invoices.id>0)).select(count,
											left=[	db.auth_user.on(db.auth_user.id==db.invoices.user),
													db.fiscals.on(db.fiscals.user==db.auth_user.id)],
											orderby=~db.invoices.id).first()
		items_per_page=settings.invoiceitems
		pag=Pagination(int(records[count]), items_per_page)
		invoices= db((db.invoices.id>0)).select(db.orders.status,
												db.orders.invoice,
												db.invoices.ALL, 
												db.auth_user.id,
												db.auth_user.first_name,
												db.auth_user.last_name,  
												db.fiscals.fiscalname,

												left=[	db.orders.on(db.orders.invoice==db.invoices.id),
														db.auth_user.on(db.auth_user.id==db.invoices.user),
														db.fiscals.on(db.fiscals.user==db.auth_user.id),
														],
												orderby=~db.invoices.id,
												limitby=pag.limitby())
		
		total=0
		totaltaxes=0
		for invoice in db(db.invoices.created_at>=datetime.date(datetime.datetime.today().year,1,1)).select():
			total=total+ invoice.total
			totaltaxes= totaltaxes + invoice.taxes

		return dict(invoices=invoices, pagination=pag, records=records[count], items_per_page=items_per_page, total=total, totaltaxes=totaltaxes)

	else:
		redirect(URL(request.application,'default','user/login'))
예제 #21
0
def items():
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        from invoices import Invoice, Order, Orderlist
        from shops import Product
        from adminsettings import Adminsettings
        Adminsettings(db), Invoice(db), Order(db), Orderlist(db), Product(db)
        settings = db(db.adminsettings.id > 0).select(
            db.adminsettings.ALL).first()
        #entrada: data: { 'product': int, 'quantity': int, 'rate': int, 'operation': ['add','del','set'] }
        #salida: (json)sales
        #begin
        #comprobar si tiene un order abierta y si no crearla
        order = db((db.orders.user == request.vars.customer)
                   & (db.orders.id == request.vars.orderid)).select().first()

        try:
            if not order:
                orderid = db.orders.insert(status="CreandoAdmin",
                                           user=request.vars.customer,
                                           payment_method='Transferencia',
                                           tax=settings.tax,
                                           manual_operation=True)
                order = db.orders(orderid)

            return db((db.orderlist.g_order == order.id)).select(
                db.orderlist.ALL,
                db.products.name,
                db.products.id,
                join=[db.products.on(db.products.id == db.orderlist.product)
                      ]).as_list()

        except Exception as ex:
            logger.debug(ex)
            db.rollback()
    else:
        return dict()
예제 #22
0
def ipn_handler():
	import urllib2, datetime

	logger.debug(request.vars)



	#queryid=request.vars['custom']

	
	url="%(scheme)s://%(host)s?cmd=_notify-validate&%(urlrequest)s" % {'scheme':request.env.wsgi_url_scheme,'host':'www.sandbox.paypal.com/cgi-bin/webscr','urlrequest':URL(vars=request.vars)}
	#url="%(scheme)s://%(host)s?cmd=_notify-validate&%(urlrequest)s" % {'scheme':request.env.wsgi_url_scheme,'host':'www.paypal.com/cgi-bin/webscr','urlrequest':URL(vars=request.vars)}

	url=url.replace("/payment/ipn_handler?","")
	#logger.debug("llego4 %s" % url)

	result=""
	while True:
	 	try:
	 		req = urllib2.Request(url)
	 		output = urllib2.urlopen(req)
	 		result=output.read()
	 		break
		except Exception as ex:
				logger.debug("Error %s"% ex)

	

	#IPN datos relevante: custom, subscr_id, txn_type, txn_id, ipn_track_id, payment_status,
	# PayPal will then send one single-word message, VERIFIED, if the message is valid; otherwise, it will send another single-word message, INVALID.

	# Important: After you have authenticated an IPN message (that is, received a VERIFIED response from PayPal), you must perform these important checks before you can assume that the IPN is both legitimate and has not already been processed:

	# Check that the payment_status is Completed.
	# If the payment_status is Completed, check the txn_id against the previous PayPal transaction that you processed to ensure the IPN message is not a duplicate.
	# Check that the receiver_email is an email address registered in your PayPal account.
	# Check that the price (carried in mc_gross) and the currency (carried in mc_currency) are correct for the item (carried in item_name or item_number).
	# Once you have completed these checks, IPN authentication is complete. Now, you can update your database with the information provided and initiate any back-end processing that's appropriate.
		
	#IPN nornal

	#<Storage {'protection_eligibility': 'Eligible', 'last_name': 'Buyer', 'txn_id': '3DE20514FP4266159', 'receiver_email': '*****@*****.**', 'payment_status': 'Completed', 'payment_gross': '', 'tax': '0.00', 'residence_country': 'ES', 'address_state': 'Albacete', 'payer_status': 'verified', 'txn_type': 'web_accept', 'address_country': 'Spain', 'handling_amount': '0.00', 'payment_date': '03:40:08 Nov 04, 2014 PST', 'first_name': 'Test', 'item_name': '[Gextiendas] Servicios de ecommerce', 'address_street': 'calle Vilamar\\xc3\\xad 76993- 17469', 'charset': 'windows-1252', 'custom': '0113679HUQ', 'notify_version': '3.8', 'address_name': 'Test Buyer', 'test_ipn': '1', 'item_number': '', 'receiver_id': 'K6VY4N9UQQLNQ', 'transaction_subject': '0113679HUQ', 'business': '*****@*****.**', 'payer_id': 'RNH2WS7RX3LV8', 'verify_sign': 'AwD4sJJmdrzDKNGw7KMAMuZSx1AHAUFXw7K0K.MTc4yFwx3f-ME79PYb', 'address_zip': '02001', 'payment_fee': '', 'address_country_code': 'ES', 'address_city': 'Albacete', 'address_status': 'unconfirmed', 'mc_fee': '2.61', 'mc_currency': 'EUR', 'shipping': '0.00', 'payer_email': '*****@*****.**', 'payment_type': 'instant', 'mc_gross': '66.55', 'ipn_track_id': '70c4750d34201', 'quantity': '1'}> 
	#<Storage {'protection_eligibility': 'Eligible', 'last_name': 'Buyer', 'txn_id': '3DE20514FP4266159', 'receiver_email': '*****@*****.**', 'payment_status': 'Completed', 'payment_gross': '', 'tax': '0.00', 'residence_country': 'ES', 'address_state': 'Albacete', 'payer_status': 'verified', 'txn_type': 'web_accept', 'address_country': 'Spain', 'handling_amount': '0.00', 'payment_date': '03:40:08 Nov 04, 2014 PST', 'first_name': 'Test', 'item_name': '[Gextiendas] Servicios de ecommerce', 'address_street': 'calle Vilamar\\xc3\\x83\\xc2\\xad 76993- 17469', 'charset': 'UTF-8', 'custom': '0113679HUQ', 'notify_version': '3.8', 'address_name': 'Test Buyer', 'test_ipn': '1', 'item_number': '', 'receiver_id': 'K6VY4N9UQQLNQ', 'transaction_subject': '0113679HUQ', 'business': '*****@*****.**', 'payer_id': 'RNH2WS7RX3LV8', 'auth': 'A5I9nNJn6BAC5e2tgl00VrEPDi978J0G7DckCMvTJ2Wus4RGjw67pD3EaztVX2b2cU4WjXEM43QIgv9obAMATIA', 'verify_sign': 'AFcWxV21C7fd0v3bYYYRCpSSRl31Af8nlEsXeJR3qYq0oRp.V6axDaRc', 'address_zip': '02001', 'payment_fee': '', 'address_country_code': 'ES', 'address_city': 'Albacete', 'address_status': 'unconfirmed', 'mc_fee': '2.61', 'mc_currency': 'EUR', 'shipping': '0.00', 'payer_email': '*****@*****.**', 'payment_type': 'instant', 'mc_gross': '66.55', 'quantity': '1'}> [] 
	#<Storage {'protection_eligibility': 'Eligible', 'last_name': 'Buyer', 'txn_id': '3DE20514FP4266159', 'receiver_email': '*****@*****.**', 'payment_status': 'Completed', 'payment_gross': '', 'tax': '0.00', 'residence_country': 'ES', 'address_state': 'Albacete', 'payer_status': 'verified', 'txn_type': 'web_accept', 'address_country': 'Spain', 'handling_amount': '0.00', 'payment_date': '03:40:08 Nov 04, 2014 PST', 'first_name': 'Test', 'item_name': '[Gextiendas] Servicios de ecommerce', 'address_street': 'calle Vilamar\\xc3\\xad 76993- 17469', 'charset': 'windows-1252', 'custom': '0113679HUQ', 'notify_version': '3.8', 'address_name': 'Test Buyer', 'test_ipn': '1', 'item_number': '', 'receiver_id': 'K6VY4N9UQQLNQ', 'transaction_subject': '0113679HUQ', 'business': '*****@*****.**', 'payer_id': 'RNH2WS7RX3LV8', 'verify_sign': 'AwD4sJJmdrzDKNGw7KMAMuZSx1AHAUFXw7K0K.MTc4yFwx3f-ME79PYb', 'address_zip': '02001', 'payment_fee': '', 'address_country_code': 'ES', 'address_city': 'Albacete', 'address_status': 'unconfirmed', 'mc_fee': '2.61', 'mc_currency': 'EUR', 'shipping': '0.00', 'payer_email': '*****@*****.**', 'payment_type': 'instant', 'mc_gross': '66.55', 'ipn_track_id': '70c4750d34201', 'quantity': '1'}> 
	#<Storage {'protection_eligibility': 'Eligible', 'last_name': 'Buyer', 'txn_id': '3DE20514FP4266159', 'receiver_email': '*****@*****.**', 'payment_status': 'Completed', 'payment_gross': '', 'tax': '0.00', 'residence_country': 'ES', 'address_state': 'Albacete', 'payer_status': 'verified', 'txn_type': 'web_accept', 'address_country': 'Spain', 'handling_amount': '0.00', 'payment_date': '03:40:08 Nov 04, 2014 PST', 'first_name': 'Test', 'item_name': '[Gextiendas] Servicios de ecommerce', 'address_street': 'calle Vilamar\\xc3\\xad 76993- 17469', 'charset': 'windows-1252', 'custom': '0113679HUQ', 'notify_version': '3.8', 'address_name': 'Test Buyer', 'test_ipn': '1', 'item_number': '', 'receiver_id': 'K6VY4N9UQQLNQ', 'transaction_subject': '0113679HUQ', 'business': '*****@*****.**', 'payer_id': 'RNH2WS7RX3LV8', 'verify_sign': 'AwD4sJJmdrzDKNGw7KMAMuZSx1AHAUFXw7K0K.MTc4yFwx3f-ME79PYb', 'address_zip': '02001', 'payment_fee': '', 'address_country_code': 'ES', 'address_city': 'Albacete', 'address_status': 'unconfirmed', 'mc_fee': '2.61', 'mc_currency': 'EUR', 'shipping': '0.00', 'payer_email': '*****@*****.**', 'payment_type': 'instant', 'mc_gross': '66.55', 'ipn_track_id': '70c4750d34201', 'quantity': '1'}> 
	

	#IPN recurrent  
	#primera notificación. Alta de suscripción. Notiicado por mi cuenta.	
	#<Storage {'last_name': 'Buyer', 'receiver_email': '*****@*****.**', 'residence_country': 'ES', 'payer_status': 'verified', 'txn_type': 'subscr_signup', 'first_name': 'Test', 'item_name': 'Servicios Gextiendas', 'charset': 'windows-1252', 'custom': '202545T4H4', 'notify_version': '3.8', 'recurring': '1', 'test_ipn': '1', 'business': '*****@*****.**', 'payer_id': 'RNH2WS7RX3LV8', 'period3': '1 M', 'verify_sign': 'AX6PBnkcJ7jJrr5pDIO.z1RmrMaaAGgNGrGxSeVNwJzNXXwYvajPnm4-', 'subscr_id': 'I-BWW79X6683EA', 'mc_amount3': '21.78', 'mc_currency': 'EUR', 'subscr_date': '05:12:14 Nov 03, 2014 PST', 'payer_email': '*****@*****.**', 'ipn_track_id': '6eb738f99ad8', 'reattempt': '1'}>

	#segunda. Notificación de pago por parte de la cuenta del cliente
	#<Storage {'protection_eligibility': 'Ineligible', 'last_name': 'Buyer', 'txn_id': '69G69974FM486513Y', 'receiver_email': '*****@*****.**', 'payment_status': 'Completed', 'payment_gross': '', 'residence_country': 'ES', 'payer_status': 'verified', 'txn_type': 'subscr_payment', 'payment_date': '05:12:15 Nov 03, 2014 PST', 'first_name': 'Test', 'item_name': 'Servicios Gextiendas', 'charset': 'windows-1252', 'custom': '202545T4H4', 'notify_version': '3.8', 'transaction_subject': 'Servicios Gextiendas', 'test_ipn': '1', 'receiver_id': 'K6VY4N9UQQLNQ', 'business': '*****@*****.**', 'payer_id': 'RNH2WS7RX3LV8', 'verify_sign': 'AaS.4COnBP7ShIMRTtOpCSbO2eC3AXffHkIB5NNBcAMHHtS-KslOaLMS', 'subscr_id': 'I-BWW79X6683EA', 'payment_fee': '', 'mc_fee': '1.09', 'mc_currency': 'EUR', 'payer_email': '*****@*****.**', 'payment_type': 'instant', 'mc_gross': '21.78', 'ipn_track_id': '6eb738f99ad8'}> 

	# ==> /var/log/apache2/gextiendas_443.com-error.log <== 
	
	
	#baja
	#notificacion baja de suscripción desde mi cuenta por el payer
	#<Storage {'last_name': 'Buyer', 'receiver_email': '*****@*****.**', 'residence_country': 'ES', 'payer_status': 'verified', 'txn_type': 'subscr_cancel', 'first_name': 'Test', 'item_name': 'Servicios Gextiendas', 'charset': 'windows-1252', 'custom': '202545T4H4', 'notify_version': '3.8', 'recurring': '1', 'test_ipn': '1', 'business': '*****@*****.**', 'payer_id': 'RNH2WS7RX3LV8', 'period3': '1 M', 'verify_sign': 'Aey6maswQ4YaVSn6P5pFEGe747AEAsoWZDTnZcoJRVJim0KtLpzDZghw', 'subscr_id': 'I-BWW79X6683EA', 'mc_amount3': '21.78', 'mc_currency': 'EUR', 'subscr_date': '05:16:43 Nov 03, 2014 PST', 'payer_email': '*****@*****.**', 'ipn_track_id': 'd58261bd67c86', 'reattempt': '1'}> 
	

	if result.replace("\n","")=="VERIFIED":
		#guardar datos en paypalrecord
		from invoices import Paypalrecord, Paymentcode, Order
		Paypalrecord(db), Order(db)
		if request.vars['txn_id']:
			paypalrecord=db(db.paypalrecords.txn_id==request.vars['txn_id']).select(db.paypalrecords.ALL,
																					db.paymentcodes.ALL,
																					join=[db.paymentcodes.on(db.paymentcodes.id==db.paypalrecords.payment_code)])
			
			order=db(db.paymentcodes.code==request.vars['custom']).select(	db.orders.ALL,
																			db.payments.id,
																			join=[db.paymentcodes.id==db.orders.payment_code])

			if request.vars['payment_status']=='Completed':
				if not paypalrecord:
					if 	request.vars['receiver_email']==business and request.vars['mc_gross']== (order.orders.total + order.orders.totaltax) and request.vars['mc_currency']=="EUR": #para evitar spoofing IPN
						db.paypalrecord.insert(	
												payment_code = db(db.paymentcodes.code==request.vars['custom']).select(db.paymentcodes.id).first()['id'],
												subscr_id = request.vars['subscr_id'],
												payer_id = request.vars['payer_id'],
												txn_type = request.vars['txn_type'],
												txn_id = request.vars['txn_id'],
												ipn_track_id = request.vars['ipn_track_id'],
												payment_status = request.vars['payment_status'],
												payment_date = request.vars['payment_date'])

	elif result.replace("\n","")=="INVALID":
		#email a administradores para investigar. Sospechoso de fraude.
		pass
예제 #23
0
def paypalcheckout():
	from paypalcrypto import PaypalCrypto
	import time
	from queuemail import Queuemail
	from invoices import Order, Orderlist
	from shops import ContractedProduct, PricePlan
	from adminsettings import Adminsettings
	from auxiliartools import AuxiliarTools	
	
	Order(db), Orderlist(db), Adminsettings(db), ContractedProduct(db), PricePlan(db)
	settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
	external=AuxiliarTools(db)

	order=db((db.orders.user==auth.user_id) & (db.orders.status=="Creando")).select().first()
	
	
	try:
		if order!=None:
			
			code=external.generatecode()
			if not order.payment_code:
				order.update_record(payment_code=db.paymentcodes.insert(code=code))
				db.commit()
			order.update_record(payment_method="Paypal")
			#custom="código pedido %s %s %s"%(order.user*100, order.id*100, str(long(time.mktime(order.ordered_at.timetuple())*1e3)))
			
			logger.debug("FLATRATE: %s %s %s" % (request.vars.flatrate, request.vars.flatrate==True, type(request.vars.flatrate)))
			attributes=None
			if request.vars.flatrate=='False':

				attributes= {
					"cert_id":"UPWJKQGJHDE4S",
					"cmd":"_xclick",
					#"cmd":"_cart",
					"amount":"%.2f" % (float(order.total) + float(order.totaltax)),
					"currency_code":"EUR",
					"custom":order.payment_code.code,
					"item_name":"[Gextiendas] Servicios de ecommerce",
					#"business":"K6VY4N9UQQLNQ", #[email protected]
					"business":"*****@*****.**",
					#"business":"*****@*****.**",
					"paymentaction":"sale",
					"notify_url":"%(scheme)s://%(host)s%(urlrequest)s" % {'scheme':request.env.wsgi_url_scheme,'host':request.env.http_host,'urlrequest':URL(request.application,'payment','ipn_handler')},
					"return":"%(scheme)s://%(host)s%(urlrequest)s" % {'scheme':request.env.wsgi_url_scheme,'host':request.env.http_host,'urlrequest':URL(request.application, 'payment','receipt_page')}
				}
			else:
				attributes= {
					"cert_id":"UPWJKQGJHDE4S",
					"cmd":"_xclick-subscriptions",
					#"amount":"%.2f" % (float(order.total) + float(order.totaltax)),
					"a3":"%.2f" % (float(order.total) + float(order.totaltax)),
					"p3":"1",
					"t3":"M",
					"src":"1",
					"sra":"1",
					"1c":"ES",
					"no_shipping":"1",
					"currency_code":"EUR",
					"custom":order.payment_code.code,
					"item_name":"Servicios Gextiendas",
					#"business":"K6VY4N9UQQLNQ", #[email protected]
					"business": business,
					#"business":"*****@*****.**",
					"paymentaction":"sale",
					"notify_url":"%(scheme)s://%(host)s%(urlrequest)s" % {'scheme':request.env.wsgi_url_scheme,'host':request.env.http_host,'urlrequest':URL(request.application,'payment','ipn_handler')},
					"return":"%(scheme)s://%(host)s%(urlrequest)s" % {'scheme':request.env.wsgi_url_scheme,'host':request.env.http_host,'urlrequest':URL(request.application, 'account','index')}
				}

			logger.debug("ATTRIBUTESSS %s" % attributes)
	except Exception as ex:
		db.rollback()
		logger.debug("Paypalcheck error: %s" % ex)
		session.flash="Ocurrió un error, inténtelo de nuevo"
		redirect('payment','index')

	pc=PaypalCrypto(attributes)
	encattrs=pc.paypalencrypt()
	logger.debug("encattrs: %s" % encattrs)

	

	return dict(encattrs=encattrs, order=db(db.orders.id==order.id).select(	db.orders.ALL,
												db.contractedproducts.ALL,
												left=[	db.orderlist.on(db.orderlist.g_order==db.orders.id),
														db.contractedproducts.on(db.contractedproducts.orderlist==db.orderlist.id)]
												).first())
예제 #24
0
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]
remote_addr = request.env.remote_addr
try:
예제 #25
0
파일: plans.py 프로젝트: FreeMEM/gextiendas
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')
예제 #26
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'))
예제 #27
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'))
예제 #28
0
def item():
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):

        from shops import Product
        from invoices import Order, Orderlist
        from adminsettings import Adminsettings
        Adminsettings(db), Order(db), Orderlist(db), Product(db)
        settings = db(db.adminsettings.id > 0).select(
            db.adminsettings.ALL).first()
        #entrada: data: { 'product': int, 'quantity': int, 'rate': int, 'operation': ['add','del','set'] }
        #salida: (json)sales
        #begin
        #comprobar si tiene un order abierta y si no crearla
        if request.vars.orderid:
            order = db((db.orders.user == request.vars.customer) & (
                db.orders.id == request.vars.orderid)).select().first()
        else:
            order = db((db.orders.user == request.vars.customer) &
                       (db.orders.status == "CreandoAdmin")).select().first()
        if not order and request.vars.operation == "add":
            orderid = db.orders.insert(status="CreandoAdmin",
                                       user=request.vars.customer,
                                       payment_method='Transferencia',
                                       tax=settings.tax,
                                       manual_operation=True)
            order = db.orders(orderid)

        orderlist_id = None
        try:
            #add/del product y quantity.
            row = db((db.orderlist.product == request.vars.product)
                     & (db.orderlist.g_order == order.id)).select().first()

            if row:
                orderlist_id = row.id

                if request.vars.operation == "add":
                    db(db.orderlist.id == orderlist_id).update(
                        quantity=int(row.quantity) +
                        int(request.vars.quantity))

                elif request.vars.operation == "set":

                    db(db.orderlist.id == orderlist_id).update(
                        quantity=int(request.vars.quantity))
                db.commit()
            else:
                product = db(
                    db.products.id == request.vars.product).select().first()
                #valor iva, para conservar el valor en caso de variar en el futuro
                #el precio para conservar en caso de variar en el futuro.
                orderlist_id = db.orderlist.insert(
                    product=request.vars.product,
                    g_order=order.id,
                    quantity=request.vars.quantity,
                    price=product.price,
                    price_wdto=product.price,
                    tax="%.2f" % settings.tax)
                db.commit()

        except Exception as ex:
            logger.debug("ALGO SALIO MAL en item %s" % ex)
            db.rollback()
        #retorna json del pedido

        data = db((db.orderlist.g_order == order.id)).select(
            db.orderlist.ALL,
            db.products.name,
            join=[db.products.on(db.products.id == db.orderlist.product)
                  ]).as_list()
        return data
    else:
        return dict()
예제 #29
0
def printorder():
    import os, uuid, subprocess
    import gluon.contenttype, gluon.globals
    from appy.pod.renderer import Renderer
    from invoices import Order, Orderlist
    from shops import Product
    from adminsettings import Adminsettings
    Adminsettings(db), Order(db), Orderlist(db), Product(db)
    settings = db(db.adminsettings.id > 0).select(db.adminsettings.ALL).first()
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):

        order = db(db.orders.id == request.args(0)).select(
            db.orders.ALL,
            db.auth_user.id,
            db.auth_user.first_name,
            db.auth_user.last_name,
            db.auth_user.email,
            db.fiscals.ALL,
            left=[
                db.auth_user.on(db.auth_user.id == db.orders.user),
                db.fiscals.on(db.fiscals.user == db.auth_user.id)
            ]).first()
        if order:
            ordernumber = "%s" % order.orders.id
            orderdate = "%s" % order.orders.ordered_at.strftime("%d-%m-%Y")
            customernumber = "%s" % order.auth_user.email
            customernif = "%s" % ("", order.fiscals.tax_identification
                                  )[order.fiscals.tax_identification != None]
            nombre = "%s" % (
                "%s %s" %
                (order.auth_user.first_name, order.auth_user.last_name),
                order.fiscals.fiscalname)[order.fiscals.fiscalname != ""]
            domicilio = "%s" % (
                "", order.fiscals.address)[order.fiscals.address != None]
            domicilio2 = "%s %s %s" % (
                ("",
                 order.fiscals.postal_code)[order.fiscals.postal_code != None],
                ("", order.fiscals.city)[order.fiscals.city != None],
                ("", order.fiscals.province)[order.fiscals.province != None])
            telefono = "%s" % order.fiscals.country
            fax = "%s" % order.fiscals.phone

            iva = "%.2f" % order.orders.tax
            totaliva = "%.2f" % float(order.orders.totaltax)
            total = "%.2f" % float(order.orders.total)
            totalorder = "%.2f" % float(
                float(order.orders.total) + float(order.orders.totaltax))

            items = []

            for item in db(db.orderlist.g_order == order.orders.id).select(
                    db.orderlist.ALL,
                    db.products.ALL,
                    left=[
                        db.products.on(db.products.id == db.orderlist.product)
                    ]):

                tax_result = "%.2f" % (
                    ((float(item.orderlist.price) *
                      (float(item.orderlist.quantity))) *
                     float(item.orderlist.tax)) / float(100))

                items.append(
                    dict(
                        id="%s" % item.products.id,
                        name="%s" % item.products.name,
                        cant="%s" % item.orderlist.quantity,
                        price="%.2f" % float(item.orderlist.price),
                        percent="%.2f" % float(
                            item.orderlist.tax
                        ),  #se refiere al iva, pero en el .odt puse este nombre de variable por una ida de olla.
                        total="%.2f" % (float(item.orderlist.quantity) *
                                        float(item.orderlist.price))))

            try:

                # Report creation
                template_file = os.path.join(request.folder, 'private',
                                             'order.odt')
                # tmp_uuid = uuid.uuid4()
                output_file_odt = os.path.join(
                    request.folder, 'private', 'tmp',
                    '%s_%s.odt' % ("pedido", order.orders.id))
                output_file_pdf = os.path.join(
                    request.folder, 'private', 'tmp',
                    '%s_%s.pdf' % ("pedido", order.orders.id))

                #por si existiese de vez anterior
                for filepath in [output_file_odt, output_file_pdf]:
                    if os.path.exists(filepath):
                        os.remove(filepath)

                renderer = Renderer(template_file, locals(), output_file_odt)

                renderer.run()

                command = "unoconv --format pdf --output %s %s" % (
                    os.path.join(request.folder, 'private',
                                 'tmp'), output_file_odt)
                process = subprocess.Popen(command, shell=True)
                processcode = process.wait()

                response.headers['Content-Length'] = '%s' % os.path.getsize(
                    output_file_pdf)
                response.headers[
                    'Content-Type'] = '%s' % gluon.contenttype.contenttype(
                        '.pdf')
                response.headers[
                    'Content-Disposition'] = 'attachment; filename=%s_%s.pdf' % (
                        "pedido", order.orders.id)
                stream = open(output_file_pdf, 'rb')
                for filepath in [output_file_odt, output_file_pdf]:
                    if os.path.exists(filepath):
                        os.remove(filepath)
                return stream
                # response.stream(output_file_pdf, chunk_size=4096)

            except Exception as ex:

                for filepath in [output_file_odt, output_file_pdf]:
                    if os.path.exists(filepath):
                        os.remove(filepath)
                logger.debug("Error general al generar PDF: %s " % ex)
                pass
            except IOError, e:  # Explicitly ignore IOError if it occurs.

                for filepath in [output_file_odt, output_file_pdf]:
                    if os.path.exists(filepath):
                        os.remove(filepath)
                logger.debug("Error IOerror al generar PDF: %s" % e)
                pass
        session.flash = 'No se pudo encontrar el pedido, inténtelo de nuevo'
        if auth.has_membership('superadministradores') or auth.has_membership(
                'administradores'):
            redirect(
                URL(request.application,
                    'administrator',
                    'viewinvoice',
                    args=request.args(0)))
        else:
            redirect(
                URL(request.application,
                    'account',
                    'billing',
                    args=request.args(0)))
예제 #30
0
def neworder():

    from shops import Product
    from invoices import Fiscal, Order, Orderlist, Budgetlist
    from adminsettings import Adminsettings
    Adminsettings(db), Product(db), Fiscal(db), Order(db), Orderlist(
        db), Budgetlist(db)
    settings = db(db.adminsettings.id > 0).select(db.adminsettings.ALL).first()

    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        if request.args(0):
            products = db(db.products.active == True).select()
            if request.vars.budget:
                order = db((db.orders.user == request.args(0))
                           & (db.orders.status == "CreandoAdmin")
                           & (db.orders.budget == request.vars.budget)).select(
                           ).first()
                if not order:
                    orderid = db.orders.insert(status="CreandoAdmin",
                                               user=request.args(0),
                                               budget=request.vars.budget,
                                               tax=settings.tax,
                                               payment_method='Transferencia',
                                               manual_operation=True)
                    order = db.orders(orderid)
                    for row in db(db.budgetlist.g_budget ==
                                  request.vars.budget).select():
                        db.orderlist.insert(product=row.product,
                                            g_order=orderid,
                                            quantity=row.quantity,
                                            price=row.price,
                                            price_wdto=row.price_wdto,
                                            tax=row.tax,
                                            dto=row.dto,
                                            dto_percentage=row.dto_percentage)

            else:

                if request.args(1):
                    order = db((db.orders.user == request.args(0)) & (
                        db.orders.id == request.args(1))).select().first()
                else:
                    order = db((db.orders.user == request.args(0)) & (
                        db.orders.status == "CreandoAdmin")).select().first()

                if not order:
                    orderid = db.orders.insert(status="CreandoAdmin",
                                               tax=settings.tax,
                                               user=request.args(0),
                                               payment_method='Transferencia',
                                               manual_operation=True)
                    order = db.orders(orderid)

            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()

            db.commit()

            return dict(products=products,
                        customer=customer,
                        tax=order.tax,
                        order=order)
        else:
            redirect(URL(request.application, 'administrator', 'users'))
    else:
        redirect(URL(request.application, 'default', 'user/login'))