def test_customer(self): from autonomie.models.customer import Customer print Customer.get(1) appstruct = {'name':u'Projéct&$', "code":"ABDC", "customers":["1"]} self.addOne(appstruct) project = self.getOne() self.assertEqual(len(project.customers), 1)
def submit_success(self, appstruct): customer = Customer() customer.company = self.request.context customer = merge_session_with_post(customer, appstruct) self.dbsession.add(customer) self.dbsession.flush() message = u"Le client <b>{0}</b> a été ajouté avec succès".format( customer.name) self.session.flash(message) return HTTPFound(self.request.route_path('customer', id=customer.id))
def test_customer_archive(customer, get_csrf_request_with_db): req = get_csrf_request_with_db() cid = customer.id from autonomie.views.customer import customer_archive req.context = customer req.referer = '/' customer_archive(req) req.dbsession.flush() assert Customer.get(cid).archived customer_archive(req) req.dbsession.flush() assert Customer.get(cid).archived is False
def add_customer(company, customer_name, customer_code, customer_lastname): customer = Customer() customer.name = customer_name #u"Institut médical Dupont & Dupond" customer.contactLastName = customer_lastname # "Dupont" customer.code = customer_code #"IMDD" customer.company = company session = DBSESSION() session.add(customer) session.flush() print u"Added customer to %s: %s" % (company.name, customer_name) return customer
def customer2(dbsession, company): from autonomie.models.customer import Customer customer = Customer( name=u"customer2", code=u"CUST", lastname=u"Lastname", firstname=u"Firstname", address=u"1th street", zip_code=u"01234", city=u"City", ) customer.company = company dbsession.add(customer) dbsession.flush() return customer
def customer2(dbsession, company2): from autonomie.models.customer import Customer customer = Customer( name=u"customer 2", code=u"CUST2", lastname=u"Lastname2", firstname=u"Firstname2", address=u"1th street", zip_code=u"01234", city=u"City", ) customer.company = company2 dbsession.add(customer) dbsession.flush() return customer
def submit_success(self, appstruct): log.debug("Submitting cancelinvoice add") appstruct = get_cancel_invoice_dbdatas(appstruct) customer_id = appstruct["task"]['customer_id'] customer = Customer.get(customer_id) cinvoice = CancelInvoice( self.context.company, customer, self.context, self.context.phases[0], self.request.user, ) cinvoice = merge_session_with_post( cinvoice, appstruct["task"] ) try: cinvoice = self.set_task_status(cinvoice) cinvoice.invoice.check_resulted(user_id=self.request.user.id) self.dbsession.merge(cinvoice.invoice) # Line handling cinvoice = add_lines_to_cancelinvoice(cinvoice, appstruct) self.dbsession.add(cinvoice) self.dbsession.flush() self.session.flash(u"L'avoir a bien été ajoutée.") except Forbidden, err: self.request.session.flash(err.message, queue='error')
def _get_company_customers(context): """ Return company customers :param obj context: The current Pyramid context :returns: A list of Customer instances :rtype: list """ company_id = context.get_company_id() customers = Customer.label_query() customers = customers.filter_by(company_id=company_id).all() if hasattr(context, "project_id"): # Si le contexte est attaché à un projet, on s'assure que les clients du # projet sont présentés en haut de la liste des clients en utilisant une # fonction de tri custom project_id = context.project_id def sort_pid_first(a, b): """ Sort customers moving the customers belonging to the current project up in the list """ if project_id in a.get_project_ids(): return -1 elif project_id in b.get_project_ids(): return 1 else: return 0 customers = sorted(customers, cmp=sort_pid_first) return customers
def submit_success(self, appstruct): log.debug("Submitting estimation add") appstruct = get_estimation_dbdatas(appstruct) customer_id = appstruct["task"]['customer_id'] customer = Customer.get(customer_id) estimation = Estimation( self.context.company, customer, self.context, self.context.phases[0], self.request.user, ) estimation = merge_session_with_post( estimation, appstruct['task'] ) try: # Line handling estimation = add_lines_to_estimation(estimation, appstruct) self.dbsession.add(estimation) self.dbsession.flush() estimation = self.set_task_status(estimation) self.session.flash(u"Le devis a bien été ajouté.") except Forbidden, err: self.request.session.flash(err.message, queue='error')
def submit_success(self, appstruct): log.debug("Submitting invoice add") appstruct = get_invoice_dbdatas(appstruct) customer_id = appstruct["task"]['customer_id'] customer = Customer.get(customer_id) invoice = Invoice( self.context.company, customer, self.context, self.context.phases[0], self.request.user, ) invoice = merge_session_with_post( invoice, appstruct["task"] ) try: invoice = self.set_task_status(invoice) # Line handling invoice = add_lines_to_invoice(invoice, appstruct) self.dbsession.add(invoice) self.dbsession.flush() self.session.flash(u"La facture a bien été ajoutée.") except Forbidden, err: self.request.session.flash(err.message, queue='error')
def submit_success(self, appstruct): if self.factory is None: raise Exception("Forgot to set the factory attribute") name = appstruct['name'] phase_id = appstruct['phase_id'] phase = Phase.get(phase_id) project_id = appstruct['project_id'] project = Project.get(project_id) customer_id = appstruct['customer_id'] customer = Customer.get(customer_id) new_object = self.factory( self.context.company, customer, project, phase, self.request.user, ) new_object.name = name if hasattr(self, "_more_init_attributes"): self._more_init_attributes(new_object, appstruct) self.dbsession.add(new_object) self.dbsession.flush() if hasattr(self, "_after_flush"): self._after_flush(new_object) url = self.request.route_path("/%ss/{id}" % new_object.type_, id=new_object.id) return HTTPFound(url)
def submit_success(self, appstruct): logger.debug("# Duplicating a document #") name = appstruct['name'] phase_id = appstruct['phase_id'] phase = Phase.get(phase_id) project_id = appstruct['project_id'] project = Project.get(project_id) customer_id = appstruct['customer_id'] customer = Customer.get(customer_id) task = self.context.duplicate( self.request.user, project, phase, customer, ) task.name = name task.course = appstruct['course'] self.dbsession.add(task) self.dbsession.flush() logger.debug( u"The {t.type_} {t.id} has been duplicated to {new_t.id}".format( t=self.context, new_t=task)) return HTTPFound( self.request.route_path('/%ss/{id}' % self.context.type_, id=task.id))
def submit_success(self, appstruct): if self.factory is None: raise Exception("Forgot to set the factory attribute") project_id = appstruct.pop('project_id') appstruct['project'] = Project.get(project_id) customer_id = appstruct.pop('customer_id') appstruct['customer'] = Customer.get(customer_id) new_object = self.factory( user=self.request.user, company=self.context.company, **appstruct ) if hasattr(self, "_more_init_attributes"): self._more_init_attributes(new_object, appstruct) self.dbsession.add(new_object) self.dbsession.flush() if hasattr(self, "_after_flush"): self._after_flush(new_object) url = self.request.route_path( "/%ss/{id}" % new_object.type_, id=new_object.id ) return HTTPFound(url)
def submit_success(self, appstruct): logger.debug("# Duplicating a document #") project_id = appstruct.pop('project_id') appstruct['project'] = Project.get(project_id) customer_id = appstruct.pop('customer_id') appstruct['customer'] = Customer.get(customer_id) task = self.context.duplicate( user=self.request.user, **appstruct ) if hasattr(self, "_after_task_duplicate"): self._after_task_duplicate(task, appstruct) self.dbsession.add(task) self.dbsession.flush() logger.debug( u"The {t.type_} {t.id} has been duplicated to {new_t.id}".format( t=self.context, new_t=task ) ) return HTTPFound( self.request.route_path( '/%ss/{id}' % self.context.type_, id=task.id ) )
def individual_customer(dbsession, company): from autonomie.models.customer import Customer customer = Customer( code=u"CUST", type_='individual', civilite=u"mr&mme", lastname=u"Lastname", firstname=u"Firstname", address=u"1th street", zip_code=u"01234", city=u"City", ) customer.company = company dbsession.add(customer) dbsession.flush() return customer
def get_customers_from_request(request): """ Get customers options for new task and task duplicate form Find customers regarding the current context Project -> Project.customers ... :returns: A list of customers :rtype: list """ from autonomie.models.customer import Customer from autonomie.models.task import Task customers = [] context = request.context if isinstance(context, Project): customers = context.customers elif isinstance(context, Task): customers = [context.customer] elif isinstance(context, Customer): customers = [context] elif hasattr(context, 'project') and context.project is not None: customers = context.project.customers else: company_id = request.current_company from autonomie.models.customer import Customer customers = Customer.query().filter_by(company_id=company_id).all() return customers
def deferred_customer_widget(node, kw): if is_admin: query = Customer.query().join(Customer.company) query = query.options( contains_eager(Customer.company).load_only('name') ) query = query.options(load_only('id', 'label')) datas = OrderedDict() for item in query: datas.setdefault(item.company.name, []).append( (item.id, item.label) ) # All customers, grouped by Company for company_name, customers in datas.items(): values.append( deform.widget.OptGroup( company_name, *customers ) ) else: # Company customers only company = kw['request'].context for cust in company.customers: values.append( (cust.id, u"%s (%s)" % (cust.name, cust.code)) ) return deform.widget.Select2Widget( values=values, **(widget_options or {}) )
def submit_success(self, appstruct): log.debug("Submitting cancelinvoice add") appstruct = get_cancel_invoice_dbdatas(appstruct) customer_id = appstruct["task"]['customer_id'] customer = Customer.get(customer_id) cinvoice = CancelInvoice( self.context.company, customer, self.context, self.context.phases[0], self.request.user, ) cinvoice = merge_session_with_post(cinvoice, appstruct["task"]) try: cinvoice = self.set_task_status(cinvoice) cinvoice.invoice.check_resulted(user_id=self.request.user.id) self.dbsession.merge(cinvoice.invoice) # Line handling cinvoice = add_lines_to_cancelinvoice(cinvoice, appstruct) self.dbsession.add(cinvoice) self.dbsession.flush() self.session.flash(u"L'avoir a bien été ajoutée.") except Forbidden, err: self.request.session.flash(err.message, queue='error')
def get_company_customers(kw): """ Retrieve all customers attached to a context's company """ from autonomie.models.customer import Customer request = kw['request'] company_id = request.context.get_company_id() return Customer.query().filter_by(company_id=company_id).all()
def migrate_datas(): from autonomie_base.models.base import DBSESSION session = DBSESSION() from autonomie.models.customer import Customer for customer in Customer.query().options( sa.orm.load_only("id", "name", "lastname", "firstname", "civilite", "type_")): customer.label = customer._get_label() session.merge(customer)
def deferred_customer_widget(node, kw): if default_option: values = [default_option] else: values = [] if is_admin: query = Customer.query().join(Customer.company) query = query.options( contains_eager(Customer.company).load_only('name') ) query = query.options(load_only('id', 'label')) if with_invoice: query = query.filter( Customer.id.in_( DBSESSION().query(distinct(Task.customer_id)).filter( Task.type_.in_(['invoice', 'cancelinvoice']) ) ) ) elif with_estimation: query = query.filter( Customer.id.in_( DBSESSION().query(distinct(Task.customer_id)).filter( Task.type_ == 'estimation' ) ) ) datas = OrderedDict() for item in query: datas.setdefault(item.company.name, []).append( (item.id, item.label) ) # All customers, grouped by Company for company_name, customers in datas.items(): values.append( deform.widget.OptGroup( company_name, *customers ) ) else: # Company customers only company = kw['request'].context for cust in company.customers: values.append( (cust.id, u"%s (%s)" % (cust.name, cust.code)) ) return deform.widget.Select2Widget( values=values, **(widget_options or {}) )
def add_customer( **kw): #company, customer_name, customer_code, customer_lastname): customer = Customer(**kw) session = DBSESSION() session.add(customer) session.flush() print u"Added customer to %s: %s" % (customer.company.name, customer.name) return customer
def _get_project_customers(project): """ Return project customers :param obj project: The current project :returns: A list of Customer instances :rtype: list """ query = Customer.label_query() customers = query.filter(Customer.projects.any(Project.id == project.id)) return customers
def deferred_fullcustomer_list_widget(node, kw): from autonomie.models.project import build_customer_values from autonomie.models.customer import Customer values = [('', u"Tous les clients")] for comp in Company.query().options(load_only("id", "name")): customers = Customer.label_query().filter_by(company_id=comp.id) values.append( deform.widget.OptGroup( comp.name, *build_customer_values(customers, default=False))) return deform.widget.Select2Widget(values=values, placeholder=u"Sélectionner un client")
def populate_db(session): from autonomie.models.user import User user = User( login='******', firstname='user1_firstname', lastname="user1_lastname", email="*****@*****.**" ) user.set_password('o') session.add(user) from autonomie.models.project import Project project = Project( name='Projet 1', code='P001', definition="Projet 1" ) session.add(project) from autonomie.models.customer import Customer cust = Customer( code='C001', name='Client1', contactLastName=u'Client Lastname', address=u'15 rue Victore Hugo', zipCode='69003', city='Lyon', ) cust.projects.append(project) session.add(cust) from autonomie.models.project import Phase phase = Phase(name='Phase de test') phase.project = project session.add(phase) from autonomie.models.company import Company c = Company( name="company1", goal="Company of user1", phone='0457858585', ) c.employees.append(user) c.customers.append(cust) c.projects.append(project) session.add(c) from autonomie.scripts import fake_database fake_database.set_configuration()
def customers(self): """ Return the number of real customers (with invoices) for the current year """ company_id = self.request.context.id result = 0 customers = Customer.query().filter(Customer.company_id==company_id) for customer in customers: for invoice in customer.invoices: if invoice.financial_year == self.year: if invoice.CAEStatus in Invoice.valid_states: result += 1 break return result
def customers(self): """ Return the number of real customers (with invoices) for the current year """ company_id = self.request.context.id result = 0 customers = Customer.query().filter(Customer.company_id == company_id) for customer in customers: for invoice in customer.invoices: if invoice.financial_year == self.year: if invoice.CAEStatus in Invoice.valid_states: result += 1 break return result
def submit_success(self, appstruct): """ Flush project edition to the database """ customer_ids = appstruct.pop("customers", []) project = merge_session_with_post(self.request.context, appstruct) project.customers = [] for customer_id in customer_ids: customer = Customer.get(customer_id) if customer is not None: project.customers.append(customer) self.dbsession.merge(project) self.dbsession.flush() message = u"Le projet <b>{0}</b> a été édité avec succès".format( project.name) self.request.session.flash(message) return HTTPFound(self.request.route_path('project', id=project.id))
def customer_objectify(id_): """ Objectify the associated form node schema (an id schemanode) Return the customer object with the given id_ Note : colanderalchemy schemanode is to a model and provides a objectify method used to convert an appstruct to the appropriate model. For the project->customer relationship, we need to be able to configure only existing elements. Since we didn't found a clear way to do it with colanderalchemy, we add the node manually and fit the colanderalchemy way of working by implementing usefull methods (namely objectify and dictify) """ obj = Customer.get(id_) return obj
def deferred_customer_widget(node, kw): if is_admin: # All customers, grouped by Company for comp in Company.query().options(load_only("id", "name")): customers = Customer.label_query().filter_by( company_id=comp.id, ) values.append( deform.widget.OptGroup(comp.name, *build_customer_values(customers))) else: # Company customers only company = kw['request'].context for cust in company.customers: values.append((cust.id, u"%s (%s)" % (cust.name, cust.code))) return deform.widget.Select2Widget(values=values, **(widget_options or {}))
def customer(dbsession): from autonomie.models.customer import Customer datas = { 'name': 'Company', 'contactLastName': u'Lastname', 'contactFirstName': u'FirstName', 'address': 'Address should be multiline', 'zipCode': "21000", "city": "Dijon", 'compte_cg': "Compte CG1515", 'compte_tiers': "Compte Tiers", 'code': 'CODE' } c = Customer(**datas) dbsession.add(c) dbsession.flush() return c
def unique_ccode(node, value): """ Test customer code unicity """ if len(value) != 4: message = u"Le code client doit contenir 4 caractères." raise colander.Invalid(node, message) #Test unicity query = Customer.query().filter(Customer.company_id == company_id)\ .filter(Customer.code == value) if customer: # In edit mode, it will always fail query = query.filter(Customer.id != customer.id) result = query.all() if len(result): message = u"Vous avez déjà utilisé ce code '{0}' pour un autre \ client".format(value) raise colander.Invalid(node, message)
def validate_customer_project_phase(form, value): """ Validate that customer project and phase are linked :param obj form: The form object :param dict value: The submitted values """ customer_id = value['customer_id'] project_id = value['project_id'] phase_id = value.get('phase_id') if phase_id and not Project.check_phase_id(project_id, phase_id): exc = colander.Invalid(form, u"Projet et dossier ne correspondent pas") exc['phase_id'] = u"Ne correspond pas au projet ci-dessus" raise exc if not Customer.check_project_id(customer_id, project_id): exc = colander.Invalid(form, u"Client et projet ne correspondent pas") exc['project_id'] = u"Ne correspond pas au client ci-dessus" raise exc
def get_customers_from_request(request): """ Extract a customers list from the request object :param obj request: The pyramid request object :returns: A list of customers :rtype: list """ if isinstance(request.context, Project): company_id = request.context.company.id elif isinstance(request.context, Company): company_id = request.context.id else: return [] customers = Customer.label_query() customers = customers.filter_by(company_id=company_id) customers = customers.filter_by(archived=False) return customers.order_by(Customer.label).all()
def pre_duplicate_process(self, task, status, params): """ Common pre process method for document duplication """ form = get_duplicate_form(self.request) # if an error is raised here, it will be cached a level higher appstruct = form.validate(params.items()) log.debug(u" * Form has been validated") customer_id = appstruct.get('customer') customer = Customer.get(customer_id) project_id = appstruct.get('project') project = Project.get(project_id) phase_id = appstruct.get('phase') phase = Phase.get(phase_id) log.debug(u" * Phase : %s" % phase) log.debug(u" * Project : %s" % project) appstruct['phase'] = phase appstruct['project'] = project appstruct['customer'] = customer appstruct['user'] = self.request.user return appstruct
def pre_duplicate_process(self, task, status, params): """ Common pre process method for document duplication """ form = get_duplicate_form(self.request) # if an error is raised here, it will be cached a level higher appstruct = form.validate(params.items()) logger.debug(u" * Form has been validated") customer_id = appstruct.get('customer') customer = Customer.get(customer_id) project_id = appstruct.get('project') project = Project.get(project_id) phase_id = appstruct.get('phase') phase = Phase.get(phase_id) logger.debug(u" * Phase : %s" % phase) logger.debug(u" * Project : %s" % project) appstruct['phase'] = phase appstruct['project'] = project appstruct['customer'] = customer appstruct['user'] = self.request.user return appstruct
def submit_success(self, appstruct): """ Add a project with a default phase in the database """ project = Project() project.company_id = self.request.context.id customer_ids = appstruct.pop("customers", []) project = merge_session_with_post(project, appstruct) for customer_id in customer_ids: customer = Customer.get(customer_id) if customer: project.customers.append(customer) self.dbsession.add(project) self.dbsession.flush() # Add a default phase to the project default_phase = Phase() default_phase.project = project self.dbsession.add(default_phase) message = u"Le projet <b>{0}</b> a été ajouté avec succès".format( project.name) self.request.session.flash(message) return HTTPFound(self.request.route_path('project', id=project.id))
def customer(content): res = Customer.query().first() res.code = "CLI1" return res
def getOne(): return Customer.query().filter(Customer.name == 'Company').one()
def customer(content): res = Customer.query().first() return res
def test_check_project_id(customer, project): from autonomie.models.customer import Customer assert Customer.check_project_id(customer.id, project.id) assert not Customer.check_project_id(customer.id, project.id + 1)
def getOne(): return Customer.query().filter(Customer.name=='Company').one()
def get_individual_customer(): return Customer.query().filter(Customer.lastname == 'Lastname 2').one()
def query(self): company = self.request.context return Customer.query().filter_by(company_id=company.id)
def query(self): company = self.request.context query = Customer.query().options(undefer_group('edit')) return query.filter(Customer.company_id == company.id)