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)
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'))
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)
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)
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'))
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()
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'))
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'))
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())
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()
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)
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'))
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()
def delete_accountingentry(): if auth.has_membership('administradores') or auth.has_membership('superadministradores'): from invoices import Orderlist, AccountingEntry, CreditAccount Orderlist(db), AccountingEntry(db), CreditAccount(db) #comprobar que el AccountingEntry que se va a borrar es correcto try: accountingentry=db.accountingentries(request.vars.accountingentries) creditaccount=db.creditaccounts(accountingentry.creditaccount) balance=None if creditaccount.user==int(request.vars.customer): #buscar el primer accountingentry con ese orderlist y a partir de ese, la lista de accountingsentry con ese user hasta el final. accountingentries=db(db.accountingentries.id>=db((db.accountingentries.orderlist==accountingentry.orderlist) & (db.accountingentries.active==True)).select().first()['id']).select() #recorrer la lista for ae in accountingentries: #si coincide orderlist, quedarse con total*(-1), desactivar accountingentry if ae.orderlist==accountingentry.orderlist: if float(ae.total)>=0: total=float(ae.total)*(-1) else: total=0 #desactivar db(db.accountingentries.id==ae.id).update(active=False, deactivated_by=auth.user_id, deactivated_at=datetime.datetime.now()) #si no, sumarr a balance el total*(-1) else: aentry=db.accountingentries(ae.id) balance=float(aentry.balance)+total logger.debug("%s %s %s %s + %s = %s" % (aentry.id, total, aentry.balance, aentry.balance, total, balance)) aentry.update_record(balance=balance) #modificar balance de CreditAccount if balance!=None: db(db.creditaccounts.id==accountingentry.creditaccount).update(balance=balance) db.commit() return "ok" else: return "fail" except Exception as ex: db.rollback() logger.debug("Error delete_accountingentry %s" % ex) raise HTTP(500, ex) else: return "fail"
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()
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())
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:
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')
#*/1 * * * * cd /home/gextiendas/web2py && /usr/bin/python web2py.py -S gextiendas -M -R applications/gextiendas/private/managetools/managedomains_contracts.py >> /tmp/manage_domains_contracts.out 2>&1 #este cron busca dominios para activar/desactivar en tiendas # client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None") # client = SoapClient(wsdl="http://localhost:8000/internalgexcommerce/default/call/soap?WSDL=None") # logger.debug(client.addShopSite(auth.user_id)) #buscar contratos cuya fecha de expiración sea NULL o >= CURRENT_DATE() y plan distinto de NULL o free from gluon import * from shops import ContractedProduct, Product, PricePlan, Shop from invoices import Order, Orderlist contract = ContractedProduct(db) Product(db), PricePlan(db), Shop(db), Orderlist(db), Order(db) mcontracts = db( ((db.contractedproducts.expiration == None) | (db.contractedproducts.expiration >= datetime.datetime.now())) & ((db.profileplans.active == True) & (db.priceplans.planname != "free") & (db.contractedproducts.active == True))).select( db.contractedproducts.ALL, db.products.plan, db.products.price, db.products.suscription, db.products.name, db.priceplans.planname, db.priceplans.id, db.profileplans.ALL, db.orders.ALL,
def postcontracts(): import simplejson from dateutil.relativedelta import relativedelta if auth.has_membership('superadministradores') or auth.has_membership( 'administradores'): from shops import ContractedProduct, Product, Shop from invoices import Order, Orderlist, CreditAccount, AccountingEntry Order(db), Orderlist(db), Product(db), ContractedProduct(db), Shop(db) accounting = AccountingEntry(db) logger.debug(request.post_vars) data = simplejson.loads(request.post_vars.datacontracts) shopid = request.post_vars.shopid try: for d in data: #NO SE PUEDE HACER EL INSERT DIRECTAMENTE. HAY QUE VER SI EL SHOP YA TIENE CONTRATADO EL PRODUCTO. SI NO TIENE se hace un INSERT, si no, no hace nada. #Sólo se va a poder contratar una unidad y la recursividad y duración de la periodicidad harán el resto. orderlist = db(db.orderlist.id == int(d['orderlist'])).select( db.orderlist.ALL, db.products.ALL, db.orders.ALL, join=[ db.products.on(db.products.id == db.orderlist.product), db.orders.on(db.orders.id == db.orderlist.g_order) ]).first() contracted = db( (db.contractedproducts.shop == shopid) & (db.contractedproducts.user == session.usercontract) & (db.contractedproducts.product == orderlist.orderlist.product)).select().first() if not contracted: db.contractedproducts.insert( user=session.usercontract, product=orderlist.orderlist.product, period=orderlist.products. min_period, #optimizar para evitar más consultas autorenove=d['autorenove'], shop=shopid, orderlist=orderlist.orderlist.id, paymentmethod=orderlist.orders.payment_method, automatics_action=d['automatics_action'], notifications=d['notifications'], credit_annotation=d['credit_annotation'], invoice=request.vars.invoice) else: contracted.update_record( autorenove=d['autorenove'], automatics_action=d['automatics_action'], notifications=d['notifications'], credit_annotation=d['credit_annotation'], ) logger.debug("LLegoogoo1") #anotar crédito si orders pagado y si credit_annotation==True y si not in accountingentries if orderlist.orders.status == "Pagado" and d[ 'credit_annotation']: if not db((db.accountingentries.orderlist == orderlist.orderlist.id) & (db.accountingentries.active == True)).select( ).first(): logger.debug("LLegoogoo2") if not accounting.annotation( db.orderlist(orderlist.orderlist.id), db.orders(orderlist.orders.id), positive=True): raise Exception( "Ocurrió un error al hacer la anotación en postcontracts" ) logger.debug("LLegoogoo3") if contracted: if request.vars.invoice and contracted.invoice: if int(request.vars.invoice) > int( contracted.invoice): expiration = contracted.expiration if contracted.period == 'hours': #no usado por ahora inc = datetime.timedelta( hours=contracted.quantity) elif contracted.period == 'days': #no usado por ahora inc = datetime.timedelta( days=contracted.quantity) elif contracted.period == 'week': #no usado por ahora inc = datetime.timedelta( weeks=contracted.quantity) elif contracted.period == 'month': inc = relativedelta( months=contracted.quantity) horizon_date = 15 #15 días elif contracted.period == 'year': inc = relativedelta( years=contracted.quantity) horizon_date = 30 * 11 #días. No tengo en cuenta febreros ni bisiestos porque es sólo para hacer algo en 11 meses aprox. else: inc = datetime.timedelta(hours=0) if not accounting.annotation( db.orderlist( orderlist.orderlist.id), db.orders(orderlist.orders.id), positive=False): raise Exception( "Ocurrió un error al hacer la anotación en postcontracts" ) contracted.update_record( expiration=expiration + inc, invoice=request.vars.invoice) db.commit() session.flash = "Contratos creados correctamente" except Exception as ex: logger.debug("Se produjo un error en postcontracts %s" % ex) db.rollback() raise HTTP(500, ex) session.usercontract = None return "ok" else: return "no authorized"
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()
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)))
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'))
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
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'))
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'))
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()