def get_entry_models(self): yield AccountEntry yield PartnerEntry if dd.is_installed('ana'): yield AnaAccountEntry if dd.is_installed('sheets'): yield ItemEntry
def objects(): Partner = rt.models.contacts.Partner Person = rt.models.contacts.Person for ct in COMPANY_TYPES: yield companyType(**ct) # qs = rt.models.contacts.RoleType.objects.filter(rt.lookup_filter('name', "CEO")) # if qs.count(): # raise Exception("Oops, there is already a CEO in {}".format(qs)) # dd.logger.info("Creating the CEO function") yield roletype(**dd.str2kw('name', _("CEO"), can_sign=True)) yield roletype(**dd.str2kw('name', _("Director"), can_sign=True)) yield roletype(**dd.str2kw('name', _("Secretary"))) yield roletype(**dd.str2kw('name', _("IT manager"))) yield roletype(**dd.str2kw('name', _("President"), can_sign=True)) # yield roletype(**babel_values('name', en="Manager", fr='Gérant', de="Geschäftsführer", et="Tegevjuht")) # yield roletype(**babel_values('name', en="Director", fr='Directeur', de="Direktor", et="Direktor")) # yield roletype(**babel_values('name', en="Secretary", fr='Secrétaire', de="Sekretär", et="Sekretär")) # yield roletype(**babel_values('name', en="IT Manager", fr='Gérant informatique', de="EDV-Manager", et="IT manager")) # yield roletype(**babel_values('name', en="President", fr='Président', de="Präsident", et="President")) if dd.is_installed('excerpts') and dd.is_installed('appypod'): ExcerptType = rt.models.excerpts.ExcerptType ContentType = rt.models.contenttypes.ContentType yield ExcerptType( build_method='appypdf', template="TermsConditions.odt", content_type=ContentType.objects.get_for_model(Person), **dd.str2kw('name', _("Terms & conditions"))) if dd.is_installed('contenttypes'): # TODO: remove this because the feature isn't used. But afterwards adapt # the doctests! ContentType = rt.models.contenttypes.ContentType I = Instantiator('gfks.HelpText', 'content_type field help_text').build t = ContentType.objects.get_for_model(Person) #~ yield I(t,'birth_date',u"""\ #~ Unkomplette Geburtsdaten sind erlaubt, z.B. #~ <ul> #~ <li>00.00.1980 : irgendwann in 1980</li> #~ <li>00.07.1980 : im Juli 1980</li> #~ <li>23.07.0000 : Geburtstag am 23. Juli, Alter unbekannt</li> #~ </ul> #~ """) ct = ContentType.objects.get_for_model(Partner) yield I( ct, 'language', u"""\ Die Sprache, in der Dokumente ausgestellt werden sollen. """)
def update_item(self): if self.pk is None or not self.state.editable: return if self.items_edited or not self.edit_totals: return tt = self.journal.trade_type account = tt.get_partner_invoice_account(self.partner) if account is None: account = CommonAccounts.waiting.get_object() if account is None: raise Warning( _("{} is not configured").format( CommonAccounts.waiting)) kw = dict() if dd.is_installed('ana') and account.needs_ana: kw['ana_account'] = account.ana_account kw['account'] = account kw['total_incl'] = self.total_incl qs = self.items.all() if qs.count(): item = qs[0] for k, v in kw.items(): setattr(item, k, v) else: item = self.add_voucher_item(seqno=1, **kw) item.total_incl_changed(None) item.full_clean() item.save()
def get_milestone_users(self): #todo if dd.is_installed("stars"): for s in rt.models.stars.Star.for_obj(self): # u = obj.partner.get_as_user() # if u is not None: yield s.user
def get_overview_elems(self, ar): """Overrides :meth:`lino.core.model.Model.get_overview_elems`. """ elems = [ar.obj2html(self)] # show full summary # elems += [' ({})'.format(self.state.button_text)] # elems += [' ', self.state.button_text, ' '] if self.user and self.user != ar.get_user(): elems += [' ', _(" by "), self.user.obj2href(ar)] if self.end_user_id: elems += [' ', _("for"), ' ', self.end_user.obj2href(ar)] if dd.is_installed('votes'): qs = rt.models.votes.Vote.objects.filter(votable=self, state=VoteStates.assigned) if qs.count() > 0: elems += [', ', _("assigned to"), ' '] elems += join_elems([vote.user.obj2href(ar) for vote in qs], sep=', ') elif getattr(self, "assigned_to", None): elems += [ ", ", _("assigned to"), " ", self.assigned_to.obj2href(ar) ] return E.p(*forcetext(elems))
def save(self, *args, **kw): if not self.google_resourceName and self.name: body = {'names': [{'displayName': self.name, "givenName": self.last_name, "familyName": self.first_name}]} if self.email: body['emailAddresses'] = [{'value': self.email, 'type': 'work'}] if dd.is_installed('phones'): body.update( {'PhoneNumber': [{'value': self.phone, 'type': 'main'}, {'value': self.gsm, 'type': 'mobile'}]}) try: results = service.people().createContact(body=body).execute() if results and results.get('resourceName', False): self.google_resourceName = results.get('resourceName', False) self.google_contactID = results.get('resourceName', False).split('/')[1] except HttpError as e: print(e.content) elif self.google_resourceName: try: contactToUpdate = service.people().get(resourceName=self.google_resourceName, personFields='names,emailAddresses').execute() contactToUpdate['names'] = [ {'displayName': self.name, "givenName": self.last_name, "familyName": self.first_name}] service.people().updateContact(resourceName=self.google_resourceName, updatePersonFields='names,emailAddresses', body=contactToUpdate).execute() except HttpError as e: print(e.content) res = super(GooglePeople, self).save(*args, **kw) return res
class MembersByList(Members): label = _("Members") master_key = 'list' order_by = ['seqno'] if dd.is_installed("phones"): column_names = "seqno partner remark workflow_buttons partner__address_column partner__contact_details *" else: column_names = "seqno partner remark workflow_buttons partner__address_column partner__email partner__gsm *"
def get_wanted_movements(self): item_sums = self.get_payable_sums_dict() # logger.info("20120901 get_wanted_movements %s", sums_dict) counter_sums = SumCollector() partner = self.get_partner() has_vat = dd.is_installed('vat') kw = dict() for k, amount in item_sums.items(): # amount = myround(amount) # first item of each tuple k is itself a tuple (account, ana_account) acc_tuple, prj, vat_class, vat_regime = k account, ana_account = acc_tuple # if not isinstance(acc_tuple, tuple): # raise Exception("Not a tuple: {}".format(acc_tuple)) if not isinstance(account, rt.models.ledger.Account): raise Exception("Not an account: {}".format(account)) if has_vat: kw.update( vat_class=vat_class, vat_regime=vat_regime) if account.needs_partner: kw.update(partner=partner) yield self.create_movement( None, acc_tuple, prj, self.journal.dc, amount, **kw) counter_sums.collect(prj, amount) tt = self.get_trade_type() if tt is None: if len(counter_sums.items()): raise Warning("No trade type for {}".format(self)) return acc = self.get_trade_type().get_main_account() if acc is None: if len(counter_sums.items()): raise Warning("No main account for {}".format(tt)) return total_amount = 0 for prj, amount in counter_sums.items(): total_amount += amount yield self.create_movement( None, (acc, None), prj, not self.journal.dc, amount, partner=partner if acc.needs_partner else None, match=self.get_match()) if dd.plugins.ledger.worker_model \ and TradeTypes.clearings.main_account \ and self.payment_term_id and self.payment_term.worker: worker = self.payment_term.worker dc = self.journal.dc # one movement to nullify the credit that was booked to the partner account, # another movment to book it to the worker's account: yield self.create_movement( None, (acc, None), None, dc, total_amount, partner=partner, match=self.get_match()) yield self.create_movement( None, (TradeTypes.clearings.get_main_account(), None), None, not dc, total_amount, partner=worker, match=self.get_match())
def objects(): Account = rt.modules.accounts.Account JournalGroups = rt.modules.ledger.JournalGroups BankStatement = rt.modules.finan.BankStatement PaymentOrder = rt.modules.finan.PaymentOrder DisbursementOrdersByJournal = rt.modules.finan.DisbursementOrdersByJournal InvoicesByJournal = rt.modules.vatless.InvoicesByJournal ProjectInvoicesByJournal = rt.modules.vatless.ProjectInvoicesByJournal MatchRule = rt.modules.ledger.MatchRule a4400 = Account.objects.get(ref="4400") a4450 = Account.objects.get(ref="4450") a5800 = Account.objects.get(ref="5800") kw = dict(journal_group=JournalGroups.reg) kw.update(trade_type='purchases', ref="REG") kw.update(dd.str2kw('name', _("Incoming invoices"))) kw.update(dc=CREDIT) yield ProjectInvoicesByJournal.create_journal(**kw) kw.update(ref="SREG") kw.update(dd.str2kw('name', _("Collective purchase invoices"))) yield InvoicesByJournal.create_journal(**kw) kw.update(dd.str2kw('name', _("Disbursement orders"))) kw.update(account='4450', ref="AAW") kw.update(journal_group=JournalGroups.anw) # kw.update(dc=CREDIT) # kw.update(invert_due_dc=False) jnl = DisbursementOrdersByJournal.create_journal(**kw) yield jnl yield MatchRule(journal=jnl, account=a4400) if dd.is_installed('client_vouchers'): ClientVoucher = rt.modules.client_vouchers.ClientVoucher kw = dict(journal_group=JournalGroups.aids) kw.update(trade_type='aids', ref="AIDS") kw.update(dd.str2kw('name', _("Aid allocations"))) jnl = ClientVoucher.create_journal(**kw) yield jnl yield MatchRule(journal=jnl, account=a4400) kw = dict() # kw.update(journal_group=JournalGroups.tre) # kw.update(dd.str2kw('name', _("KBC"))) # kw.update(account='5500', ref="KBC") # jnl = BankStatement.create_journal(**kw) # yield jnl # yield MatchRule(journal=jnl, account=a4450) # yield MatchRule(journal=jnl, account=a5800) kw.update(journal_group=JournalGroups.zau) kw.update(dd.str2kw('name', _("KBC Payment Orders"))) kw.update(account='5800', ref="ZKBC") kw.update(dc=CREDIT) jnl = PaymentOrder.create_journal(**kw) yield jnl yield MatchRule(journal=jnl, account=a4450)
def objects(): if not dd.is_installed('excerpts'): return if not dd.is_installed('appypod'): return ContentType = rt.models.contenttypes.ContentType ExcerptType = rt.models.excerpts.ExcerptType yield ExcerptType( build_method='appyodt', #template='Default.odt', body_template='welcome.body.html', # certifying=True, primary=True, content_type=ContentType.objects.get_for_model(rt.models.users.User), **dd.str2kw('name', _("Welcome letter")))
def statements(self, ar): if ar is None or not dd.is_installed('b2c'): return '' Account = rt.modules.b2c.Account try: b2c = Account.objects.get(iban=self.iban) except Account.DoesNotExist: return '' return ar.obj2html(b2c, fds(b2c.last_transaction))
def statements(self, ar): if ar is None or not dd.is_installed('b2c'): return '' Account = rt.models.b2c.Account try: b2c = Account.objects.get(iban=self.iban) except Account.DoesNotExist: return '' return ar.obj2html(b2c, fds(b2c.last_transaction))
def objects(): Partner = rt.models.contacts.Partner Person = rt.models.contacts.Person for ct in COMPANY_TYPES: yield companyType(**ct) yield roletype(**babel_values('name', en="Manager", fr='Gérant', de="Geschäftsführer", et="Tegevjuht")) yield roletype(**babel_values('name', en="Director", fr='Directeur', de="Direktor", et="Direktor")) yield roletype(**babel_values('name', en="Secretary", fr='Secrétaire', de="Sekretär", et="Sekretär")) yield roletype(**babel_values('name', en="IT Manager", fr='Gérant informatique', de="EDV-Manager", et="IT manager")) yield roletype(**babel_values('name', en="President", fr='Président', de="Präsident", et="President")) if dd.is_installed('excerpts') and dd.is_installed('appypod'): ExcerptType = rt.models.excerpts.ExcerptType ContentType = rt.models.contenttypes.ContentType yield ExcerptType( build_method='appypdf', template="TermsConditions.odt", content_type=ContentType.objects.get_for_model(Person), **dd.str2kw('name', _("Terms & conditions"))) if dd.is_installed('contenttypes'): ContentType = rt.models.contenttypes.ContentType I = Instantiator('gfks.HelpText', 'content_type field help_text').build t = ContentType.objects.get_for_model(Person) #~ yield I(t,'birth_date',u"""\ #~ Unkomplette Geburtsdaten sind erlaubt, z.B. #~ <ul> #~ <li>00.00.1980 : irgendwann in 1980</li> #~ <li>00.07.1980 : im Juli 1980</li> #~ <li>23.07.0000 : Geburtstag am 23. Juli, Alter unbekannt</li> #~ </ul> #~ """) t = ContentType.objects.get_for_model(Partner) yield I(t, 'language', u"""\ Die Sprache, in der Dokumente ausgestellt werden sollen. """)
def objects(): if not dd.is_installed('excerpts'): return if not dd.is_installed('appypod'): return ContentType = rt.models.contenttypes.ContentType ExcerptType = rt.models.excerpts.ExcerptType yield ExcerptType( build_method='appyodt', #template='Default.odt', body_template='welcome.body.html', # certifying=True, primary=True, content_type=ContentType.objects.get_for_model( rt.models.users.User), **dd.str2kw('name', _("Welcome letter")))
def save_new_instance(elem, ar): super(Workable, elem).save_new_instance(ar) if rt.settings.SITE.loading_from_dump or not dd.is_installed('working'): return me = ar.get_user() # print elem.create_session_on_create if elem.create_session_on_create and me is not None and me.open_session_on_new_ticket: ses = rt.models.working.Session(ticket=elem, user=me) ses.full_clean() ses.save()
def get_simple_parameters(cls): for p in super(Tickets, cls).get_simple_parameters(): yield p yield 'end_user' yield 'state' yield 'project' yield 'topic' yield 'site' yield 'priority' if not dd.is_installed('votes'): yield 'assigned_to'
def get_simple_parameters(cls): for p in super(Tickets, cls).get_simple_parameters(): yield p yield 'end_user' yield 'state' # yield 'project' # yield 'topic' yield 'site' yield 'priority' yield 'last_commenter' if not dd.is_installed('votes'): yield 'assigned_to'
def after_ui_save(self, ar, cw): super(Comment, self).after_ui_save(ar, cw) if self.owner_id: self.owner.on_commented(self, ar, cw) if dd.is_installed("memo"): ref_objects = settings.SITE.plugins.memo.parser.get_referred_objects(self.body) for ref_object in ref_objects: created_mention = Mention(comment=self, owner_id=ref_object.pk, owner_type=ContentType.objects.get_for_model(ref_object.__class__)) created_mention.touch() created_mention.save()
class UploadController(dd.Model): class Meta(object): abstract = True def get_upload_area(self): return UploadAreas.general if dd.is_installed("uploads"): show_uploads = dd.ShowSlaveTable( 'uploads.UploadsByController', button_text=u"🖿") # u"\u1F5BF"
def add_company(self, name, url, **kw): if not dd.is_installed('vat'): kw.pop('vat_id', None) obj = Company(name=name, url=url, **kw) # if VatRegimes.is_installed(): # if dd.is_installed('bevats') or dd.is_installed('bevat'): # if obj.country.isocode == 'BE': # obj.vat_regime = VatRegimes.subject # else: # obj.vat_regime = VatRegimes.intracom self.current_partner = obj self.primary = True return obj
class HouseholdDetail(dd.DetailLayout): if dd.is_installed('addresses') and dd.is_installed('phones'): main = """ address_box bottom_box """ address_box = "overview:50 data_box:30" data_box = """ type prefix name language id """ else: main = """ type prefix name language:10 id address_box bottom_box """ address_box = "box3 contact_box" box3 = """ country region city zip_code:10 street_prefix street:25 street_no street_box addr2:40 """ contact_box = """ phone gsm email:40 url """ bottom_box = "#remarks households.MembersByHousehold"
def inject_partner_field(sender=None, **kwargs): User = sender.models.users.User if dd.is_installed('contacts'): Partner = sender.models.contacts.Partner if not issubclass(User, Partner): dd.inject_field(User, 'partner', dd.ForeignKey( 'contacts.Partner', blank=True, null=True, related_name='users_by_partner', on_delete=models.PROTECT)) # a related_name is needed so that Avanti can have aClient # who inherits from both Partner and UserAuthored return dd.inject_field(User, 'partner', dd.DummyField())
def site_company_objects(): company = Instantiator( 'contacts.Company', "name zip_code city:name street street_no", country='EE').build rumma = company( 'Rumma & Ko OÜ', '78003', 'Vigala', 'Uus tn', '1', url="http://www.saffre-rumma.net/") if dd.is_installed('vat'): rumma.vat_id = "EE100588749" # a vat_id is required for generating valid XML from payment order yield rumma settings.SITE.site_config.update(site_company=rumma)
def get_change_body(self, ar, cw): if cw is None: s = _("{user} commented on {obj}") else: s = _("{user} modified comment on {obj}") user = ar.get_user() s = s.format(user=user, obj=ar.obj2memo(self.owner)) if dd.is_installed("inbox"): #mailto:[email protected]?subject=SUBJECT&body=Filling%20in%20the%20Body!%0D%0Afoo%0D%0Abar s += ' <a href="{href}">{reply}</a>'.format( href=comment_email.gen_href(self, user), reply=_("Reply")) s += ':<br>' + self.body # if False: # s += '\n<p>\n' + self.more_text return s
def migrate_from_1_1_25(self, globals_dict): """ - rename PaymentInstructionsByJournal to DisbursementOrdersByJournal - remove all ledger vouchers - remove all plausibility problems because checker names have changed (please run yourself checkdata after migration) """ globals_dict.update(create_plausibility_problem=noop) if not dd.is_installed('ledger'): return '1.1.26' ledger_Journal = rt.modules.ledger.Journal bv2kw = globals_dict['bv2kw'] def create_ledger_journal(id, ref, build_method, template, seqno, name, trade_type, voucher_type, journal_group, auto_check_clearings, force_sequence, account_id, printed_name, dc): kw = dict() kw.update(id=id) kw.update(ref=ref) kw.update(build_method=build_method) kw.update(template=template) kw.update(seqno=seqno) if name is not None: kw.update(bv2kw('name',name)) kw.update(trade_type=trade_type) if voucher_type == 'finan.PaymentInstructionsByJournal': voucher_type = 'finan.DisbursementOrdersByJournal' kw.update(voucher_type=voucher_type) kw.update(journal_group=journal_group) kw.update(auto_check_clearings=auto_check_clearings) kw.update(force_sequence=force_sequence) kw.update(account_id=account_id) if printed_name is not None: kw.update(bv2kw('printed_name',printed_name)) kw.update(dc=dc) return ledger_Journal(**kw) globals_dict.update(create_ledger_journal=create_ledger_journal) globals_dict.update(create_ledger_voucher=noop) globals_dict.update(create_ledger_movement=noop) globals_dict.update(create_finan_bankstatement=noop) globals_dict.update(create_finan_bankstatementitem=noop) globals_dict.update(create_finan_journalentry=noop) globals_dict.update(create_finan_journalentryitem=noop) globals_dict.update(create_finan_paymentorder=noop) globals_dict.update(create_finan_paymentorderitem=noop) globals_dict.update(create_vatless_accountinvoice=noop) globals_dict.update(create_vatless_invoiceitem=noop) return '1.1.26'
def site_company_objects(): company = Instantiator('contacts.Company', "name zip_code city:name street street_no", country='EE').build rumma = company('Rumma & Ko OÜ', '78003', 'Vigala', 'Uus tn', '1', url="http://www.saffre-rumma.net/") if dd.is_installed('vat'): rumma.vat_id = "EE100588749" # a vat_id is required for generating valid XML from payment order yield rumma settings.SITE.site_config.update(site_company=rumma)
class Workable(dd.Model): class Meta: abstract = True create_session_on_create = False def get_ticket(self): return self def is_workable_for(self, user): return True if dd.is_installed('working'): start_session = StartTicketSession() end_session = EndTicketSession() def disabled_fields(self, ar): s = super(Workable, self).disabled_fields(ar) user = ar.get_user() if not (user.authenticated and self.is_workable_for(user)): s.add('start_session') s.add('end_session') return s Session = rt.models.working.Session qs = Session.objects.filter( user=user, ticket=self.get_ticket(), end_time__isnull=True) if qs.exists(): s.add('start_session') else: s.add('end_session') return s def save_new_instance(elem, ar): super(Workable, elem).save_new_instance(ar) if rt.settings.SITE.loading_from_dump or not dd.is_installed('working'): return me = ar.get_user() # print elem.create_session_on_create if elem.create_session_on_create and me is not None and me.open_session_on_new_ticket: ses = rt.models.working.Session(ticket=elem, user=me) ses.full_clean() ses.save()
def get_wanted_movements(self): """Implements :meth:`lino_xl.lib.ledger.Voucher.get_wanted_movements`. """ item_sums = self.get_payable_sums_dict() # logger.info("20120901 get_wanted_movements %s", sums_dict) counter_sums = SumCollector() partner = self.get_partner() has_vat = dd.is_installed('vat') kw = dict() for k, amount in item_sums.items(): # amount = myround(amount) acc_tuple, prj, vat_class, vat_regime = k # acc_tuple is a tuple (account, ana_account) if not isinstance(acc_tuple, tuple): raise Exception("Not a tuple: {}".format(acc_tuple)) if not isinstance(acc_tuple[0], rt.models.ledger.Account): raise Exception("Not an account: {}".format(acc_tuple[0])) if has_vat: kw.update( vat_class=vat_class, vat_regime=vat_regime) if acc_tuple[0].needs_partner: kw.update(partner=partner) yield self.create_movement( None, acc_tuple, prj, self.journal.dc, amount, **kw) counter_sums.collect(prj, amount) tt = self.get_trade_type() if tt is None: if len(counter_sums.items()): raise Warning("No trade type for {}".format(self)) return acc = self.get_trade_type().get_main_account() if acc is None: if len(counter_sums.items()): raise Warning("No main account for {}".format(tt)) else: for prj, amount in counter_sums.items(): # amount = myround(amount) yield self.create_movement( None, (acc, None), prj, not self.journal.dc, amount, partner=partner if acc.needs_partner else None, match=self.get_match())
def add_company(self, name, url, **kw): if not dd.is_installed('vat'): kw.pop('vat_id', None) obj = Company(name=name, url=url, **kw) # if VatRegimes.is_installed(): # if dd.is_installed('bevats') or dd.is_installed('bevat'): # if obj.country.isocode == 'BE': # obj.vat_regime = VatRegimes.subject # else: # obj.vat_regime = VatRegimes.intracom self.current_partner = obj self.primary = True # if dd.is_installed('vat') and obj.vat_id: # if obj.vat_id[:2] == obj.country.iso_code: # obj.vat_regime = rt.models.vat.VatRegimes.subject # else: # obj.vat_regime = rt.models.vat.VatRegimes.intracom return obj
def find_links(self, ar, child, parent): if not dd.is_installed('humanlinks'): return [] types = {} # mapping LinkType -> list of parents for lnk in rt.modules.humanlinks.Link.objects.filter(child=child): # child=child, parent=p): tt = lnk.type.as_child(lnk.child) l = types.setdefault(tt, []) l.append(lnk.parent) elems = [] for tt, parents in types.items(): if len(elems): elems.append(', ') text = join_elems( [parent.format_family_member(ar, p) for p in parents], sep=_(" and ")) elems += [tt, _(" of ")] + text return elems
def get_change_body(self, ar, cw): if cw is None: s = _("{user} commented on {obj}") else: s = _("{user} modified comment on {obj}") user = ar.get_user() s = s.format( user=user, obj=ar.obj2memo(self.owner)) if dd.is_installed("inbox"): #mailto:[email protected]?subject=SUBJECT&body=Filling%20in%20the%20Body!%0D%0Afoo%0D%0Abar s += ' <a href="{href}">{reply}</a>'.format( href=comment_email.gen_href(self, user), reply=_("Reply")) s += ':<br>' + self.body # if False: # s += '\n<p>\n' + self.more_text return s
class UnassignedTickets(Tickets): if dd.is_installed('votes'): column_names = "summary site user votes_by_ticket *" else: column_names = "summary site user assigned_to *" label = _("Unassigned Tickets") required_roles = dd.login_required(Triager) @classmethod def param_defaults(self, ar, **kw): kw = super(UnassignedTickets, self).param_defaults(ar, **kw) kw.update(show_assigned=dd.YesNo.no) # kw.update(show_private=dd.YesNo.no) # kw.update(show_active=dd.YesNo.yes) # kw.update(show_closed=dd.YesNo.no) kw.update(state=TicketStates.opened) return kw
def inject_partner_field(sender=None, **kwargs): User = sender.models.users.User if dd.is_installed('contacts'): Partner = sender.models.contacts.Partner if not issubclass(User, Partner): dd.inject_field( User, 'partner', dd.ForeignKey('contacts.Partner', blank=True, null=True, related_name='users_by_partner', on_delete=models.PROTECT)) # a related_name is needed so that Avanti can have aClient # who inherits from both Partner and UserAuthored return dd.inject_field(User, 'partner', dd.DummyField())
class PartnerDetailMixin(dd.DetailLayout): """Defines a panel :attr:`ledger`, to be added as a tab panel to your layout's `main` element. .. attribute:: ledger Shows the tables `VouchersByPartner` and `MovementsByPartner`. """ if dd.is_installed('ledger'): ledger = dd.Panel(""" payment_term vat.VouchersByPartner ledger.MovementsByPartner """, label=dd.plugins.ledger.verbose_name) else: ledger = dd.DummyPanel()
def find_links(self, ar, child, parent): if not dd.is_installed('humanlinks'): return [] types = {} # mapping LinkType -> list of parents for lnk in rt.models.humanlinks.Link.objects.filter(child=child): # child=child, parent=p): tt = lnk.type.as_child(lnk.child) l = types.setdefault(tt, []) l.append(lnk.parent) elems = [] for tt, parents in types.items(): if len(elems): elems.append(', ') text = join_elems( [parent.format_family_member(ar, p) for p in parents], sep=gettext(" and ")) elems += [tt, gettext(" of ")] + text return elems
def full_clean(self): """Copy data fields from child""" if self.person_id: for k in person_fields: setattr(self, k, getattr(self.person, k)) elif not settings.SITE.loading_from_dump: # create Person row if all fields are filled has_all_fields = True kw = dict() for k in person_fields: if getattr(self, k): kw[k] = getattr(self, k) else: has_all_fields = False if has_all_fields: # M = rt.models.pcsw.Client M = config.person_model try: obj = M.objects.get(**kw) except M.DoesNotExist: obj = M(**kw) obj.full_clean() obj.save() self.person = obj super(Member, self).full_clean() if not settings.SITE.loading_from_dump: # Auto-create human links between this member and other # household members. if self.person_id and self.role and self.household_id: if dd.is_installed('humanlinks'): Link = rt.models.humanlinks.Link ConcreteMember = rt.models.households.Member if self.role in child_roles: for pm in ConcreteMember.objects.filter( household=self.household, role__in=parent_roles): Link.check_autocreate(pm.person, self.person) elif self.role in parent_roles: for cm in ConcreteMember.objects.filter( household=self.household, role__in=child_roles): Link.check_autocreate(self.person, cm.person)
def full_clean(self): """Copy data fields from child""" if self.person_id: for k in person_fields: setattr(self, k, getattr(self.person, k)) elif not settings.SITE.loading_from_dump: # create Person row if all fields are filled has_all_fields = True kw = dict() for k in person_fields: if getattr(self, k): kw[k] = getattr(self, k) else: has_all_fields = False if has_all_fields: # M = rt.modules.pcsw.Client M = config.person_model try: obj = M.objects.get(**kw) except M.DoesNotExist: obj = M(**kw) obj.full_clean() obj.save() self.person = obj super(Member, self).full_clean() if not settings.SITE.loading_from_dump: # Auto-create human links between this member and other # household members. if self.person_id and self.role and self.household_id: if dd.is_installed('humanlinks'): Link = rt.models.humanlinks.Link ConcreteMember = rt.models.households.Member if self.role in child_roles: for pm in ConcreteMember.objects.filter( household=self.household, role__in=parent_roles): Link.check_autocreate(pm.person, self.person) elif self.role in parent_roles: for cm in ConcreteMember.objects.filter( household=self.household, role__in=child_roles): Link.check_autocreate(self.person, cm.person)
def after_ui_save(self, ar, cw): # Emits notification about the change to every observer. super(ChangeNotifier, self).after_ui_save(ar, cw) if not dd.is_installed('notify'): # happens e.g. in amici where we use calendar without notify return mt = self.get_notify_message_type() if mt is None: return def msg(user, mm): subject = self.get_change_subject(ar, cw) if not subject: return None return (subject, self.get_change_body(ar, cw)) # owner = self.get_change_owner() # rt.models.notify.Message.emit_notification( # ar, owner, mt, msg, self.get_change_observers(ar)) rt.models.notify.Message.emit_notification( ar, self, mt, msg, self.get_change_observers(ar))
def run_from_ui(self, ar, **kw): if not dd.is_installed('humanlinks'): return today = dd.today() n = 0 Member = rt.models.households.Member for hh in ar.selected_rows: known_children = set() for mbr in hh.member_set.filter(role__in=child_roles): if mbr.person: known_children.add(mbr.person.id) new_children = dict() for parent in hh.member_set.filter(role__in=parent_roles): for childlnk in parent.person.humanlinks_children.all(): child = childlnk.child if not child.id in known_children: age = child.get_age(today) if age is None or age <= dd.plugins.households.adult_age: childmbr = new_children.get(child.id, None) if childmbr is None: cr = MemberRoles.child # if parent.role == MemberRoles.head: # cr = MemberRoles.child_of_head # else: # cr = MemberRoles.child_of_partner childmbr = Member( household=hh, person=child, dependency=MemberDependencies.full, role=cr) new_children[child.id] = childmbr n += 1 else: childmbr.role = MemberRoles.child # if parent.role == MemberRoles.head: # childmbr.dependency = MemberDependencies.full childmbr.full_clean() childmbr.save() ar.success( _("Added %d children.") % n, refresh_all=True)
class Postable(dd.Model): """ Mixin for models that provide a "Post" button. """ class Meta: abstract = True if dd.is_installed('postings'): create_postings = CreatePostings() def get_postable_recipients(self): return [] def get_recipients(self): Posting = rt.models.postings.Posting qs = Posting.objects.filter( owner_id=self.pk, owner_type=ContentType.get_for_model( self.__class__)) return qs.values('partner')
def receive(self, text_data): try: data = json.loads(text_data) # logger.info("Recived WS data: " + text_data) user = self.scope.get('user', False) # Very Basic auth for confirming that this user is the on sending this message. if user: data["user"] = user if dd.is_installed("chat"): ChatMessage = rt.models.resolve( "chat.ChatMessage" ) # TODO HAVE WHITELIST OF FUNCTIONS! if data.get('function') and hasattr( ChatMessage, data.get('function')): getattr(ChatMessage, data.get('function'))(data) except Exception as E: logger.exception(E) raise E
def get_story(self, ar, header_level=None): # if header_level is None: # header = None # header = getattr(E, "h{}".format(header_level)) # pv = ar.param_values self.check_period_range() # bpv = dict(start_period=self.start_period, # end_period=self.end_period) balances = [] if True: balances.append(ar.spawn( AccountEntriesByReport, master_instance=self)) if dd.is_installed('ana'): balances.append(ar.spawn( AnaEntriesByReport, master_instance=self)) for tt in TradeTypes.get_list_items(): balances.append(ar.spawn( PartnerEntriesByReport, master_instance=self, param_values=dict(trade_type=tt))) balances.append(ar.spawn( BalanceEntriesByReport, master_instance=self, param_values=dict(sheet_type=SheetTypes.balance))) balances.append(ar.spawn( ResultsEntriesByReport, master_instance=self, param_values=dict(sheet_type=SheetTypes.results))) # for st in SheetTypes.get_list_items(): # balances.append(ar.spawn( # ItemEntriesByReport, # master_instance=self, # param_values=dict(sheet_type=st))) if True: for sar in balances: # if header: # yield header(str(sar.get_title())) yield sar
def objects(): TXT = Cycler( [styled, table, lorem, short_lorem, cond_comment, plain1, plain2]) if not dd.is_installed('tickets'): return OWNERS = Cycler(rt.models.tickets.Ticket.objects.all()) if len(OWNERS) == 0: return Comment = rt.models.comments.Comment User = rt.models.users.User for i in range(2): for u in User.objects.all(): owner = OWNERS.pop() if owner.private: txt = "<p>Very confidential comment</p>" else: txt = TXT.pop() # txt = "Hackerish comment" obj = Comment(user=u, owner=owner, body=txt) obj.before_ui_save(None) yield obj
def objects(): TXT = Cycler([styled, table, lorem, short_lorem, cond_comment, plain1, plain2]) if not dd.is_installed('tickets'): return OWNERS = Cycler(rt.models.tickets.Ticket.objects.all()) if len(OWNERS) == 0: return Comment = rt.models.comments.Comment User = rt.models.users.User for i in range(2): for u in User.objects.all(): owner = OWNERS.pop() if owner.private: txt = "<p>Very confidential comment</p>" else: txt = TXT.pop()# txt = "Hackerish comment" obj = Comment( user=u, owner=owner, body=txt) obj.before_ui_save(None) yield obj
def get_overview_elems(self, ar): """Overrides :meth:`lino.core.model.Model.get_overview_elems`. """ elems = [ ar.obj2html(self) ] # show full summary # elems += [' ({})'.format(self.state.button_text)] # elems += [' ', self.state.button_text, ' '] if self.user and self.user != ar.get_user(): elems += [ ' ', _(" by "), self.user.obj2href(ar)] if self.end_user_id: elems += [' ', _("for"), ' ', self.end_user.obj2href(ar)] if dd.is_installed('votes'): qs = rt.models.votes.Vote.objects.filter( votable=self, state=VoteStates.assigned) if qs.count() > 0: elems += [', ', _("assigned to"), ' '] elems += join_elems( [vote.user.obj2href(ar) for vote in qs], sep=', ') elif getattr(self, "assigned_to", None): elems += [", ", _("assigned to"), " ", self.assigned_to.obj2href(ar)] return E.p(*forcetext(elems))
constants = dd.Panel( """ system_note_type default_build_method propgroup_skills propgroup_softskills propgroup_obstacles residence_permit_upload_type \ work_permit_upload_type \ driving_licence_upload_type # client_calendar default_event_type prompt_calendar client_guestrole team_guestrole """, label=_("Constants")) cbss = dd.Panel( """ cbss_org_unit sector ssdn_user_id ssdn_email cbss_http_username cbss_http_password """, label=dd.apps.cbss.verbose_name, required_roles=dd.required(CBSSUser)) # When a Welfare Site decides to hide the "debts" app (as chatelet does) # then we must remove the `master_budget` field. # TODO: find a more elegant way to do this. if not dd.is_installed('debts'): SiteConfigDetail.general.replace('master_budget', '') class SiteConfigs(SiteConfigs): detail_layout = SiteConfigDetail()
def migrate_from_1_1_22(self, globals_dict): """- contenttypes.HelpText renamed to gfks.HelpText - Fields Partner.bic and Partner.iban no longer exist. Check whether sepa.Account exists. """ globals_dict.update(contenttypes_HelpText=rt.modules.gfks.HelpText) if dd.is_installed('sepa'): self.sepa_accounts = [] contacts_Partner = rt.modules.contacts.Partner def create_contacts_partner(id, modified, created, country_id, city_id, zip_code, region_id, addr1, street_prefix, street, street_no, street_box, addr2, name, language, email, url, phone, gsm, fax, remarks, is_obsolete, activity_id, client_contact_type_id, iban, bic): kw = dict() kw.update(id=id) kw.update(modified=modified) kw.update(created=created) kw.update(country_id=country_id) kw.update(city_id=city_id) kw.update(zip_code=zip_code) kw.update(region_id=region_id) kw.update(addr1=addr1) kw.update(street_prefix=street_prefix) kw.update(street=street) kw.update(street_no=street_no) kw.update(street_box=street_box) kw.update(addr2=addr2) kw.update(name=name) kw.update(language=language) kw.update(email=email) kw.update(url=url) kw.update(phone=phone) kw.update(gsm=gsm) kw.update(fax=fax) kw.update(remarks=remarks) kw.update(is_obsolete=is_obsolete) kw.update(activity_id=activity_id) kw.update(client_contact_type_id=client_contact_type_id) # kw.update(iban=iban) # kw.update(bic=bic) if iban: self.sepa_accounts.append((id, bic, iban)) return contacts_Partner(**kw) globals_dict.update(create_contacts_partner=create_contacts_partner) def check_sepa_accounts(loader): Account = rt.modules.sepa.Account for pk, bic, iban in self.sepa_accounts: try: Account.objects.get(partner_id=pk, bic=bic, iban=iban) except Account.MultipleObjectsReturned: pass except Account.DoesNotExist: obj = Account(partner_id=pk, bic=bic, iban=iban) obj.full_clean() obj.save() logger.info("20150825 created %s for partner #%s", obj, pk) self.after_load(check_sepa_accounts) return '1.1.23'
def tickets_objects(): # was previously in tickets User = rt.models.users.User Company = rt.models.contacts.Company Topic = rt.models.topics.Topic TT = rt.models.tickets.TicketType Ticket = rt.models.tickets.Ticket # Competence = rt.models.tickets.Competence Interest = rt.models.topics.Interest Milestone = dd.plugins.tickets.milestone_model # Milestone = rt.models.deploy.Milestone # Deployment = rt.models.deploy.Deployment # WishTypes = rt.models.deploy.WishTypes # Project = rt.models.tickets.Project # Site = rt.models.tickets.Site Site = dd.plugins.tickets.site_model Link = rt.models.tickets.Link LinkTypes = rt.models.tickets.LinkTypes Subscription = rt.models.tickets.Subscription #EntryType = rt.models.blogs.EntryType #Entry = rt.models.blogs.Entry # Star = rt.models.stars.Star # Tagging = rt.models.blogs.Tagging # Line = rt.models.courses.Line List = rt.models.lists.List cons = rt.models.users.UserTypes.consultant dev = rt.models.users.UserTypes.developer yield create_user("marc") yield create_user("mathieu", cons) yield create_user("luc", dev) yield create_user("jean", rt.models.users.UserTypes.senior) USERS = Cycler(User.objects.all()) WORKERS = Cycler(User.objects.filter( username__in='mathieu luc jean'.split())) END_USERS = Cycler(User.objects.filter(user_type='')) yield named(TT, _("Bugfix")) yield named(TT, _("Enhancement")) yield named(TT, _("Upgrade")) # sprint = named(Line, _("Sprint")) # yield sprint TYPES = Cycler(TT.objects.all()) yield Topic(name="Lino Core", ref="linõ") yield Topic(name="Lino Welfare", ref="welfäre") yield Topic(name="Lino Cosi", ref="così") yield Topic(name="Lino Voga", ref="faggio") # ref differs from name TOPICS = Cycler(Topic.objects.all()) RTYPES = Cycler(ReportingTypes.objects()) for name in "welket welsch pypi".split(): obj = Company(name=name) yield obj yield Site( name=name, company=obj, reporting_type=RTYPES.pop()) COMPANIES = Cycler(Company.objects.all()) yield Company(name="Saffre-Rumma") for u in Company.objects.exclude(name="pypi"): for i in range(3): yield Interest(owner=u, topic=TOPICS.pop()) # prj1 = Project( # name="Framewörk", ref="linö", private=False, # company=COMPANIES.pop(), # reporting_type=RTYPES.pop(), # start_date=i2d(20090101)) # yield prj1 # yield Project( # name="Téam", ref="téam", start_date=i2d(20100101), # reporting_type=RTYPES.pop(), # company=COMPANIES.pop(), # parent=prj1, private=True) # prj2 = Project( # name="Documentatión", ref="docs", private=False, # reporting_type=RTYPES.pop(), # company=COMPANIES.pop(), # start_date=i2d(20090101), parent=prj1) # yield prj2 # yield Project( # name="Research", ref="research", private=False, # company=COMPANIES.pop(), # start_date=i2d(19980101), parent=prj2) # yield Project( # name="Shop", ref="shop", private=False, # reporting_type=RTYPES.pop(), # company=COMPANIES.pop(), # start_date=i2d(20120201), end_date=i2d(20120630)) # PROJECTS = Cycler(Project.objects.all()) # for u in User.objects.all(): # yield Competence(user=u, project=PROJECTS.pop()) # yield Competence(user=u, project=PROJECTS.pop()) if dd.is_installed('meetings'): SITES = Cycler(Site.objects.exclude(name="pypi")) # LISTS = Cycler(List.objects.all()) for i in range(7): site = SITES.pop() d = dd.today(i*2-20) kw = dict( user=WORKERS.pop(), start_date=d, # line=sprint, # project=PROJECTS.pop(), # expected=d, reached=d, # expected=d, reached=d, name="{}@{}".format(d.strftime("%Y%m%d"), site), # list=LISTS.pop() ) kw[Milestone.site_field_name] = site yield Milestone(**kw) # yield Milestone(site=SITES.pop(), expected=dd.today()) # yield Milestone(project=PROJECTS.pop(), expected=dd.today()) SITES = Cycler(Site.objects.all()) TicketStates = rt.models.tickets.TicketStates TSTATES = Cycler(TicketStates.objects()) # Vote = rt.models.votes.Vote # VoteStates = rt.models.votes.VoteStates # VSTATES = Cycler(VoteStates.objects()) num = [0] def ticket(summary, **kwargs): num[0] += 1 u = WORKERS.pop() kwargs.update( ticket_type=TYPES.pop(), summary=summary, user=u, state=TSTATES.pop(), topic=TOPICS.pop()) if num[0] % 2: kwargs.update(site=SITES.pop()) if num[0] % 4: kwargs.update(private=True) else: kwargs.update(private=False) if num[0] % 5: kwargs.update(end_user=END_USERS.pop()) # if False: # kwargs.update(project=PROJECTS.pop()) obj = Ticket(**kwargs) yield obj # if obj.state.active: # yield Vote( # votable=obj, user=WORKERS.pop(), state=VSTATES.pop()) yield ticket("Föö fails to bar when baz") yield ticket("Bar is not always baz") yield ticket("Baz sucks") yield ticket("Foo and bar don't baz") yield ticket("Cannot create Foo", description="""<p>When I try to create a <b>Foo</b>, then I get a <b>Bar</b> instead of a Foo.</p>""") yield ticket("Sell bar in baz") yield ticket("No Foo after deleting Bar") yield ticket("Is there any Bar in Foo?") yield ticket("Foo never matches Bar") yield ticket("Where can I find a Foo when bazing Bazes?") yield ticket("Class-based Foos and Bars?") yield ticket("Foo cannot bar") # Example of memo markup: yield ticket("Bar cannot foo", description="""<p>Linking to [ticket 1] and to [url http://luc.lino-framework.org/blog/2015/0923.html blog].</p> """) yield ticket("Bar cannot baz") yield ticket("Bars have no foo") yield ticket("How to get bar from foo") TEXTS = Cycler(""" Foo never bars No more foo when bar is gone Cannot delete foo Why is foo so bar Irritating message when bar How can I see where bar? Misc optimizations in Baz Default account in invoices per partner 'NoneType' object has no attribute 'isocode' """.strip().splitlines()) # n = Ticket.objects.count() for i in range(100): # yield ticket("Ticket {}".format(i+n+1)) yield ticket(TEXTS.pop()) if dd.is_installed('meetings'): WTYPES = Cycler(WishTypes.objects()) MILESTONES = Cycler(Milestone.objects.all()) for t in Ticket.objects.all(): # t.set_author_votes() if t.id % 4: yield Deployment( milestone=MILESTONES.pop(), ticket=t, wish_type=WTYPES.pop()) yield Link( type=LinkTypes.requires, parent=Ticket.objects.get(pk=1), child=Ticket.objects.get(pk=2)) # yield EntryType(**dd.str2kw('name', _('Release note'))) # yield EntryType(**dd.str2kw('name', _('Feature'))) # yield EntryType(**dd.str2kw('name', _('Upgrade instruction'))) # ETYPES = Cycler(EntryType.objects.all()) # TIMES = Cycler('12:34', '8:30', '3:45', '6:02') #blogger = USERS.pop() # def entry(offset, title, body, **kwargs): # kwargs['user'] = blogger # kwargs['entry_type'] = ETYPES.pop() # kwargs['pub_date'] = dd.today(offset) # kwargs['pub_time'] = TIMES.pop() # return Entry(title=title, body=body, **kwargs) # yield entry(-3, "Hello, world!", "This is our first blog entry.") # e = entry(-2, "Hello again", "Our second blog entry is about [ticket 1]") # yield e # yield Interest(owner=e, topic=TOPICS.pop()) # e = entry(-1, "Our third entry", """\ # Yet another blog entry about [ticket 1] and [ticket 2]. # This entry has two taggings""") # yield e # yield Interest(owner=e, topic=TOPICS.pop()) # yield Interest(owner=e, topic=TOPICS.pop()) for U in User.objects.all(): if U.user_type >= rt.models.users.UserTypes.senior: for s in Site.objects.all(): yield Subscription(site=s, user=U)
# super(JournalGroup, self).__init__(value, text, name, **kwargs) class JournalGroups(dd.ChoiceList): item_class = JournalGroup verbose_name = _("Journal group") verbose_name_plural = _("Journal groups") required_roles = dd.login_required(LedgerStaff) add = JournalGroups.add_item add('10', _("Sales"), 'sales') add('20', _("Purchases"), 'purchases') add('30', _("Wages"), 'wages') add('40', _("Financial"), 'financial') add('50', _("VAT"), 'vat') if dd.is_installed("sales"): JournalGroups.sales.menu_group = dd.plugins.sales # JournalGroups.purchases.menu_group = dd.plugins.ledger class PeriodStates(dd.Workflow): pass add = PeriodStates.add_item add('10', _("Open"), 'open') add('20', _("Closed"), 'closed') class CommonAccount(dd.Choice): show_values = True clearable = False
# def get_change_observers(self, ar=None): # # in lino_welfare the project is pcsw.Client # prj = self.project # if isinstance(prj, ChangeNotifier): # for u in prj.get_change_observers(ar): # yield u def get_change_info(self, ar, cw): yield E.p( gettext("Subject"), ': ', self.subject, E.br(), gettext("Client"), ': ', ar.obj2memo(self.project)) if dd.is_installed('contacts'): dd.update_field( Note, 'company', verbose_name=_("Recipient (Organization)")) dd.update_field( Note, 'contact_person', verbose_name=_("Recipient (Person)")) class NoteDetail(dd.DetailLayout): main = """ date:10 time event_type:25 type:25 subject project company contact_person contact_role id user:10 language:8 build_time body:40 #outbox.MailsByController:40 """
topic = ticket.get_topic() if topic: qs = qs.filter( skills_competence_set_by_user__topic=topic) cond = models.Q() for dem in rt.models.skills.Demand.objects.filter( demander=ticket): skills = dem.skill.get_parental_line() cond |= models.Q( skills_competence_set_by_user__faculty__in=skills) qs = qs.filter(cond) qs = qs.order_by('skills_competence_set_by_user__affinity') return qs if dd.is_installed('tickets'): from lino_xl.lib.tickets.roles import Triager, Reporter from lino_xl.lib.tickets.ui import Tickets class SuggestedTicketsByEndUser(Tickets): """Shows the tickets of other users which need help on a faculty for which I am competent. """ master = dd.plugins.skills.end_user_model label = _("Where I can help") required_roles = dd.login_required(Reporter) column_names = 'detail_link:50 needed_skills ' \ 'workflow_buttons:30 *'
def objects(): ClientContactType = rt.modules.pcsw.ClientContactType Person = resolve_model('contacts.Person') Company = resolve_model('contacts.Company') #~ Contact = resolve_model('contacts.Contact') Role = resolve_model('contacts.Role') RoleType = resolve_model('contacts.RoleType') Authority = resolve_model('users.Authority') #~ Country = resolve_model('countries.Country') Client = resolve_model('pcsw.Client') person = Instantiator(Person).build client = Instantiator(Client).build company = Instantiator(Company).build #~ contact = Instantiator(Contact).build role = Instantiator(Role).build #~ link = Instantiator(Link).build #~ exam_policy = Instantiator('isip.ExamPolicy').build Place = resolve_model('countries.Place') #~ Job = resolve_model('jobs.Job') #~ Place = settings.SITE.modules.countries.Place StudyType = resolve_model('cv.StudyType') #~ Country = resolve_model('countries.Country') Property = resolve_model('properties.Property') eupen = Place.objects.get(name__exact='Eupen') #~ stvith = Place.objects.get(zip_code__exact='4780') stvith = Place.objects.get(name__in=('Sankt Vith', 'Saint-Vith')) kettenis = Place.objects.get(name__exact='Kettenis') vigala = Place.objects.get(name__exact='Vigala') ee = countries.Country.objects.get(pk='EE') be = belgium = countries.Country.objects.get(isocode__exact='BE') andreas = Person.objects.get(name__exact="Arens Andreas") annette = Person.objects.get(name__exact="Arens Annette") hans = Person.objects.get(name__exact="Altenberg Hans") ulrike = Person.objects.get(name__exact="Charlier Ulrike") erna = Person.objects.get(name__exact=u"Ärgerlich Erna") ## Coaching types # We use only abbreviated names in `CoachingType.name` because the # users usually know these abbrevs. kw = dd.str2kw('name', _("Colleague")) COLLEAGUE = cal.GuestRole(**kw) yield COLLEAGUE # id must match `isip.ContactBase.person_changed` ASD = pcsw.CoachingType( id=isip.COACHINGTYPE_ASD, does_integ=False, does_gss=True, eval_guestrole=COLLEAGUE, **dd.babelkw( 'name', de="ASD", # (Allgemeiner Sozialdienst) nl="ASD", # (Algemene Sociale Dienst) fr="SSG", # (Service social général) en="General", # (General Social Service) )) yield ASD DSBE = pcsw.CoachingType( id=isip.COACHINGTYPE_DSBE, does_gss=False, does_integ=True, eval_guestrole=COLLEAGUE, **dd.babelkw( 'name', de="DSBE", # (Dienst für Sozial-Berufliche Eingliederung) fr="SI", # Service intégration en="Integ", # Integration service )) yield DSBE DEBTS = pcsw.CoachingType( does_gss=False, does_integ=False, **dd.babelkw( 'name', de="Schuldnerberatung", fr="Médiation de dettes", en="Debts mediation", )) yield DEBTS melanie = person(first_name="Mélanie", last_name="Mélard", email=settings.SITE.demo_email, city=eupen, country='BE', gender=dd.Genders.female, language='fr') ## newcomers : Melanie does not work with newcomers because she is ## the boss. Hubert does live consultations (no appointments). And ## Alicia does only appointments but no life ## consultations. Caroline and Judith do both. yield melanie melanie = users.User( username="******", partner=melanie, profile='110', coaching_type=DSBE, newcomer_consultations=False, newcomer_appointments=False) yield melanie hubert = person(first_name=u"Hubert", last_name=u"Huppertz", email=settings.SITE.demo_email, city=kettenis, country='BE', gender=dd.Genders.male) yield hubert hubert = users.User( username="******", partner=hubert, profile='100', coaching_type=DSBE, newcomer_consultations=True, newcomer_appointments=False) yield hubert alicia = person( first_name=u"Alicia", last_name=u"Allmanns", email=settings.SITE.demo_email, city=kettenis, country='BE', # gender=dd.Genders.female, # don't set gender language='fr') yield alicia alicia = users.User( username="******", partner=alicia, profile='100', coaching_type=DSBE, newcomer_consultations=True, newcomer_appointments=True) yield alicia theresia = person(first_name="Theresia", last_name="Thelen", email=settings.SITE.demo_email, city=eupen, country='BE', gender=dd.Genders.female) yield theresia theresia = users.User(username="******", partner=theresia, profile='210') yield theresia nicolas = users.User(username="******", profile='') yield nicolas # yield Authority(user=alicia, authorized=hubert) # yield Authority(user=alicia, authorized=melanie) # yield Authority(user=hubert, authorized=melanie) yield Authority(user=hubert, authorized=theresia) yield Authority(user=alicia, authorized=theresia) yield Authority(user=melanie, authorized=theresia) caroline = users.User( username="******", first_name="Caroline", last_name="Carnol", profile='200', coaching_type=ASD, newcomer_consultations=True, newcomer_appointments=True) yield caroline obj = person(first_name="Judith", last_name="Jousten", email=settings.SITE.demo_email, city=eupen, country='BE', gender=dd.Genders.female) yield obj judith = users.User( username="******", partner=obj, profile='400', coaching_type=ASD, newcomer_consultations=True, newcomer_appointments=True) yield judith yield users.User( username="******", first_name="Patrick", last_name="Paraneau", profile='910', email=settings.SITE.demo_email) # for obj in pcsw.CoachingType.objects.all(): # yield users.Team(**dd.babelkw('name', **field2kw(obj, 'name'))) obj = cal.GuestRole( # email_template="Visitor.eml.html", **dd.babelkw( 'name', de="Besucher", fr="Visiteur", en="Visitor", et="Külaline", )) yield obj settings.SITE.site_config.update(client_guestrole=obj) yield cal.GuestRole(**dd.babelkw('name', de=u"Vorsitzender", fr=u"Président", en=u"Chairman", et=u"Eesistuja", )) yield cal.GuestRole(**dd.babelkw('name', de=u"Schriftführer", fr=u"Greffier", en=u"Reporter", et=u"Sekretär", )) calendar = Instantiator('cal.EventType').build kw = dict(invite_client=False, is_appointment=False) kw.update(dd.str2kw('name', _("Consultations with client"))) kw.update(dd.str2kw('event_label', _("Consultation"))) # kw.update(dd.babelkw( # 'name', # de="Visiten (ohne Verabredung)", # fr="Consultations sans rendez-vous", # en="Prompt consultation", # et="Külaline", # )) obj = calendar(**kw) yield obj settings.SITE.site_config.update(prompt_calendar=obj) kw = dict(invite_client=True) kw.update(dd.str2kw("name", _("External meetings with client"))) kw.update(dd.str2kw("event_label", _("External meeting"))) yield calendar(**kw) kw = dict(invite_client=True) kw.update(dd.str2kw("name", _("Informational meetings"))) kw.update(dd.str2kw("event_label", _("Informational meeting"))) yield calendar(**kw) kw = dict(invite_client=False) kw.update(dd.str2kw("name", _("Internal meetings"))) kw.update(dd.str2kw("event_label", _("Internal meeting"))) yield calendar(**kw) # yield calendar(**dd.babelkw('name', # de=u"Versammlung intern", # fr=u"Réunions internes", # en=u"Internal meetings")) kw = dict(invite_client=False) kw.update(dd.str2kw("name", _("External meetings"))) kw.update(dd.str2kw("event_label", _("External meeting"))) yield calendar(**kw) # yield calendar(**dd.babelkw('name', # de=u"Versammlung extern", # fr=u"Réunions externes", # en=u"External meetings")) kw = dict(invite_client=False) kw.update(dd.str2kw("name", _("Private"))) yield calendar(**kw) # yield calendar(**dd.babelkw('name', # de="Privat", # fr="Privé", # en="Private")) sector = Instantiator(cv.Sector).build for ln in SECTORS_LIST.splitlines(): if ln: a = ln.split('|') if len(a) == 3: kw = dict(en=a[0], fr=a[1], de=a[2]) yield sector(**dd.babelkw('name', **kw)) horeca = cv.Sector.objects.get(pk=5) function = Instantiator(cv.Function, sector=horeca).build yield function(**dd.babelkw('name', de=u"Kellner", fr=u'Serveur', en=u'Waiter', )) yield function(**dd.babelkw('name', de=u"Koch", fr=u'Cuisinier', en=u'Cook', )) yield function(**dd.babelkw('name', de=u"Küchenassistent", fr=u'Aide Cuisinier', en=u'Cook assistant', )) yield function(**dd.babelkw('name', de=u"Tellerwäscher", fr=u'Plongeur', en=u'Dishwasher', )) contractType = Instantiator(jobs.ContractType, "ref", exam_policy=3).build yield contractType('art60-7a', **dd.babelkw('name', de=u"Sozialökonomie", fr=u'économie sociale', en=u'social economy', )) yield contractType('art60-7b', **dd.babelkw('name', de=u"Sozialökonomie - majoré", fr=u'économie sociale - majoré', en=u'social economy - increased', )) yield contractType('art60-7c', **dd.babelkw('name', de=u"mit Rückerstattung", fr=u'avec remboursement', en=u'social economy with refund', )) yield contractType('art60-7d', **dd.babelkw('name', de=u"mit Rückerstattung Schule", fr=u'avec remboursement école', en=u'social economy school', )) yield contractType('art60-7e', **dd.babelkw('name', de=u"Stadt Eupen", fr=u"ville d'Eupen", en=u'town', )) contractType = Instantiator(isip.ContractType, "ref", exam_policy=1).build yield contractType("vsea", needs_study_type=True, **dd.babelkw( 'name', de=u"VSE Ausbildung", fr=u"VSE Ausbildung", en=u"VSE Ausbildung", )) yield contractType("vseb", **dd.babelkw('name', de=u"VSE Arbeitssuche", fr=u"VSE Arbeitssuche", en=u"VSE Arbeitssuche", )) yield contractType("vsec", **dd.babelkw('name', de=u"VSE Lehre", fr=u"VSE Lehre", en=u"VSE Lehre", )) yield contractType("vsed", needs_study_type=True, **dd.babelkw('name', de=u"VSE Vollzeitstudium", fr=u"VSE Vollzeitstudium", en=u"VSE Vollzeitstudium", )) yield contractType("vsee", **dd.babelkw('name', de=u"VSE Sprachkurs", fr=u"VSE Sprachkurs", en=u"VSE Sprachkurs", )) t = RoleType.objects.get(pk=4) # It manager t.use_in_contracts = False t.save() #~ country = Instantiator('countries.Country',"isocode name").build #~ yield country('SUHH',"Soviet Union") #~ cpas = company(name=u"ÖSHZ Eupen",city=eupen,country=belgium) cpas = company(name=u"ÖSHZ Kettenis", city=kettenis, country=belgium) yield cpas bisa = company(name=u"BISA", city=eupen, country=belgium) yield bisa bisa_dir = role(company=bisa, person=annette, type=1) yield bisa_dir rcycle = company(name=u"R-Cycle Sperrgutsortierzentrum", city=eupen, country=belgium) yield rcycle rcycle_dir = role(company=rcycle, person=andreas, type=1) yield rcycle_dir yield role(company=rcycle, person=erna, type=2) # IT manager : no contracts yield role(company=rcycle, person=ulrike, type=4) yield company(name=u"Die neue Alternative V.o.G.", city=eupen, country=belgium) proaktiv = company(name=u"Pro Aktiv V.o.G.", city=eupen, country=belgium) yield proaktiv proaktiv_dir = role(company=proaktiv, person=hans, type=1) # IT manager : no contracts yield role(company=proaktiv, person=ulrike, type=4) yield proaktiv_dir yield company(name=u"Werkstatt Cardijn V.o.G.", city=eupen, country=belgium) yield company(name=u"Behindertenstätten Eupen", city=eupen, country=belgium) yield company(name=u"Beschützende Werkstätte Eupen", city=eupen, country=belgium) kw = dd.str2kw('name', _("Health insurance")) cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium) #~ kw = dict(is_health_insurance=True,country=belgium) yield company(name="Alliance Nationale des Mutualités Chrétiennes", **kw) yield company(name="Mutualité Chrétienne de Verviers - Eupen", **kw) yield company(name="Union Nationale des Mutualités Neutres", **kw) yield company(name="Mutualia - Mutualité Neutre", **kw) yield company(name="Solidaris - Mutualité socialiste et syndicale de la province de Liège", **kw) fkw = dd.str2kw('name', _("Pharmacy")) # Apotheke cct = rt.modules.pcsw.ClientContactType.objects.get(**fkw) kw = dict(client_contact_type=cct, country=belgium, city=eupen) yield company( name="Apotheke Reul", street='Klosterstraße', street_no=20, **kw) yield company( name="Apotheke Schunck", street='Bergstraße', street_no=59, **kw) yield company( name="Pharmacies Populaires de Verviers", street='Aachener Straße', street_no=258, **kw) yield company( name="Bosten-Bocken A", street='Haasstraße', street_no=6, **kw) kw = dd.str2kw('name', _("Advocate")) cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium, city=eupen) yield company(name=u"Brüll Christine", street=u'Schilsweg', street_no=4, **kw) yield company(name=u"Brocal Catherine", street=u'Neustraße', street_no=115, **kw) yield company(name=u"Bourseaux Alexandre", street=u'Aachener Straße', street_no=21, **kw) yield company(name=u"Baguette Stéphanie", street=u'Gospertstraße', street_no=24, **kw) # Bailiff = Gerichtsvollzieher = Huissier de justice kw = dd.str2kw('name', _("Bailiff")) if dd.is_installed('debts'): kw.update(is_bailiff=True) cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium, city=eupen) yield company(name="Demarteau Bernadette", street='Aachener Straße', street_no=25, **kw) kw.update(city=stvith) yield company(name="Schmitz Marc", street='Rodter Straße', street_no=43, street_box="B", **kw) # Inkasso-Unternehmen kw = dd.str2kw('name', _("Debt collecting company")) if dd.is_installed('debts'): kw.update(is_bailiff=True) cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium, city=eupen) yield company(name="Cashback sprl", street='Vervierser Straße', street_no=1, **kw) yield company(name="Money Wizard AS", street='Neustraße', street_no=1, **kw) # settings.SITE.site_config.debts_bailiff_type = cct # yield settings.SITE.site_config def person2client(p, **kw): c = mti.insert_child(p, Client) for k, v in kw.items(): setattr(c, k, v) c.client_state = pcsw.ClientStates.coached c.save() return Client.objects.get(pk=p.pk) #~ luc = Person.objects.get(name__exact="Saffre Luc") #~ luc = person2client(luc,national_id = '680601 053-29') #~ luc.birth_place = 'Eupen' #~ luc.birth_date = '1968-06-01' #~ luc.birth_country = be #~ luc.full_clean() #~ luc.save() #~ #~ ly = person(first_name="Ly",last_name="Rumma", #~ city=vigala,country='EE', #~ gender=dd.Genders.female) #~ yield ly #~ mari = person(first_name="Mari",last_name="Saffre", #~ city=vigala,country='EE', #~ gender=dd.Genders.female) #~ yield mari #~ iiris = person(first_name="Iiris",last_name="Saffre", #~ city=vigala,country='EE', #~ gender=dd.Genders.female) #~ yield iiris gerd = person(first_name="Gerd", last_name="Gerkens", city=kettenis, email=settings.SITE.demo_email, # '*****@*****.**' country='BE', gender=dd.Genders.male) yield gerd yield role(company=cpas, person=gerd, type=4) # see :blogentry:`20111007` tatjana = client( first_name=u"Tatjana", last_name=u"Kasennova", #~ first_name=u"Татьяна",last_name=u"Казеннова", city=kettenis, country='BE', #~ national_id='1237', birth_place="Moskau", # birth_country='SUHH', client_state=pcsw.ClientStates.newcomer, #~ newcomer=True, gender=dd.Genders.female) yield tatjana michael = Person.objects.get(name__exact="Mießen Michael") jean = Person.objects.get(name__exact="Radermacher Jean") #~ yield cpas sc = settings.SITE.site_config sc.site_company = cpas sc.signer1 = michael sc.signer2 = jean yield sc yield role(company=cpas, person=michael, type=sc.signer1_function) yield role(company=cpas, person=jean, type=sc.signer2_function) bernard = Person.objects.get(name__exact="Bodard Bernard") kw = dd.str2kw('name', _("Employment office")) # Arbeitsvermittler cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium, city=eupen) adg = company(name=u"Arbeitsamt der D.G.", **kw) adg.save() yield adg settings.SITE.site_config.job_office = adg yield settings.SITE.site_config adg_dir = role(company=adg, person=bernard, type=1) yield adg_dir kw = dd.str2kw('name', _("Physician")) # Arzt if dd.is_installed('aids'): kw.update(can_refund=True) cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium, city=eupen) yield person(first_name="Waltraud", last_name="Waldmann", **kw) kw = dd.str2kw('name', _("Family doctor")) # Hausarzt if dd.is_installed('aids'): kw.update(can_refund=True) cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium, city=eupen) yield person(first_name="Werner", last_name="Wehnicht", **kw) kw = dd.str2kw('name', _("Dentist")) if dd.is_installed('aids'): kw.update(can_refund=True) cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium, city=eupen, title="Dr.") yield person(first_name="Carmen", last_name="Castou", **kw) yield person(first_name="Walter", last_name="Waldmann", **kw) kw = dd.str2kw('name', _("Pediatrician")) if dd.is_installed('aids'): kw.update(can_refund=True) cct = ClientContactType(**kw) yield cct kw = dict(client_contact_type=cct, country=belgium, city=eupen, title="Dr.") yield person(first_name="Killian", last_name="Kimmel", **kw) # kw = dd.str2kw('name', _("Landlord")) # Vermieter # if dd.is_installed('aids'): # kw.update(can_refund=True) # cct = ClientContactType(**kw) # yield cct # kw = dict(client_contact_type=cct, country=belgium, city=eupen) # yield person(first_name="Vera", last_name="Veltz", **kw) # yield person(first_name="Vanessa", last_name="Veithen", **kw) #~ from django.core.exceptions import ValidationError # ~ # a circular reference: bernard is contact for company adg and also has himself as `job_office_contact` #~ try: #~ bernard.job_office_contact = adg_dir #~ bernard.clean() #~ bernard.save() #~ except ValidationError: #~ pass #~ else: #~ raise Exception("Expected ValidationError") DIRECTORS = (annette, hans, andreas, bernard) #~ USERS = Cycler(root,melanie,hubert,alicia) AGENTS = Cycler(melanie, hubert, alicia, judith) COACHINGTYPES = Cycler(pcsw.CoachingType.objects.filter( does_gss=False, does_integ=False)) #~ CLIENTS = Cycler(andreas,annette,hans,ulrike,erna,tatjana) count = 0 #~ for person in Person.objects.filter(gender__isnull=False): for person in Person.objects.exclude(gender=''): if not person.birth_date: # not those from humanlinks if users.User.objects.filter(partner=person).count() == 0: if contacts.Role.objects.filter(person=person).count() == 0: birth_date = settings.SITE.demo_date(-170 * count - 16 * 365) national_id = generate_ssin(birth_date, person.gender) client = person2client(person, national_id=national_id, birth_date=birth_date) # youngest client is 16; 170 days between each client count += 1 if count % 2: client.client_state = pcsw.ClientStates.coached elif count % 5: client.client_state = pcsw.ClientStates.newcomer else: client.client_state = pcsw.ClientStates.former # Dorothée is three times in our database if client.first_name == "Dorothée": client.national_id = None client.birth_date = '' client.full_clean() client.save() #~ CLIENTS = Cycler(Client.objects.filter(is_active=True,newcomer=False)) CLIENTS = Cycler( Client.objects.filter(client_state=pcsw.ClientStates.coached)) #~ oshz = Company.objects.get(name=u"ÖSHZ Eupen") #~ project = Instantiator('projects.Project').build #~ note = Instantiator('notes.Note').build langk = Instantiator('cv.LanguageKnowledge').build #~ prj = project(name="Testprojekt",company=oshz) #~ yield prj #~ yield note(user=user,project=prj,date=i2d(20091006),subject="Programmierung",company=oshz) #~ prj = project(name="Testprojekt",company=oshz) #~ yield prj #~ yield note(user=user,project=prj,date=i2d(20091007),subject="Anschauen",company=oshz) Note = resolve_model('notes.Note') USERS = Cycler(users.User.objects.all()) SUBJECTS = Cycler(u""" Erstgespräch Versammlung beim AG Zwischenbericht Krisensitzung """.splitlines()) for i in range(10): yield Note(user=USERS.pop(), date=settings.SITE.demo_date(days=i), subject=SUBJECTS.pop()) schule = StudyType.objects.get(pk=1) # uni = StudyType.objects.get(pk=4) abi = u"Abitur" study = Instantiator('cv.Study').build gerd = CLIENTS.pop() luc = CLIENTS.pop() ly = CLIENTS.pop() mari = CLIENTS.pop() iiris = CLIENTS.pop() luc.card_number = '591413288107' luc.card_valid_from = i2d(20110819) luc.card_valid_until = i2d(20160819) luc.card_issuer = "Eupen" luc.card_type = BeIdCardTypes.belgian_citizen luc.save() luc.make_demo_picture() gerd.card_number = '123456789012' gerd.card_valid_from = i2d(20120819) gerd.card_valid_until = i2d(20130818) gerd.card_issuer = "Eupen" gerd.card_type = BeIdCardTypes.foreigner_c gerd.save() gerd.make_demo_picture() yield study(person=luc, type=schule, content=abi, start_date='19740901', end_date='19860630') yield study(person=gerd, type=schule, content=abi, start_date='19740901', end_date='19860630') yield langk(person=luc, language='ger', written='4', spoken='4') yield langk(person=gerd, language='ger', written='4', spoken='4') yield langk(person=mari, language='ger', written='2', spoken='4') yield langk(person=iiris, language='ger', written='0', spoken='4') yield langk(person=ly, language='ger', written='2', spoken='1') yield langk(person=luc, language='fre', written='4', spoken='3') yield langk(person=gerd, language='fre', written='4', spoken='3') yield langk(person=luc, language='eng', written='4', spoken='3') yield langk(person=gerd, language='eng', written='4', spoken='3') yield langk(person=ly, language='eng', written='3', spoken='3') yield langk(person=gerd, language='dut', written='3', spoken='3') yield langk(person=luc, language='est', written='3', spoken='3') yield langk(person=ly, language='est', written='4', spoken='4') yield langk(person=mari, language='est', written='3', spoken='4') yield langk(person=iiris, language='est', written='0', spoken='3') jobtype = Instantiator(jobs.JobType, 'name').build art607 = jobtype(u'Sozialwirtschaft = "majorés"') yield art607 yield jobtype(u'Intern') yield jobtype(u'Extern (Öffentl. VoE mit Kostenrückerstattung)') yield jobtype(u'Extern (Privat Kostenrückerstattung)') #~ yield jobtype(u'VSE') yield jobtype(u'Sonstige') rcycle = mti.insert_child(rcycle, jobs.JobProvider) yield rcycle bisa = mti.insert_child(bisa, jobs.JobProvider) yield bisa proaktiv = mti.insert_child(proaktiv, jobs.JobProvider) yield proaktiv # jobs (Art.60-7) CSTATES = Cycler(jobs.CandidatureStates.objects()) JOBS_CONTRACT_TYPES = Cycler(jobs.ContractType.objects.all()) JTYPES = Cycler(jobs.JobType.objects.all()) PROVIDERS = Cycler(jobs.JobProvider.objects.all()) SECTORS = Cycler(cv.Sector.objects.all()) FUNCTIONS = Cycler(cv.Function.objects.all()) REMARKS = Cycler( _("A very hard job."), '', _("No supervisor. Only for independent people."), '', '', '') for i in range(8): f = FUNCTIONS.pop() yield jobs.Job(provider=PROVIDERS.pop(), type=JTYPES.pop(), contract_type=JOBS_CONTRACT_TYPES.pop(), name=unicode(f), remark=REMARKS.pop(), sector=SECTORS.pop(), function=f) JOBS = Cycler(jobs.Job.objects.all()) for i in range(40): yield jobs.Candidature(job=JOBS.pop(), person=CLIENTS.pop(), state=CSTATES.pop(), date_submitted=settings.SITE.demo_date(-40 + i)) # reset SECTORS and FUNCTIONS SECTORS = Cycler(cv.Sector.objects.all()) FUNCTIONS = Cycler(cv.Function.objects.all()) obj = jobs.Offer( name="Übersetzer DE-FR (m/w)", remark="""\ Wir sind auf der Suche nach einem Deutsch-Französich Übersetzer (M/F) um einen Selbständigenr zu Geschäftsessen und kommerziellen Termine zu begleiten. Sie übernehmen die Übersetzung von Gespräche während kommerziellen Kontakte mit deutschen Kunden. Es ist spontane und pünktliche Aufträge, den ganzen Tag, in Eupen und/oder Deutschland. Regelmäßigkeit: 1-2 Mal pro Monat, je nach Bedarf. Flexibilität: die Termine sind je nach Kandidat anpassbar.""", provider=PROVIDERS.pop(), selection_from=settings.SITE.demo_date(-120), selection_until=settings.SITE.demo_date(-20), start_date=settings.SITE.demo_date(10), sector=SECTORS.pop(), function=FUNCTIONS.pop()) yield obj # reset SECTORS and FUNCTIONS SECTORS = Cycler(cv.Sector.objects.all()) FUNCTIONS = Cycler(cv.Function.objects.all()) for i in range(30): yield jobs.Candidature( person=CLIENTS.pop(), state=CSTATES.pop(), date_submitted=settings.SITE.demo_date(-20 + i * 2), sector=SECTORS.pop(), function=FUNCTIONS.pop(), ) COUNTRIES = Cycler(countries.Country.objects.all()) COMPANIES = Cycler(Company.objects.all()) # reset SECTORS and FUNCTIONS SECTORS = Cycler(cv.Sector.objects.all()) FUNCTIONS = Cycler(cv.Function.objects.all()) DURATIONS = Cycler([1, 2, 3, 6, 6, 9, 12, 12, 24, 24]) # months STATES = Cycler(cv.EducationEntryStates.items()) for i in range(30): start_date = settings.SITE.demo_date(-1200 + i * 2) d = DURATIONS.pop() end_date = DurationUnits.months.add_duration(start_date, d) yield cv.Experience( person=CLIENTS.pop(), company=COMPANIES.pop(), country=COUNTRIES.pop(), start_date=start_date, end_date=end_date, sector=SECTORS.pop(), function=FUNCTIONS.pop(), ) TRAINING_TYPES = Cycler(cv.StudyType.objects.filter(is_training=True)) for i in range(20): start_date = settings.SITE.demo_date(-1200 + i * 2) d = DURATIONS.pop() end_date = DurationUnits.months.add_duration(start_date, d) yield cv.Training( person=CLIENTS.pop(), type=TRAINING_TYPES.pop(), school=SCHOOLS.pop(), country=COUNTRIES.pop(), start_date=start_date, end_date=end_date, sector=SECTORS.pop(), function=FUNCTIONS.pop(), state=STATES.pop(), ) STUDY_TYPES = Cycler(cv.StudyType.objects.filter(is_study=True)) EDULEVELS = Cycler(cv.EducationLevel.objects.all()) for i in range(20): start_date = settings.SITE.demo_date(-1200 + i * 2) d = DURATIONS.pop() end_date = DurationUnits.months.add_duration(start_date, d) yield cv.Study( person=CLIENTS.pop(), type=STUDY_TYPES.pop(), school=SCHOOLS.pop(), country=COUNTRIES.pop(), start_date=start_date, end_date=end_date, state=STATES.pop(), education_level=EDULEVELS.pop(), ) #~ baker = Properties.objects.get(pk=1) #~ baker.save() #~ yield baker """ Distribute properties to persons. The distribution should be "randomly", but independant of site's language setting. """ for i, p in enumerate(Client.objects.all()): if i % 2: country = belgium else: country = COUNTRIES.pop() p.birth_country_id = country p.nationality_id = country if i % 3: p.languageknowledge_set.create( language_id='eng', written='3', spoken='3') elif i % 5: p.languageknowledge_set.create( language_id='eng', written='4', spoken='4') if p.zip_code == '4700': p.languageknowledge_set.create(language_id='ger', native=True) if i % 2: p.languageknowledge_set.create( language_id='fre', written='2', spoken='2') p.is_cpas = True #~ p.is_active = True #~ p.client_state = pcsw.ClientStates.coached #~ p.native_language_id = 'ger' p.save() for short_code, isocode in ( ('B', 'BE'), ('D', 'DE'), ('F', 'FR'), ): c = countries.Country.objects.get(pk=isocode) c.short_code = short_code c.save() i = pcsw.Client.objects.order_by('name').__iter__() p = i.next() offset = 0 for f in cv.Function.objects.all(): yield jobs.Candidature(person=p, function=f, sector=f.sector, #~ date_submitted=i2d(20111019)) date_submitted=settings.SITE.demo_date(offset)) p = i.next() offset -= 1 PERSONGROUPS = Cycler(pcsw.PersonGroup.objects.all()) AGENTS_SCATTERED = Cycler( alicia, hubert, melanie, caroline, hubert, melanie, hubert, melanie) ENDINGS = Cycler(pcsw.CoachingEnding.objects.all()) for client in pcsw.Client.objects.all(): story = COACHING_STORIES.get(client.client_state) if story: if not client.group: client.group = PERSONGROUPS.pop() PERSONGROUPS.pop() # ~ for i in range(5-client.group.id): PERSONGROUPS.pop() # client.save() periods = story.pop() type = COACHINGTYPES.pop() for a, b, primary, ct in periods: if ct == CT_OTHER: type = COACHINGTYPES.pop() elif ct == CT_GSS: type = ASD elif ct == CT_INTEG: type = DSBE kw = dict(client=client, user=AGENTS_SCATTERED.pop(), type=type, primary=primary) if a is not None: kw.update(start_date=settings.SITE.demo_date(a)) if b is not None: kw.update(end_date=settings.SITE.demo_date(b)) kw.update(ending=ENDINGS.pop()) yield pcsw.Coaching(**kw) # every 10th partner is obsolete for i, p in enumerate(contacts.Partner.objects.all()): if i % 10 == 0: p.is_obsolete = True p.save() # The reception desk opens at 8am. 20 visitors have checked in, # half of which RECEPTION_CLIENTS = Cycler(reception.Clients.request(user=theresia)) REASONS = Cycler(_("Urgent problem"), '', _("Complain"), _("Information")) today = settings.SITE.demo_date() now = datetime.datetime(today.year, today.month, today.day, 8, 0) for i in range(1, 20): obj = RECEPTION_CLIENTS.pop() now += datetime.timedelta(minutes=3 * i, seconds=3 * i) obj = reception.create_prompt_event( obj, obj, AGENTS.pop(), REASONS.pop(), settings.SITE.site_config.client_guestrole, now) yield obj # TODO: the following possibly causes more than one busy guest per # agent. qs = cal.Guest.objects.filter(waiting_since__isnull=False) busy_agents = set() for i, obj in enumerate(qs): busy_since = obj.waiting_since + \ datetime.timedelta(minutes=2 * i, seconds=2 * i) if i % 3 == 0: obj.gone_since = busy_since + \ datetime.timedelta(minutes=2 * i, seconds=3 * i) obj.state = cal.GuestStates.gone elif not obj.event.user in busy_agents: obj.busy_since = busy_since obj.state = cal.GuestStates.busy busy_agents.add(obj.event.user) yield obj Calendar = dd.resolve_model('cal.Calendar') COLORS = Cycler(Calendar.COLOR_CHOICES) for u in settings.SITE.user_model.objects.exclude(profile=None): obj = Calendar(name=u.username, color=COLORS.pop()) yield obj u.calendar = obj u.save() # create a primary ClientAddress for each Client. # no longer needed. done by plausibility.fixtures.demo2 # for obj in settings.SITE.modules.contacts.Partner.objects.all(): # obj.repairdata() # have partners speak different languages # most partners speak first language if len(settings.SITE.languages): ld = [] # language distribution ld = [settings.SITE.languages[0].django_code] * 10 if len(settings.SITE.languages) > 1: ld += [settings.SITE.languages[1].django_code] * 3 if len(settings.SITE.languages) > 2: ld += [settings.SITE.languages[2].django_code] LANGS = Cycler(ld) for obj in settings.SITE.modules.contacts.Partner.objects.all(): obj.language = LANGS.pop() obj.save()