Exemple #1
0
def items():
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        from invoices import Invoice, Budget, Budgetlist
        from shops import Product
        from adminsettings import Adminsettings
        Adminsettings(db), Invoice(db), Budget(db), Budgetlist(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 budget abierta y si no crearla
        budget = db((db.budgets.user == request.vars.customer) &
                    (db.budgets.id == request.vars.budgetid)).select().first()

        try:
            if not budget:
                budgetid = db.budgets.insert(status="Creando",
                                             user=request.vars.customer,
                                             tax=settings.tax)
                budget = db.budgets(budgetid)

            return db((db.budgetlist.g_budget == budget.id)).select(
                db.budgetlist.ALL,
                db.products.name,
                db.products.id,
                join=[db.products.on(db.products.id == db.budgetlist.product)
                      ]).as_list()

        except Exception as ex:
            logger.debug(ex)
            db.rollback()
    else:
        return dict()
Exemple #2
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()
Exemple #3
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)
Exemple #4
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()
Exemple #5
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)
Exemple #6
0
	def __insertinvoice(self, order, invoice_number, paid, manualinvoice): #esto genera crédito y contratos
		from shops import ContractedProduct
		from adminsettings import Adminsettings
		db=self.db

		ContractedProduct(db), Orderlist(db), Adminsettings(db)
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		try:
			invoiceid=db.invoices.insert(	user=order.user,
											subtotal=order.total,
											discount="0.00",
											total="%.2f" % (float(order.total)+float(order.totaltax)),
											taxes=order.totaltax,
											tax=settings.tax,
											invoice_number=invoice_number)


			#fecha de confirmación del order y "Pagado"
			if paid!="Pendiente pago":
				db(db.orders.id==order.id).update(invoice=invoiceid, confirmed_at=datetime.datetime.now(), status="Pagado")
			else:
				db(db.orders.id==order.id).update(invoice=invoiceid, confirmed_at=datetime.datetime.now(), status=paid)


			#actualizar datos contratos sobre forma de pago
			success_annotation=True
			accountingentry=AccountingEntry(db)


			for orderlist in db(db.orderlist.g_order==order.id).select():
				db((db.contractedproducts.user==order.user) & (db.contractedproducts.product==orderlist.product)).update(paymentmethod=order.payment_method)
				if paid!="Pendiente pago" and not manualinvoice:
					#anotar accountingentry
					success_annotation=accountingentry.annotation(orderlist, order)

				if not success_annotation:
					break
			if success_annotation:
				db.commit()
				return invoiceid
			else:
				db.rollback()
				return None
			
			
		except db._adapter.driver.IntegrityError:
			db.rollback()
			logger.debug("ERROR IntegrityError en INSERTINVOICE : %s" % ex)

			self.makeinvoice(order.id)
		except Exception, ex:
			logger.debug("ERROR en INSERTINVOICE: %s" % ex)
			db.rollback()
			return None
Exemple #7
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()
Exemple #8
0
def newbudget():

    from shops import Product
    from invoices import Fiscal, Budget
    from adminsettings import Adminsettings
    Adminsettings(db), Product(db), Fiscal(db), Budget(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.args(1):
                budget = db((db.budgets.user == request.args(0)) & (
                    db.budgets.id == request.args(1))).select().first()
            else:
                budget = db((db.budgets.user == request.args(0)) &
                            (db.budgets.status == "Creando")).select().first()

            if not budget:
                budgetid = db.budgets.insert(status="Creando",
                                             tax=settings.tax,
                                             user=request.args(0))
                budget = db.budgets(budgetid)

            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=budget.tax,
                        budgetid=budget.id)
        else:
            redirect(URL(request.application, 'administrator', 'users'))
    else:
        redirect(URL(request.application, 'default', 'user/login'))
Exemple #9
0
def index(): 
	from pagination import Pagination
	from blog import Blog, Images
	from comments import Comments
	from adminsettings import Adminsettings, Cifrar
	Adminsettings(db)
	Blog(db,ckeditor), Images(db)
	Comments(db)
	settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
	session.publishing=False
	session.preview=False
	records=db(db.blog.id>0).count()
	items_per_page=settings.blogitems
	pag=Pagination(records, items_per_page)
	posts = db(db.blog.public==True).select(db.blog.ALL, orderby=~db.blog.id, limitby=pag.limitby(), cache=(cache.ram, 5), cacheable=True)
	lastposts = db(db.blog.public==True).select(db.blog.ALL, orderby=~db.blog.id, limitby=(0,10), cache=(cache.ram, 150), cacheable=True)
	
	return dict(posts=posts, pagination=pag, records=records, items_per_page=items_per_page, lastposts=lastposts)
Exemple #10
0
def confirmbudget():
    from invoices import Budget, Budgetlist
    from adminsettings import Adminsettings
    Adminsettings(db), Budget(db), Budgetlist(db)
    settings = db(db.adminsettings.id > 0).select(db.adminsettings.ALL).first()
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        try:
            budget = db((db.budgets.user == request.vars.customer) & (
                db.budgets.id == request.vars.budgetid)).select().first()

            total = float(0)
            totaltax = float(0)
            budgetlist = db(db.budgetlist.g_budget == budget.id).select()

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

                totaltax = (total * float(settings.tax)) / 100

                db(db.budgets.id == budget.id).update(
                    total="%.2f" % total,
                    totaltax="%.2f" % totaltax,
                    status="Creado",
                    confirmed_at=datetime.datetime.now())

                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('budget', 'newbudget', args=budget.id))

        redirect(
            URL(request.application,
                'administrator',
                'editcustomer',
                args=request.vars.customer))
        return dict()
Exemple #11
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()
Exemple #12
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'))
Exemple #13
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())
Exemple #14
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')
Exemple #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)
Exemple #16
0
def confirminvoice():
    from invoices import Order, Invoice, Orderlist, CreditAccount, AccountingEntry
    from adminsettings import Adminsettings
    Adminsettings(db), Order(db), Invoice(db), Orderlist(db)
    accounting = AccountingEntry(db)
    from auxiliartools import AuxiliarTools
    external = AuxiliarTools(db)
    settings = db(db.adminsettings.id > 0).select(db.adminsettings.ALL).first()
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):
        try:
            if request.vars.budget != 'None' and request.vars.budget != None:
                order = db((db.orders.user == request.vars.customer) & (
                    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()
            if not order.invoice:

                total = float(0)
                totaltax = float(0)
                orderlist = db(db.orderlist.g_order == order.id).select()
                fail = True
                if orderlist:
                    fail = False
                    for row in orderlist:
                        total = total + (float(row.quantity) *
                                         float(row.price))

                        totaltax = (total * float(settings.tax)) / 100
                    if request.vars.paid == 'False':
                        status = "Pendiente pago"
                    else:
                        status = "Pagado"
                    payment_code = None
                    if order.payment_method == "Transferencia":
                        payment_code = db.paymentcodes.insert(
                            code=external.generatecode())

                    db(db.orders.id == order.id).update(
                        total="%.2f" % total,
                        totaltax="%.2f" % totaltax,
                        status=status,
                        payment_code=payment_code,
                        confirmed_at=datetime.datetime.now(),
                        confirmed_ip=request.client,
                        confirmed_by=auth.user_id)

                    if request.vars.paid != 'False':
                        invoiceid = Invoice(db).makeinvoice(
                            order.id, None, True)  #Factura pagada
                    elif request.vars.paid == 'False':
                        invoiceid = Invoice(db).makeinvoice(
                            order.id, "Pendiente pago",
                            True)  #Pendiente de pago
                    if request.vars.budget != 'None' and request.vars.budget != None:
                        db(db.budgets.id == request.vars.budget).update(
                            invoice=invoiceid)
                    db.commit()

                    # Al ser una factura manual, hay que buscar si hay contratos esperando de ser tratados tras el pago
                    # buscar los contratos que pertenezcan a cada uno de los orderlist y si no están ya en accountingentries
                    # hacer las anotaciones que se tengan que hacer si credit_annotation==True
                    for row in orderlist:
                        contract = db(db.contractedproducts.orderlist ==
                                      row.id).select().first()
                        if contract:
                            #anotar crédito si orders pagado y si credit_annotation==True y si not in accountingentries
                            if contract.credit_annotation == True:
                                if not db(
                                    (db.accountingentries.orderlist == row.id)
                                        & (db.accountingentries.active == True)
                                ).select().first():
                                    if not accounting.annotation(
                                            row, order, positive=True):
                                        raise Exception(
                                            'Ocurrió un error al hacer la anotación en billing.confirminvoice'
                                        )

                else:
                    redirect(
                        URL(request.application,
                            'administrator',
                            'viewinvoice',
                            args=invoiceid))
                    return dict()

        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('billing', 'newinvoice', args=auth.user_id))
            return dict()
        if fail:
            redirect(
                URL(request.application,
                    'administrator',
                    'editcustomer',
                    args=request.vars.customer))
            return dict()
        else:
            redirect(
                URL(request.application,
                    'administrator',
                    'viewinvoice',
                    args=invoiceid))
            return dict()
Exemple #17
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()
Exemple #18
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)))
Exemple #19
0
# coding: utf8
from adminsettings import Adminsettings
Adminsettings(db)
@auth.requires_login()
@page_allowed_ip
def bloglist():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		from pagination import Pagination
		from blog import Blog, Draft, Images
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
		blog=Blog(db,ckeditor)
		draft=Draft(db,ckeditor)
		Images(db)
		brecords=db(db.blog.id>0).count()
		drecords=db(db.draft.id>0).count()
		records = int(brecords) + int(drecords)
		items_per_page=settings.bloglistitems
		pag=Pagination(records, items_per_page)
		drafts =db().select(db.draft.ALL, orderby=~db.draft.id, limitby=pag.limitby())
		posts = db().select(db.blog.ALL, orderby=~db.blog.id, limitby=pag.limitby())
		return dict(posts=posts, drafts=drafts, pagination=pag, records=records, items_per_page=items_per_page)
	else:
		redirect(URL(request.application,'blog','index'))



@auth.requires_login()
@page_allowed_ip
def emailbox():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		settings = db(db.adminsettings.id>0).select(db.adminsettings.ALL).first()
Exemple #20
0
def printinvoice():
    import os, uuid, subprocess
    import gluon.contenttype, gluon.globals
    from appy.pod.renderer import Renderer
    from invoices import Invoice, Order, Orderlist, 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()
    if auth.has_membership('superadministradores') or auth.has_membership(
            'administradores'):

        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.auth_user.email,
            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()
    else:

        invoice = db((db.invoices.id == 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.auth_user.email,
                         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()
    if invoice:
        invoicenumber = "%s" % invoice.invoices.invoice_number
        invoicedate = "%s" % invoice.invoices.created_at.strftime("%d-%m-%Y")
        customernumber = "%s" % invoice.auth_user.email
        customernif = "%s" % invoice.fiscals.tax_identification
        nombre = "%s" % (
            "%s %s" %
            (invoice.auth_user.first_name, invoice.auth_user.last_name),
            invoice.fiscals.fiscalname)[invoice.fiscals.fiscalname != ""]
        domicilio = "%s" % invoice.fiscals.address
        domicilio2 = "%s %s %s" % (invoice.fiscals.postal_code,
                                   invoice.fiscals.city,
                                   invoice.fiscals.province)
        telefono = "%s" % invoice.fiscals.country
        fax = "%s" % invoice.fiscals.phone
        subtotal = "%.2f" % float(invoice.invoices.subtotal)
        totaldto = "%.2f" % float(invoice.invoices.discount)
        totaliva = "%.2f" % float(invoice.invoices.taxes)
        total = "%.2f" % float(invoice.invoices.subtotal)
        totalinvoice = "%.2f" % float(invoice.invoices.total)
        iva = "%.2f" % float(invoice.invoices.tax)
        totaliva = "%.2f" % float(invoice.invoices.taxes)
        items = []
        subtotal_no_dto = 0
        for item in 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)
                ]):

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

            subtotal_no_dto += item.orderlist.price * item.orderlist.quantity
            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.
                    dto="%.2f" % float(item.orderlist.dto_percentage) + "%",
                    total="%.2f" % (float(item.orderlist.quantity) *
                                    float(item.orderlist.price))))

        try:

            # Report creation
            template_file = os.path.join(request.folder, 'private',
                                         'factura.odt')
            # tmp_uuid = uuid.uuid4()
            output_file_odt = os.path.join(
                request.folder, 'private', 'tmp',
                '%s_%s.odt' % ("factura", invoice.invoices.id))
            output_file_pdf = os.path.join(
                request.folder, 'private', 'tmp',
                '%s_%s.pdf' % ("factura", invoice.invoices.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' % (
                    "factura", invoice.invoices.invoice_number)
            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