Beispiel #1
0
def set_data_from_arr(data_arr):
    provinces_dict = {}
    cities_arr = []
    for city_dict in data_arr:
        city = City()
        city.set_city_from_dict(city_dict)
        city.get_total_scene_points()
        city.get_total_type_points()
        print(city.city_name)

        cities_arr.append(city)

        if city.city_province not in provinces_dict.keys():
            province = Province()
            province.province_name = city.city_province
        else:
            province = provinces_dict[city.city_province]

        province.add_city(city)

        if (city.city_name == '路凼填海区'):
            print('1', city.city_device_types_distribution)

        provinces_dict.update({province.province_name: province})
        if (city.city_name == '路凼填海区'):
            print('2', city.city_device_types_distribution)

    for city in cities_arr:
        if (city.city_name == '路凼填海区'):
            print('3', city.city_device_types_distribution)

    return cities_arr, provinces_dict
    def load_file_csv():
        with open('malopolska.csv', 'r') as file:
            reader = csv.reader(file, delimiter='\t')
            next(reader)

            province_name = ''
            province_type = ''
            district_name = ''
            district_type = ''

            for line in reader:
                if line[1] == '':
                    Province.province_list.append(
                        Province(line[0], line[4], line[5]))
                    province_name = line[4]
                    province_type = line[5]
                elif line[2] == '':
                    District.district_list.append(
                        District(line[0], province_name, province_type,
                                 line[1], line[4], line[5]))
                    district_name = line[4]
                    district_type = line[5]
                else:
                    Commune.commune_list.append(
                        Commune(line[0], province_name, province_type, line[1],
                                district_name, district_type, line[2], line[3],
                                line[4], line[5]))
Beispiel #3
0
def generateProvinces(colorSet):
    log(0, "Generating province data")
    provinces = []
    cpt = 1

    for color in colorSet:
        province = Province(cpt, color)

        if (province.type != "wasteland"):
            provinces.append(province)
            cpt += 1

    log(0, "Provinces generated")
    print('------------------------------')
    return provinces
Beispiel #4
0
    def __init__(self):
        self.read_locations = [
            Value("money", (170, 14, 215, 35)),
            Value("manpower", (254, 17, 300, 31)),
            #Value("stability", (420, 17, 446, 30)),
            Value("admin", (522, 58, 550, 70)),
            Value("diplo", (584, 58, 610, 70)),
            Value("mil", (641, 58, 666, 70))
        ]

        #pg init
        pg.init()
        self.screen = pg.display.set_mode((960, 540))
        self.clock = pg.time.Clock()
        pg.font.init()
        self.font = pg.font.Font('freesansbold.ttf', 8)
        self.frame_count = 0

        # EU4 init
        self.provinces = [""]
        provinces_txt = np.loadtxt('map/provinces.txt',
                                   dtype=str,
                                   delimiter=",")
        for p in provinces_txt:
            id = int(p[0])
            name = str(p[4])
            color_rgb = (int(p[1]), int(p[2]), int(p[3]))
            position = (int(p[5]), int(p[6]))
            self.provinces.append(Province(id, name, color_rgb, position))
        print(len(self.provinces))

        self.ongoing = True
        self.capital_id = 65
        while self.ongoing:
            if (self.frame_count % 10000 == 0):
                #self.get_values(self.read_locations)
                #self.draw_game(self.read_locations)

                pass
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.ongoing = False
            key = pg.key.get_pressed()
            if key[pg.K_q]:
                self.move_troops(134, 73)

            self.frame_count += 1
Beispiel #5
0
 def controlled(self):
     from province import Province
     return Province.objects(controller=self)
Beispiel #6
0
        def __init__(self):
            self.provinces = []
            self.provinces.append(Province('myrkulor', 3, ['manheim']))
            self.provinces.append(Province('elvagar', 4, ['manheim']))
            self.provinces.append(Province('angerboda', 5, ['manheim']))
            self.provinces.append(Province('anolang', 3, ['alfheim']))
            self.provinces.append(Province('gimle', 5, ['alfheim']))
            self.provinces.append(Province('utgard', 3, ['jotunheim']))
            self.provinces.append(Province('horgr', 4, ['jotunheim']))
            self.provinces.append(Province('muspelheim', 5, ['jotunheim']))
            self.provinces.append(Province('yggdrasil', 80, ['yggdrasil']))
            self.provinces.append(Province('ne', 5, ['manheim']))
            self.provinces.append(Province('nw', 5, ['manheim', 'alfheim']))
            self.provinces.append(Province('sw', 5, ['alfheim', 'jotunheim']))
            self.provinces.append(Province('se', 5, ['jotunheim']))

            self.valhalla = []
            self.provinces[8].set_pillage_reward(0)
            self.provinces[8].set_pillage_reward(1)
            self.provinces[8].set_pillage_reward(2)

            x = [0, 0, 0, 1, 1, 2, 2, 3]
            rewards = random.sample(x, 8)

            for i in range(8):
                self.provinces[i].set_pillage_reward(rewards[i])

            for i in range(9, 13):
                self.provinces[i].set_pillage_reward(4)
Beispiel #7
0
def index():
    from regnews import Regnews
    from mailboxing import Mailboxing
    from cities import Cities
    from province import Province
    from queuemail import Queuemail
    Province(db)
    Cities(db)
    Regnews(db)
    Mailboxing(db)
    Queuemail(db)

    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)

    name = Field('name',
                 'string',
                 label="Nombre",
                 length=50,
                 requires=IS_NOT_EMPTY(
                     error_message="Debe identificarse con un nombre"),
                 widget=lambda field, value: SQLFORM.widgets.string.widget(
                     field, value, _placeholder='Nombre y apellidos'))
    email = Field('email',
                  'string',
                  length=128,
                  requires=[
                      IS_NOT_EMPTY(error_message="Un email es requerido"),
                      IS_EMAIL(error_message="email incorrecto")
                  ],
                  widget=lambda field, value: SQLFORM.widgets.string.widget(
                      field, value, _placeholder='ejemplo: [email protected]'))
    phone = Field('phone', 'string', length=18, notnull=False)
    poblacion = Field('city',
                      'string',
                      length=40,
                      notnull=False,
                      widget=wpoblacion)
    provincia = Field('province',
                      'string',
                      length=40,
                      notnull=False,
                      widget=wprovincia)
    rnews = Field('rnews', 'boolean', default=True)
    message = Field(
        'message',
        'text',
        notnull=True,
        requires=IS_NOT_EMPTY(
            error_message=
            "Por favor, díganos por qué quiere contactar con nosotros."))
    form = SQLFORM.factory(name,
                           rnews,
                           email,
                           phone,
                           poblacion,
                           provincia,
                           message,
                           submit_button='contactar',
                           formstyle='bootstrap')

    queuedata = []
    if form.validate(keepvalues=False):
        data = form.vars
        try:

            reg = db(db.regnews.email == data.email).select()
            if len(reg) == 0:
                id = db.regnews.insert(email=data.email,
                                       name=data.name,
                                       news=data.rnews,
                                       phone=data.phone,
                                       city=data.city,
                                       province=data.province)
                db.mailbox.insert(regnews=id, message=data.message)
            else:
                db.mailbox.insert(regnews=reg[0].id, message=data.message)
            db.commit()
        except:
            db.rollback()
            response.flash = 'Su petición de contacto no pudo registrarse. Inténtelo de nuevo.'
        #primero encolamos el mail al usuario que ha hecho la petición de contacto
        queuedata.append({
            'to':
            '%s' % data.email,
            'subject':
            'Confirmación de petición de contacto',
            'message':
            'Estimado %s,\n hemos recibido una petición de contacto por parte suya desde el formulario de contacto de Despacho Cifrado.\n\n Muchas gracias por su interés. Le responderemos en breve.\n\n Reciba un cordial saludo.\n--\nDespacho Cifrado'
            % data.name
        })
        #y ahora notificación a cada uno de los administradores
        mails = db(db.auth_membership.group_id == 1).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:
            queuedata.append({
                'to':
                '%s' % m.auth_user.email,
                'subject':
                'Tienes una solicitud de contacto',
                'message':
                '%s con mail: %s y teléfono: %s  te ha enviado el siguiente mensaje: \n %s '
                % (data.name, data.email, data.phone, data.message)
            })
        try:
            logger.debug(queuedata)
            queue.queuemessage(queuedata)
        except Exception, ex:
            logger.debug("error al almacenar la cola de mensajes %s" % ex)
            pass
        session.flash = 'Su petición ha sido registrada'
        redirect(URL(request.application, 'default', 'index'))
Beispiel #8
0
 def domain(self):
     from province import Province
     return Province.objects(domain_of=self)
 def many2many(prop):
   province = Province.where(prop['x'], prop['y'])
   prop['provinces'] = province
   return prop
Beispiel #10
0
def editcustomer():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):
		if request.args(0):
			from invoices import Fiscal, Order, Orderlist, Invoice, Budget, AccountingEntry, CreditAccount
			from shops import ContractedProduct, Product, Shop
			from cities import Cities
			from province import Province
			Fiscal(db),	Province(db), Cities(db), ContractedProduct(db), Product(db), Shop(db), Order(db), Orderlist(db), AccountingEntry(db), CreditAccount(db),  Invoice(db), Budget(db)
			
			customer=db(db.auth_user.id==request.args(0)).select(	db.auth_user.id,
																	db.auth_user.first_name,
																	db.auth_user.last_name,
																	db.auth_user.email,
																	db.fiscals.ALL,
																	left=[db.fiscals.on(db.fiscals.user==db.auth_user.id)]).first()
			
			wpoblacion = SQLFORM.widgets.autocomplete(request, db.cities.poblacion, limitby=(0,10), min_length=2)
			wprovincia = SQLFORM.widgets.autocomplete(request, db.province.provincia, limitby=(0,10), min_length=2)


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

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

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

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

			if customer!=None:

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

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



				if form.validate(keepvalues=True):

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

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


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

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




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

			else:
				redirect(URL('administrator','newcustomer'))
		else:
			redirect(URL('administrator','users'))
Beispiel #11
0
def newcustomer():
	if auth.has_membership('administradores') or auth.has_membership('superadministradores'):

		from invoices import Fiscal
		from cities import Cities
		from province import Province
		Fiscal(db),	Province(db), Cities(db)

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

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



		if form.validate(keepvalues=True):

			try:
				userid=db.auth_user.insert(first_name=form.vars.first_name,
									last_name=form.vars.last_name,
									password=CRYPT(key=Auth.get_or_create_key(), digest_alg='pbkdf2(1000,20,sha512)', salt=True)(form.vars.password)[0],
									email=form.vars.email)
				if userid:
					db.fiscals.insert(	user=userid, 
										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)
					auth.add_membership(db(db.auth_group.role=="clientes").select().first()["id"], userid)
					db.commit()
				else:
					response.flash="no se ha creado al usario"

			except Exception, ex:
				logger.debug("No se pudo crear al nuevo cliente: %s" % ex)
				db.rollback()
				response.flash = 'Hubo un error: %s' % ex
			redirect(URL('administrator','editcustomer', args=userid))
		elif form.errors:
			response.flash = 'Hay errores'
		else:
			response.flash = 'Por favor completa los campos'
		
		form.element('input[name=city]')['_class']='form-control'
		form.element('input[name=province]')['_class']='form-control'
		
		return dict(form=form)
Beispiel #12
0
 def many2many(prop):
     province = Province.where(prop['x'], prop['y'])
     prop['provinces'] = province
     return prop
Beispiel #13
0
    def __init__(self, reset=False, preset=False):
        self.model = {
            'army': Army,
            'battle': Battle,
            'culture': Culture,
            'land': Land,
            'person': Person,
            'player': Player,
            'province': Province,
            'title': Title,
            'war': War,
        }
        connect('histemul')
        self.orders = {}

        if reset:
            client = MongoClient()
            db = client.histemul
            Player.drop_collection()
            Person.drop_collection()
            Army.drop_collection()
            Battle.drop_collection()
            War.drop_collection()

            Province.drop_collection()
            #collection = db.province_vo
            db.command('aggregate', 'province_vo', pipeline=[{'$match':{}}, {'$out': "province"}], allowDiskUse=True, cursor={})
            if preset:
                Matthieu = self.new_player('Matthieu', division='fess', tinctures=['green', 'orange'])
                Pierre = self.new_player('Pierre', division='pale', tinctures=['blue', 'red'])
                Robert = self.new_person('Robert', True, datetime.date(975, 1, 1), Matthieu, 1)
                Jean = self.new_person('Jean', True, datetime.date(981, 1, 1), Pierre, 14)
                Philippe = self.new_person('Philippe', True, datetime.date(965, 1, 1), Pierre, 39)
                Matthieu.leader = Robert
                Matthieu.save()
                Pierre.leader = Jean
                Pierre.save()

                Berquinais = Title.objects.get(pk='Berquinais')
                Berquinais.holder = Robert
                Berquinais.name_number = {'Robert': 1}
                Berquinais.save()

                Orvence = Title.objects.get(pk='Orvence')
                Orvence.holder = Jean
                Orvence.name_number = {'Jean': 1}
                Orvence.save()

                Bourquige = Title.objects.get(pk='Bourquige')
                Bourquige.holder = Philippe
                Bourquige.name_number = {'Philippe': 1}
                Bourquige.save()

                Berquinais_province = Province.objects.get(name='Berquinais')
                Berquinais_province.controller = Robert
                Berquinais_province.save()

                Orvence_province = Province.objects.get(name='Orvence')
                Orvence_province.controller = Jean
                Orvence_province.save()

                Bourquige_province = Province.objects.get(name='Bourquige')
                Bourquige_province.controller = Philippe
                Bourquige_province.save()

                Army_Orvence = self.rally_troops(Pierre, Orvence_province, 'execute')
Beispiel #14
0
 def location(self):
     from province import Province
     return Province.objects(location=self).first()
Beispiel #15
0
import os
import socket
import datetime
import copy
import gluon.contenttype
import gluon.fileutils

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

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

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

global_env = copy.copy(globals())
global_env['datetime'] = datetime
Beispiel #16
0
def fiscal():
    from invoices import Fiscal
    from cities import Cities
    from province import Province
    Fiscal(db), Province(db), Cities(db)

    fiscal = db(db.fiscals.user == auth.user_id).select().first()
    logger.debug(fiscal)
    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)
    if request.vars.wizard:
        wizard = request.vars.wizard
    else:
        wizard = False
    if fiscal:
        tax_identification = Field(
            'tax_identification',
            'string',
            label=XML(
                "<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"
            ),
            default=fiscal.tax_identification,
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        fiscalname = Field('fiscalname',
                           'string',
                           label=XML("<strong>Nombre empresa</strong>"),
                           default=fiscal.fiscalname,
                           length=128,
                           notnull=False)
        address = Field(
            'address',
            'string',
            label=XML("<strong>Dirección</strong>"),
            default=fiscal.address,
            length=250,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        city = Field(
            'city',
            'string',
            label=XML("<strong>Ciudad/Población</strong>"),
            default=fiscal.city,
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wpoblacion)
        province = Field('province',
                         'string',
                         label=XML("<strong>Provincia</strong>"),
                         default=fiscal.province,
                         notnull=False,
                         widget=wprovincia)
        country = Field(
            'country',
            'string',
            label=XML("<strong>Pais</strong>"),
            length=45,
            default=fiscal.country,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        postalcode = Field(
            'postal_code',
            'string',
            label=XML("<strong>Código postal</strong>"),
            default=fiscal.postal_code,
            length=10,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        phone = Field('phone',
                      'string',
                      label=XML("<strong>Teléfono de contacto</strong>"),
                      length=20,
                      default=fiscal.phone,
                      notnull=False)
    else:
        tax_identification = Field(
            'tax_identification',
            'string',
            label=XML(
                "<strong>NIF/CIF/NIE</strong> <span class='glyphicon glyphicon-question-sign'></span>"
            ),
            length=45,
            notnull=True,
            requires=IS_NOT_EMPTY(error_message="No olvide esta dato"))
        fiscalname = Field('fiscalname',
                           'string',
                           label=XML("<strong>Nombre empresa</strong>"),
                           length=128,
                           notnull=False)
        address = Field(
            'address',
            'string',
            label=XML("<strong>Dirección</strong>"),
            length=196,
            notnull=True,
            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,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"),
            widget=wpoblacion)
        province = Field('province',
                         'string',
                         label=XML("<strong>Provincia</strong>"),
                         length=45,
                         notnull=False,
                         widget=wprovincia)
        country = Field(
            'country',
            'string',
            label=XML("<strong>Pais</strong>"),
            length=45,
            notnull=True,
            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=True,
            requires=IS_NOT_EMPTY(error_message="no olvide este dato"))
        phone = Field('phone',
                      'string',
                      label=XML("<strong>Teléfono de contacto</strong>"),
                      length=20,
                      notnull=False)

    form = SQLFORM.factory(tax_identification,
                           fiscalname,
                           address,
                           city,
                           province,
                           country,
                           postalcode,
                           phone,
                           submit_button=('enviar datos',
                                          'siguiente')[wizard == True],
                           formstyle='bootstrap3_inline')

    if form.validate(keepvalues=True):
        if fiscal:  #update
            db(db.fiscals.id == fiscal.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)
        else:  #insert
            db.fiscals.insert(user=auth.user_id,
                              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)
        session.flash = "Datos enviados correctamente"
        if wizard:
            redirect(URL(request.application, 'payment', 'index'))
        else:
            redirect(URL('account'))

    elif form.errors:
        response.flash = 'Hay errores'

    form.element('input[name=city]')['_class'] = 'form-control'
    form.element('input[name=province]')['_class'] = 'form-control'
    form.element('div#no_table_tax_identification__row div.col-sm-9'
                 )['_class'] = 'col-sm-3'
    form.element(
        'div#no_table_fiscalname__row div.col-sm-9')['_class'] = 'col-sm-4'
    form.element('div#no_table_city__row div.col-sm-9')['_class'] = 'col-sm-4'
    form.element(
        'div#no_table_province__row div.col-sm-9')['_class'] = 'col-sm-3'
    form.element(
        'div#no_table_country__row div.col-sm-9')['_class'] = 'col-sm-2'
    form.element(
        'div#no_table_postal_code__row div.col-sm-9')['_class'] = 'col-sm-2'
    form.element('div#no_table_phone__row div.col-sm-9')['_class'] = 'col-sm-4'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'
    # form.element('label.col-lg-2')['_class']='col-lg-3 control-label'

    return dict(form=form)
Beispiel #17
0
def myaccount():
    from invoices import Fiscal
    from cities import Cities
    from province import Province
    Fiscal(db), Province(db), Cities(db),

    customer = db(db.auth_user.id == auth.user_id).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)

    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='modificar 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 modificados correctamente"
        elif form.errors:
            response.flash = 'Hay errores'
        else:
            response.flash = 'Por favor completa los campos'

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

        form.element('input[name=city]')['_class'] = 'form-control'
        form.element('input[name=province]')['_class'] = 'form-control'
        form.element(
            'div#no_table_first_name__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_last_name__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element('div#no_table_tax_identification__row div.col-sm-9'
                     )['_class'] = 'col-sm-3'
        form.element(
            'div#no_table_fiscalname__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_city__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element(
            'div#no_table_province__row div.col-sm-9')['_class'] = 'col-sm-3'
        form.element(
            'div#no_table_country__row div.col-sm-9')['_class'] = 'col-sm-2'
        form.element('div#no_table_postal_code__row div.col-sm-9'
                     )['_class'] = 'col-sm-2'
        form.element(
            'div#no_table_phone__row div.col-sm-9')['_class'] = 'col-sm-4'
        form.element('label#no_table_first_name__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_last_name__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_email__label')['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_fiscalname__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_tax_identification__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_address__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_city__label')['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_province__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_country__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element('label#no_table_postal_code__label'
                     )['_class'] = 'col-sm-2 control-label'
        form.element(
            'label#no_table_phone__label')['_class'] = 'col-sm-2 control-label'
        form.element('div#submit_record__row div.col-sm-9'
                     )['_class'] = 'col-sm-9 col-sm-offset-2'
        return dict(form=form, userid=customer.auth_user.id)