def objects(): Member = rt.modules.households.Member MemberRoles = rt.modules.households.MemberRoles # Household = resolve_model('households.Household') Person = resolve_model(dd.plugins.households.person_model) Type = resolve_model('households.Type') MEN = Cycler(Person.objects.filter(gender=dd.Genders.male).order_by('-id')) WOMEN = Cycler( Person.objects.filter(gender=dd.Genders.female).order_by('-id')) TYPES = Cycler(Type.objects.all()) ses = rt.login() for i in range(5): pv = dict(head=MEN.pop(), partner=WOMEN.pop(), type=TYPES.pop()) ses.run(Person.create_household, action_param_values=pv) # yield ses.response['data_record'] # he = MEN.pop() # she = WOMEN.pop() # fam = Household(name=he.last_name + "-" + she.last_name, type_id=3) # yield fam # yield Member(household=fam, person=he, role=Role.objects.get(pk=1)) # yield Member(household=fam, person=she, role=Role.objects.get(pk=2)) i = 0 for m in Member.objects.filter(role=MemberRoles.head): i += 1 if i % 3 == 0: m.end_date = i2d(20020304) yield m pv = dict(head=m.person, partner=WOMEN.pop(), type=TYPES.pop()) ses.run(Person.create_household, action_param_values=pv)
def objects(): Member = rt.modules.households.Member MemberRoles = rt.modules.households.MemberRoles # Household = resolve_model('households.Household') Person = dd.plugins.households.person_model Type = resolve_model('households.Type') men = Person.objects.filter(gender=dd.Genders.male).order_by('-id') women = Person.objects.filter(gender=dd.Genders.female).order_by('-id') # avoid interference with persons created by humanlinks demo # because these have already their households: men = men.filter(household_members__isnull=True) men = men.filter(humanlinks_children__isnull=True) men = men.filter(humanlinks_parents__isnull=True) women = women.filter(humanlinks_children__isnull=True) women = women.filter(humanlinks_parents__isnull=True) women = women.filter(household_members__isnull=True) MEN = Cycler(men) WOMEN = Cycler(women) TYPES = Cycler(Type.objects.all()) if not len(MEN) or not len(WOMEN): raise Exception("Not enough persons in {} and {} (all: {})".format( men, women, Person.objects.all())) # avoid automatic creation of children # loading_from_dump = settings.SITE.loading_from_dump # settings.SITE.loading_from_dump = True ses = rt.login() for i in range(5): pv = dict(head=MEN.pop(), partner=WOMEN.pop(), type=TYPES.pop()) ses.run(Person.create_household, action_param_values=pv) # yield ses.response['data_record'] # he = MEN.pop() # she = WOMEN.pop() # fam = Household(name=he.last_name + "-" + she.last_name, type_id=3) # yield fam # yield Member(household=fam, person=he, role=Role.objects.get(pk=1)) # yield Member(household=fam, person=she, role=Role.objects.get(pk=2)) i = 0 for m in Member.objects.filter(role=MemberRoles.head): i += 1 if i % 3 == 0: m.end_date = i2d(20020304) yield m pv = dict(head=m.person, partner=WOMEN.pop(), type=TYPES.pop()) ses.run(Person.create_household, action_param_values=pv)
def test01(self): """ """ from lino.modlib.cal.utils import DurationUnits start_date = i2d(20111026) self.assertEqual(DurationUnits.months.add_duration(start_date,2),i2d(20111226)) self.assertEqual(DurationUnits.months.add_duration(start_date,-2),i2d(20110826)) start_date = i2d(20110131) self.assertEqual(DurationUnits.months.add_duration(start_date,1),i2d(20110228)) self.assertEqual(DurationUnits.months.add_duration(start_date,-1),i2d(20101231)) self.assertEqual(DurationUnits.months.add_duration(start_date,-2),i2d(20101130))
def event(type,date,name,name_nl,name_fr,*features,**kw): #~ features = [f.pk for f in features] cities = kw.pop('cities',None) e = Event(type=type,date=i2d(date),name=name,name_nl=name_nl,name_fr=name_fr,**kw) e.full_clean() e.save() if features: e.features=features if cities: for name in cities: stage = Stage(event=e,city=get_city(name)) stage.full_clean() stage.save() #~ e.cities = [get_city(n) for n in cities] return e
def objects(): bd = i2d(19500203) for p in contacts.Person.objects.filter(country__isocode="BE"): yield mti.insert_child(p,Employee,birth_date=bd) bd += datetime.timedelta(days=234) # experimental value for i,e in enumerate(Employee.objects.all()): if i % 4: e.is_chef = True e.is_member = False yield e yield Area(name="North") yield Area(name="East") yield Area(name="South") yield Area(name="West") CHEFS = Cycler(Employee.objects.filter(is_chef=True)) MEMBERS = Cycler(Employee.objects.filter(is_member=True)) AREAS = Cycler(patrols.Area.objects.all()) MEMBERS_PER_TEAM = 2 le = list(Employee.objects.filter(is_member=True)) while len(le) > MEMBERS_PER_TEAM: name = '-'.join([o.last_name for o in le[:MEMBERS_PER_TEAM]]) t = Team(chef=CHEFS.pop(),name=name) yield t for e in le[:MEMBERS_PER_TEAM]: yield Member(team=t,employee=e) le = le[MEMBERS_PER_TEAM:] #~ yield Team(name="One",chef=CHEFS.pop()) #~ yield Team(name="Two",chef=CHEFS.pop()) #~ yield Team(name="Three",chef=CHEFS.pop()) TEAMS = Cycler(patrols.Team.objects.all()) d = settings.SITE.demo_date(-20) for i in range(50): yield patrols.Patrol(date=d,team=TEAMS.pop(),area=AREAS.pop()) d += ONE_DAY for p in patrols.Patrol.objects.all(): yield patrols.WorkDay(date=p.date,employee=p.team.chef,type=WDT.pop()) for m in p.team.member_set.all(): yield patrols.WorkDay(date=p.date,employee=m.employee,type=WDT.pop())
def objects(): Member = rt.modules.households.Member MemberRoles = rt.modules.households.MemberRoles # Household = resolve_model('households.Household') Person = resolve_model(dd.plugins.households.person_model) Type = resolve_model('households.Type') MEN = Cycler(Person.objects.filter(gender=dd.Genders.male) .order_by('-id')) WOMEN = Cycler(Person.objects.filter(gender=dd.Genders.female) .order_by('-id')) TYPES = Cycler(Type.objects.all()) ses = rt.login() for i in range(5): pv = dict( head=MEN.pop(), partner=WOMEN.pop(), type=TYPES.pop()) ses.run( Person.create_household, action_param_values=pv) # yield ses.response['data_record'] # he = MEN.pop() # she = WOMEN.pop() # fam = Household(name=he.last_name + "-" + she.last_name, type_id=3) # yield fam # yield Member(household=fam, person=he, role=Role.objects.get(pk=1)) # yield Member(household=fam, person=she, role=Role.objects.get(pk=2)) i = 0 for m in Member.objects.filter(role=MemberRoles.head): i += 1 if i % 3 == 0: m.end_date = i2d(20020304) yield m pv = dict( head=m.person, partner=WOMEN.pop(), type=TYPES.pop()) ses.run( Person.create_household, action_param_values=pv)
class Site(Site): title = "Lino Mini 1" demo_fixtures = 'std demo demo2' user_types_module = 'lino_xl.lib.xl.user_types' use_experimental_features = True languages = "en de fr" the_demo_date = i2d(20141023) def setup_quicklinks(self, user, tb): super(Site, self).setup_quicklinks(user, tb) tb.add_action(self.modules.contacts.Persons) tb.add_action(self.modules.contacts.Companies) def get_installed_apps(self): yield super(Site, self).get_installed_apps() yield 'lino.modlib.system' yield 'lino.modlib.users' yield 'lino_xl.lib.contacts'
def event(type, date, name, name_nl, name_fr, *features, **kw): #~ features = [f.pk for f in features] cities = kw.pop('cities', None) e = Event(type=type, date=i2d(date), name=name, name_nl=name_nl, name_fr=name_fr, **kw) e.full_clean() e.save() if features: e.features = features if cities: for name in cities: stage = Stage(event=e, city=get_city(name)) stage.full_clean() stage.save() #~ e.cities = [get_city(n) for n in cities] return e
from lino.api import ad from lino.projects.min2.settings import * from lino.utils import i2d ad.configure_plugin('sepa', import_statements_path="/home/khchine5/Documents/Documentation/Lino/Ticket 505/test_file") SITE = Site(globals(), the_demo_date=i2d(20141023)) ALLOWED_HOSTS = ['*'] DEBUG = True SECRET_KEY = "20227" # see :djangoticket:`20227`
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 if 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 # EntryType = rt.models.blogs.EntryType # Entry = rt.models.blogs.Entry # 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", rt.models.users.UserTypes.user) yield create_user("mathieu", rt.models.users.UserTypes.user) 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='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()) for name in "Bus.co farm.co share.co".split(): obj = Company(name=name) yield obj yield Site(name=name + ".com", partner=obj) COMPANIES = Cycler(Company.objects.all()) yield Company(name="in3x") for u in Company.objects.exclude(name="in3x"): for i in range(3): yield Interest(owner=u, topic=TOPICS.pop()) roletype = rt.models.contacts.RoleType yield roletype(**dd.babel_values('name', en="Manager", fr='Gérant', de="Geschäftsführer", et="Tegevjuht")) yield roletype(**dd.babel_values( 'name', en="Director", fr='Directeur', de="Direktor", et="Direktor")) yield roletype(**dd.babel_values( 'name', en="Secretary", fr='Secrétaire', de="Sekretär", et="Sekretär")) yield roletype(**dd.babel_values('name', en="IT Manager", fr='Gérant informatique', de="EDV-Manager", et="IT manager")) yield roletype(**dd.babel_values( 'name', en="President", fr='Président', de="Präsident", et="President")) # RTYPES = Cycler(ReportingTypes.objects()) 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()) SITES = Cycler(Site.objects.exclude(name="pypi")) # LISTS = Cycler(List.objects.all()) if Milestone: 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) 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", project=PROJECTS.pop()) yield ticket("Bar is not always baz", project=PROJECTS.pop()) yield ticket("Baz sucks") yield ticket("Foo and bar don't baz", project=PROJECTS.pop()) # a ticket without project: 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", project=PROJECTS.pop()) yield ticket("No Foo after deleting Bar", project=PROJECTS.pop()) yield ticket("Is there any Bar in Foo?", project=PROJECTS.pop()) yield ticket("Foo never matches Bar", project=PROJECTS.pop()) yield ticket("Where can I find a Foo when bazing Bazes?", project=PROJECTS.pop()) yield ticket("Class-based Foos and Bars?", project=PROJECTS.pop()) yield ticket("Foo cannot bar", project=PROJECTS.pop()) # Example of memo markup: yield ticket("Bar cannot foo", project=PROJECTS.pop(), 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", project=PROJECTS.pop()) yield ticket("Bars have no foo", project=PROJECTS.pop()) yield ticket("How to get bar from foo", project=PROJECTS.pop()) n = Ticket.objects.count() for i in range(100): yield ticket("Ticket {}".format(i + n + 1), project=PROJECTS.pop()) if Milestone: 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))
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()
class Site(Site): title = Site.verbose_name + " demo" the_demo_date = i2d(20141023)
def set_date(self, d): self.date = i2d(d)
class Site(Site): languages = "en de fr" the_demo_date = i2d(20141023)
from lino.api import ad from lino_book.projects.min2.settings import * from lino.utils import i2d # ad.configure_plugin('sepa', import_statements_path="/home/khchine5/Documents/Documentation/Lino/Ticket 505/test_file") SITE = Site(globals(), the_demo_date=i2d(20141023)) ALLOWED_HOSTS = ['*'] DEBUG = True SECRET_KEY = "20227" # see :djangoticket:`20227`
def tickets_objects(): # was previously in tickets User = rt.models.users.User Partner = rt.models.contacts.Partner Topic = rt.models.topics.Topic TT = rt.models.tickets.TicketType Ticket = rt.models.tickets.Ticket Interest = rt.models.topics.Interest Milestone = rt.models.deploy.Milestone Project = rt.models.tickets.Project Site = rt.models.tickets.Site Link = rt.models.tickets.Link LinkTypes = rt.models.tickets.LinkTypes EntryType = rt.models.blogs.EntryType Entry = rt.models.blogs.Entry Tagging = rt.models.blogs.Tagging cons = rt.models.users.UserTypes.consultant dev = rt.models.users.UserTypes.developer yield User(username="******", profile=cons) yield User(username="******", profile=cons) yield User(username="******", profile=dev) yield User(username="******", profile=rt.models.users.UserTypes.senior) USERS = Cycler(User.objects.all()) yield TT(**dd.str2kw("name", _("Bugfix"))) yield TT(**dd.str2kw("name", _("Enhancement"))) yield TT(**dd.str2kw("name", _("Upgrade"))) 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()) for name in "welket welsch pypi".split(): obj = Partner(name=name) yield obj yield Site(name=name, partner=obj) for u in Partner.objects.exclude(name="pypi"): for i in range(3): yield Interest(partner=u, topic=TOPICS.pop()) SITES = Cycler(Site.objects.exclude(name="pypi")) for i in range(7): d = dd.today(i * 2 - 20) yield Milestone(site=SITES.pop(), expected=d, reached=d) yield Milestone(site=SITES.pop(), expected=dd.today()) prj1 = Project(name="Framewörk", ref="linö", private=False, start_date=i2d(20090101)) yield prj1 yield Project(name="Téam", ref="téam", start_date=i2d(20100101), parent=prj1) prj2 = Project(name="Documentatión", ref="docs", private=False, start_date=i2d(20090101), parent=prj1) yield prj2 yield Project(name="Research", ref="research", private=False, start_date=i2d(19980101), parent=prj2) yield Project(name="Shop", ref="shop", private=False, start_date=i2d(20120201), end_date=i2d(20120630)) PROJECTS = Cycler(Project.objects.all()) 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 = USERS.pop() kwargs.update( ticket_type=TYPES.pop(), summary=summary, reporter=u, user=u, state=TSTATES.pop(), topic=TOPICS.pop() ) if num[0] % 2: kwargs.update(site=SITES.pop()) if False: kwargs.update(project=PROJECTS.pop()) obj = Ticket(**kwargs) yield obj if obj.state.active: yield Vote(votable=obj, user=USERS.pop(), state=VSTATES.pop()) yield ticket("Föö fails to bar when baz", project=PROJECTS.pop()) yield ticket("Bar is not always baz", project=PROJECTS.pop()) yield ticket("Baz sucks") yield ticket("Foo and bar don't baz", project=PROJECTS.pop()) # a ticket without project: 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", project=PROJECTS.pop()) yield ticket("No Foo after deleting Bar", project=PROJECTS.pop()) yield ticket("Is there any Bar in Foo?", project=PROJECTS.pop()) yield ticket("Foo never matches Bar", project=PROJECTS.pop()) yield ticket("Where can I find a Foo when bazing Bazes?", project=PROJECTS.pop()) yield ticket("Class-based Foos and Bars?", project=PROJECTS.pop()) yield ticket("Foo cannot bar", project=PROJECTS.pop()) # Example of memo markup: yield ticket( "Bar cannot foo", project=PROJECTS.pop(), 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", project=PROJECTS.pop()) yield ticket("Bars have no foo", project=PROJECTS.pop()) yield ticket("How to get bar from foo", project=PROJECTS.pop()) for i in range(100): yield ticket("Ticket {}".format(i), project=PROJECTS.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 Tagging(entry=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 Tagging(entry=e, topic=TOPICS.pop()) yield Tagging(entry=e, topic=TOPICS.pop())
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 if 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 # EntryType = rt.models.blogs.EntryType # Entry = rt.models.blogs.Entry # 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", rt.models.users.UserTypes.user) yield create_user("mathieu", rt.models.users.UserTypes.user) 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='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()) for name in "Bus.co farm.co share.co".split(): obj = Company(name=name) yield obj yield Site(name=name + ".com", partner=obj) COMPANIES = Cycler(Company.objects.all()) yield Company(name="in3x") for u in Company.objects.exclude(name="in3x"): for i in range(3): yield Interest(owner=u, topic=TOPICS.pop()) roletype = rt.models.contacts.RoleType yield roletype(**dd.babel_values('name', en="Manager", fr='Gérant', de="Geschäftsführer", et="Tegevjuht")) yield roletype(**dd.babel_values('name', en="Director", fr='Directeur', de="Direktor", et="Direktor")) yield roletype(**dd.babel_values('name', en="Secretary", fr='Secrétaire', de="Sekretär", et="Sekretär")) yield roletype(**dd.babel_values('name', en="IT Manager", fr='Gérant informatique', de="EDV-Manager", et="IT manager")) yield roletype(**dd.babel_values('name', en="President", fr='Président', de="Präsident", et="President")) # RTYPES = Cycler(ReportingTypes.objects()) 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()) SITES = Cycler(Site.objects.exclude(name="pypi")) # LISTS = Cycler(List.objects.all()) if Milestone: 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) 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", project=PROJECTS.pop()) yield ticket("Bar is not always baz", project=PROJECTS.pop()) yield ticket("Baz sucks") yield ticket("Foo and bar don't baz", project=PROJECTS.pop()) # a ticket without project: 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", project=PROJECTS.pop()) yield ticket("No Foo after deleting Bar", project=PROJECTS.pop()) yield ticket("Is there any Bar in Foo?", project=PROJECTS.pop()) yield ticket("Foo never matches Bar", project=PROJECTS.pop()) yield ticket("Where can I find a Foo when bazing Bazes?", project=PROJECTS.pop()) yield ticket("Class-based Foos and Bars?", project=PROJECTS.pop()) yield ticket("Foo cannot bar", project=PROJECTS.pop()) # Example of memo markup: yield ticket("Bar cannot foo", project=PROJECTS.pop(), 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", project=PROJECTS.pop()) yield ticket("Bars have no foo", project=PROJECTS.pop()) yield ticket("How to get bar from foo", project=PROJECTS.pop()) n = Ticket.objects.count() for i in range(100): yield ticket("Ticket {}".format(i+n+1), project=PROJECTS.pop()) if Milestone: 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))
def test01(self): # Create a room, event type, series and a course room = create(cal.Room, name="First Room") lesson = create(cal.EventType, name="Lesson", event_label="Lesson") line = create(courses.Line, name="First Line", event_type=lesson) obj = create(courses.Course, line=line, room=room, max_events=5, monday=True, state=courses.CourseStates.active, start_date=i2d(20140110)) self.assertEqual(str(obj), "Activity #1") # self.assertEqual(settings.SITE.kernel.site, settings.SITE) # self.assertEqual(settings.SITE, dd.site) # self.assertEqual(settings.SITE.plugins, dd.plugins) # self.assertEqual(settings.SITE.plugins.extjs, dd.plugins.extjs) settings.SITE.verbose_client_info_message = True users.User(username="******", user_type=UserTypes.admin, language="en").save() ses = settings.SITE.login('robin') # utility function which runs update_events and checks whether # info_message and output of cal.EntriesByController are as # expected: def check_update(obj, msg1, msg2): res = ses.run(obj.do_update_events) self.assertEqual(res['success'], True) print(res['info_message']) self.assertEqual(res['info_message'].strip(), msg1.strip()) ar = ses.spawn(cal.EntriesByController, master_instance=obj) s = ar.to_rst(column_names="when_text state summary", nosummary=True) # print(s) self.assertEqual(s.strip(), msg2.strip()) # Run do_update_events a first time check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Update presences for Activity #1 Lesson 1 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 2 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 3 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 4 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 5 : 0 created, 0 unchanged, 0 deleted. 5 row(s) have been updated. """, """ ================ =========== =================== When State Short description ---------------- ----------- ------------------- Mon 13/01/2014 Suggested Lesson 1 Mon 20/01/2014 Suggested Lesson 2 Mon 27/01/2014 Suggested Lesson 3 Mon 03/02/2014 Suggested Lesson 4 Mon 10/02/2014 Suggested Lesson 5 ================ =========== =================== """) # Decrease max_events and check whether the superfluous events # get removed. obj.max_events = 3 check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 3). 2 row(s) have been updated.""", """ ================ =========== =================== When State Short description ---------------- ----------- ------------------- Mon 13/01/2014 Suggested Lesson 1 Mon 20/01/2014 Suggested Lesson 2 Mon 27/01/2014 Suggested Lesson 3 ================ =========== =================== """) # Run do_update_events for 5 events a second time obj.max_events = 5 check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Update presences for Activity #1 Lesson 4 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 5 : 0 created, 0 unchanged, 0 deleted. 2 row(s) have been updated.""", """ ================ =========== =================== When State Short description ---------------- ----------- ------------------- Mon 13/01/2014 Suggested Lesson 1 Mon 20/01/2014 Suggested Lesson 2 Mon 27/01/2014 Suggested Lesson 3 Mon 03/02/2014 Suggested Lesson 4 Mon 10/02/2014 Suggested Lesson 5 ================ =========== =================== """) # Now we want to skip the 2nd event. We click on "Move next" # on this event. Lino then moves all subsequent events # accordingly. ar = cal.EntriesByController.request( master_instance=obj, known_values=dict(start_date=i2d(20140120))) e = ar.data_iterator[0] self.assertEqual(e.state, cal.EntryStates.suggested) # res = ses.run(e.move_next) self.assertEqual(res['success'], True) expected = """\ Move down for Activity #1 Lesson 2... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Lesson 2 has been moved from 2014-01-20 to 2014-01-27. 1 row(s) have been updated.""" self.assertEqual(res['info_message'], expected) # The event is now in state "draft" because it has been # modified by the user. self.assertEqual(e.state, cal.EntryStates.draft) # e.full_clean() # e.save() check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Lesson 2 has been moved from 2014-01-20 to 2014-01-27. 0 row(s) have been updated. """, """ ================ =========== =================== When State Short description ---------------- ----------- ------------------- Mon 13/01/2014 Suggested Lesson 1 Mon 27/01/2014 Draft Lesson 2 Mon 03/02/2014 Suggested Lesson 3 Mon 10/02/2014 Suggested Lesson 4 Mon 17/02/2014 Suggested Lesson 5 ================ =========== =================== """) # Now we imagine that February 3 is the National Day in our # country and that we create the rule for this only now. So # we have a conflict because Lino created an appointment on # that date. Of course the National Day must *not* move to an # alternative date. et = create(cal.EventType, name="Holiday", all_rooms=True) national_day = create(cal.RecurrentEvent, name="National Day", event_type=et, start_date=i2d(20140203), every_unit=cal.Recurrencies.yearly) res = ses.run(national_day.do_update_events) self.assertEqual(res['success'], True) expected = """\ Update Events for National Day... Generating events between 2014-02-03 and 2020-05-22 (max. 72). Reached upper date limit 2020-05-22 Update presences for Recurring event #1 National Day : 0 created, 0 unchanged, 0 deleted. Update presences for Recurring event #1 National Day : 0 created, 0 unchanged, 0 deleted. Update presences for Recurring event #1 National Day : 0 created, 0 unchanged, 0 deleted. Update presences for Recurring event #1 National Day : 0 created, 0 unchanged, 0 deleted. Update presences for Recurring event #1 National Day : 0 created, 0 unchanged, 0 deleted. Update presences for Recurring event #1 National Day : 0 created, 0 unchanged, 0 deleted. Update presences for Recurring event #1 National Day : 0 created, 0 unchanged, 0 deleted. 7 row(s) have been updated.""" self.assertEqual(res['info_message'], expected) ar = ses.spawn(cal.EntriesByController, master_instance=national_day) s = ar.to_rst(column_names="when_text state", nosummary=True) # print s self.assertEqual( s, """\ ================ =========== When State ---------------- ----------- Mon 03/02/2014 Suggested Tue 03/02/2015 Suggested Wed 03/02/2016 Suggested Fri 03/02/2017 Suggested Sat 03/02/2018 Suggested Sun 03/02/2019 Suggested Mon 03/02/2020 Suggested ================ =========== """) # the national day is now conflicting with our Lesson 3: ce = ar[0] self.assertEqual(ce.summary, "National Day") self.assertEqual(ce.start_date.year, 2014) ar = ses.spawn(cal.ConflictingEvents, master_instance=ce) s = ar.to_rst(column_names="when_text state auto_type") # print s self.assertEqual( s, """\ ==================== =========== ======= When State No. -------------------- ----------- ------- Mon 03/02/2014 Suggested 3 **Total (1 rows)** **3** ==================== =========== ======= """) # delete all lessons and start again with a virgin series cal.Event.objects.filter(event_type=lesson).delete() check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Lesson 4 wants 2014-02-03 but conflicts with <QuerySet [Event #8 ('Recurring event #1 National Day')]>, moving to 2014-02-10. Update presences for Activity #1 Lesson 1 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 2 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 3 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 4 : 0 created, 0 unchanged, 0 deleted. Update presences for Activity #1 Lesson 5 : 0 created, 0 unchanged, 0 deleted. 5 row(s) have been updated. """, """ ================ =========== =================== When State Short description ---------------- ----------- ------------------- Mon 13/01/2014 Suggested Lesson 1 Mon 20/01/2014 Suggested Lesson 2 Mon 27/01/2014 Suggested Lesson 3 Mon 10/02/2014 Suggested Lesson 4 Mon 17/02/2014 Suggested Lesson 5 ================ =========== =================== """) # we move the first lesson one week down and check whether # remaining entries get adapted. We manually set the state to # draft (this is automatically done when using the web ui). e = cal.Event.objects.get(event_type=lesson, auto_type=1) e.start_date = i2d(20140120) e.state = cal.EntryStates.draft e.full_clean() e.save() check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-27 and 2020-05-22 (max. 5). Lesson 3 wants 2014-02-03 but conflicts with <QuerySet [Event #8 ('Recurring event #1 National Day')]>, moving to 2014-02-10. 0 row(s) have been updated. """, """ ================ =========== =================== When State Short description ---------------- ----------- ------------------- Mon 20/01/2014 Draft Lesson 1 Mon 27/01/2014 Suggested Lesson 2 Mon 10/02/2014 Suggested Lesson 3 Mon 17/02/2014 Suggested Lesson 4 Mon 24/02/2014 Suggested Lesson 5 ================ =========== =================== """) # we cancel the third lesson and see whether Lino adds a e = cal.Event.objects.get(event_type=lesson, auto_type=3) e.state = cal.EntryStates.cancelled e.auto_type = None e.full_clean() e.save()
def test01(self): Enrolment = rt.models.courses.Enrolment Pupil = rt.models.courses.Pupil Line = rt.models.courses.Line Course = rt.models.courses.Course CourseStates = rt.models.courses.CourseStates EnrolmentStates = rt.models.courses.EnrolmentStates EventType = rt.models.cal.EventType # room = create(cal.Room, name="First Room") lesson = create(EventType, name="Lesson", event_label="Lesson") line = create(Line, name="First Line", event_type=lesson) obj = create( Course, line=line, # room=room, max_places=3, #monday=True, #start_date=i2d(20140110), state=courses.CourseStates.active) self.assertEqual(str(obj), "Activity #1") # self.assertEqual(settings.SITE.kernel.site, settings.SITE) # self.assertEqual(settings.SITE, dd.site) # self.assertEqual(settings.SITE.plugins, dd.plugins) # self.assertEqual(settings.SITE.plugins.extjs, dd.plugins.extjs) settings.SITE.verbose_client_info_message = True users.User(username="******", user_type=UserTypes.admin, language="en").save() ses = settings.SITE.login('robin') anna = create(Pupil, first_name="Anna") bert = create(Pupil, first_name="Bert") claire = create(Pupil, first_name="Claire") ernie = create(Pupil, first_name="Ernie") def ENR(p, start_date, **kwargs): return create( Enrolment, course=obj, pupil=p, state=EnrolmentStates.confirmed, start_date=start_date, **kwargs) # anna and ernie participated from the beginning. # bert stopped in may, and claire started in june. # so there were never more than 3 participants. # 2015-12-31 : 0 participants, 3 free places # 2016-01-01 : 3 participants # 2016-05-01 : bert leaves. 2 participants # 2016-06-01 : claire starts. 3 participants ENR(anna, i2d(20160101)) ENR(bert, i2d(20160101), end_date=i2d(20160501)) ENR(claire, i2d(20160601)) ENR(ernie, i2d(20160101)) self.assertEqual(obj.get_free_places(i2d(20151231)), 3) self.assertEqual(obj.get_free_places(i2d(20160101)), 0) self.assertEqual(obj.get_free_places(i2d(20160301)), 0) self.assertEqual(obj.get_free_places(i2d(20160531)), 1) self.assertEqual(obj.get_free_places(i2d(20161231)), 0) #self.assertEqual(enr.get_confirm_veto(None), '') # 20180731 the default value for the enrolment state was a # string which became an EnrolmentStates choice only during # full_clean(). Now this case is being resolved in # ChoiceListField.__init__(). enr = Enrolment(course=obj, pupil=anna) self.assertEqual(enr.state, EnrolmentStates.requested)
def test00(self): ASD = rt.models.coachings.CoachingType(id=isip.COACHINGTYPE_ASD, name="ASD") ASD.save() DSBE = rt.models.coachings.CoachingType(id=isip.COACHINGTYPE_DSBE, name="DSBE") DSBE.save() User(username='******').save() User(username='******', coaching_type=DSBE).save() User(username='******', coaching_type=ASD).save() User(username='******').save() households_Type(name="Eheleute", pk=1).save() settings.SITE.uppercase_last_name = True #~ def test01(self): """ AttributeError 'NoneType' object has no attribute 'coaching_type' """ self.assertDoesNotExist(Client, id=23633) process_line(POST_GEORGES) georges = Client.objects.get(id=23633) self.assertEqual(georges.first_name, "Georges") georges.first_name = "Peter" georges.save() process_line(POST_GEORGES) georges = Client.objects.get(id=23633) self.assertEqual(georges.first_name, "Georges") ar = rt.models.changes.ChangesByMaster.request(georges) self.assertEqual(ar.get_total_count(), 0) # Company becomes Client # ValidationError([u'A Partner cannot be parent for a Client']) (201302-22 12:42:07) # A Partner in TIM has both `PAR->NoTva` nonempty and # `PARATTR_N` set. It currently exists in Lino as a Company but # not as a Client. `watch_tim` then must create a Client after # creating also the intermediate Person. The Company child must # be removed. obj = Company(name="Müller Max Moritz", id=5088) obj.save() ar = rt.models.changes.ChangesByMaster.request(obj) self.assertEqual(ar.get_total_count(), 0) global PUT_MAX_MORITZ process_line(PUT_MAX_MORITZ) self.assertDoesNotExist(Company, id=5088) # ~ company = Company.objects.get(id=5088) # has not been deleted person = Person.objects.get(id=5088) # has been created client = Client.objects.get(id=5088) # has been created # one coaching has been created coaching = Coaching.objects.get(client=client) self.assertEqual(person.first_name, "Max Moritz") self.assertEqual(client.first_name, "Max Moritz") self.assertEqual(coaching.user.username, 'alicia') self.assertEqual(coaching.primary, True) self.assertEqual(coaching.start_date, i2d(19910812)) """ Client becomes Company """ #~ PUT_MAX_MORITZ = PUT_MAX_MORITZ.replace('"IDUSR":"******"','"IDUSR":""') PUT_MAX_MORITZ = PUT_MAX_MORITZ.replace('"ATTRIB":"N"', '"ATTRIB":""') process_line(PUT_MAX_MORITZ) #~ company = Company.objects.get(id=5088) self.assertDoesNotExist(Client, id=5088) # has been deleted self.assertDoesNotExist(Coaching, client_id=5088) #~ def test03(self): """ Test whether watch_tim raises Exception 'Cannot create Client ... from PXS' when necessary. """ self.assertDoesNotExist(Client, id=23635) try: process_line(POST_PXS) self.fail("Expected an exception") except Exception as e: self.assertEqual(str(e), "Cannot create Client 0000023635 from PXS") self.assertDoesNotExist(Client, id=23635) #~ def test04(self): """ Household becomes Client """ Household(name="Voldemort-Potter Harald", id=4260).save() process_line(PUT_PAR_POTTER) client = Client.objects.get(id=4260) # has been created self.assertDoesNotExist(Household, id=4260) # one coaching has been created coaching = Coaching.objects.get(client=client) self.assertEqual(client.first_name, "Harald") self.assertEqual(coaching.primary, True) self.assertEqual(coaching.user.username, 'alicia') self.assertEqual(coaching.start_date, i2d(19850723)) with translation.override('en'): s = changes_to_rst(client.partner_ptr) # print s self.assertEqual( s, """\ =========== ============= ==================================== ============================================================================= ============= =========== User Change Type Object Changes Object type object id ----------- ------------- ------------------------------------ ----------------------------------------------------------------------------- ------------- ----------- watch_tim Create *alicia / Voldemort-Potter H* Coaching(id=2,start_date=1985-07-23,user=2,client=4260,type=2,primary=True) Coaching 2 watch_tim Add child *Eheleute Harald VOLDEMORT-POTTER* pcsw.Client Person 4260 watch_tim Add child *Voldemort-Potter Harald* contacts.Person Partner 4260 =========== ============= ==================================== ============================================================================= ============= =========== """) #~ def test05(self): """ Person becomes Household """ Person(id=6283, first_name="Paul", last_name="Willekens-Delanuit").save() process_line(PUT_PAR_6283) household = Household.objects.get(id=6283) # has been created self.assertDoesNotExist(Person, id=6283) #~ def test06(self): """ ValidationError {'first_name': [u'This field cannot be blank.']} """ ln = """{"method":"PUT","alias":"PAR","id":"0000001334","time":"20121029 09:00:00", "user":"","data":{"IDPAR":"0000001334","FIRME":"Belgacom", "NAME2":"","RUE":"","CP":"1030","IDPRT":"V","PAYS":"B","TEL":"0800-44500", "FAX":"0800-11333","COMPTE1":"","NOTVA":"","COMPTE3":"","IDPGP":"", "DEBIT":" 2242.31","CREDIT":"","ATTRIB":"","IDMFC":"60","LANGUE":"F", "IDBUD":"","PROF":"30","CODE1":"","CODE2":"","CODE3":"", "DATCREA":{"__date__":{"year":1992,"month":10,"day":6}},"ALLO":"","NB1":"", "NB2":"","IDDEV":"","MEMO":"Foo bar","COMPTE2":"","RUENUM":"","RUEBTE":"", "DEBIT2":" 2242.31","CREDIT2":"", "IMPDATE":{"__date__":{"year":2012,"month":10,"day":24}}, "ATTRIB2":"","CPTSYSI":"","EMAIL":"*****@*****.**", "MVIDATE":{"__date__":{"year":2012,"month":9,"day":9}},"IDUSR":"","DOMI1":""}} """ self.assertDoesNotExist(Partner, id=1334) translation.deactivate_all() process_line(ln) obj = Partner.objects.get(id=1334) self.assertDoesNotExist(Company, id=1334) self.assertDoesNotExist(Person, id=1334) #~ self.fail("Expected a ValidationError") #~ except ValidationError as e: #~ self.assertEqual(str(e),"{'first_name': [u'This field cannot be blank.']}") #~ self.assertDoesNotExist(Partner,id=1334) ln = ln.replace('"NOTVA":""', '"NOTVA":"BE-0999.999.999"') process_line(ln) company = Company.objects.get(id=1334) #~ def test07(self): """ 2013-02-28 10:05:41 ValueError('Cannot assign "u\'\'": "Place.country" must be a "Country" instance.',) """ ln = """{"method":"PUT","alias":"PAR","id":"0000023649","time":"20130228 10:05:41","user":"******", "data":{"IDPAR":"0000023649","FIRME":"Reinders Denis","NAME2":"","RUE":"Sch<94>nefelderweg", "CP":"4700","IDPRT":"S","PAYS":"","TEL":"","FAX":"","COMPTE1":"","NOTVA":"","COMPTE3":"", "IDPGP":"","DEBIT":"","CREDIT":"","ATTRIB":"N","IDMFC":"30","LANGUE":"D","IDBUD":"", "PROF":"80","CODE1":"","CODE2":"","CODE3":"", "DATCREA":{"__date__":{"year":2013,"month":2,"day":28}}, "ALLO":"Herr","NB1":"","NB2":"791228 123-35","IDDEV":"","MEMO":"","COMPTE2":"", "RUENUM":" 123","RUEBTE":"a","DEBIT2":"","CREDIT2":"", "IMPDATE":{"__date__":{"year":0,"month":0,"day":0}},"ATTRIB2":"","CPTSYSI":"","EMAIL":"", "MVIDATE":{"__date__":{"year":0,"month":0,"day":0}},"IDUSR":"","DOMI1":""}} """ self.assertDoesNotExist(Client, id=23649) process_line(ln) obj = Client.objects.get(id=23649) self.assertEqual(obj.first_name, "Denis") with translation.override('en'): s = changes_to_rst(obj.partner_ptr) #~ skipped because cannot easily test due to `modified` timestamp #~ print s #~ self.assertEqual(s,"""\ #~ =========== ============= ======================== ==================== #~ User Change Type Object Changes Object type object id #~ ----------- ------------- ------------------------ -------------------- #~ watch_tim Create REINDERS Denis (23649) Client(id=23649,created=2013-02-28T00:00:00,modified=2013-05-08T10:57:34.755851,name='Reinders Denis',street='Sch<94>nefelderweg',street_no='123',street_box='a',language='de',activity=80,partner_ptr=23649,first_name='Denis',last_name='Reinders',person_ptr=23649,is_cpas=True,national_id='791228 123-35',client_state=<ClientStates.newcomer:10>) Klient 23649 #~ =========== ============= ======================== ==================== #~ """) """ 20130508 Company becomes Client 201305-03 07:49:11 INFO watch_tim : PAR:0000000005 (Company #5 (u'Air Liquide Belgium')) : Company becomes Client """ Company(name="Air Liquide Belgium", id=5).save() ln = """{"method":"PUT","alias":"PAR","id":"0000000005","time":"20130503 07:36:15", "user":"","data":{"IDPAR":"0000000005","FIRME":"Air Liquide Belgium", "NAME2":"","RUE":"Quai des Vennes","CP":"4020","IDPRT":"V","PAYS":"B", "TEL":"04/349.89.89","FAX":"04/341.20.70","COMPTE1":"GKCCBEBB:BE57551373330235", "NOTVA":"BE-0441.857.467","COMPTE3":"","IDPGP":"","DEBIT":"","CREDIT":"", "ATTRIB":"A","IDMFC":"30","LANGUE":"F","IDBUD":"","PROF":"19", "CODE1":"","CODE2":"","CODE3":"", "DATCREA":{"__date__":{"year":1985,"month":3,"day":12}},"ALLO":"S.A.", "NB1":"","NB2":"","IDDEV":"","MEMO":"\\n", "COMPTE2":"BBRUBEBB:BE12310110444892","RUENUM":" 8","RUEBTE":"","DEBIT2":"", "CREDIT2":"","IMPDATE":{"__date__": {"year":2009,"month":3,"day":10}}, "ATTRIB2":"","CPTSYSI":"","EMAIL":"", "MVIDATE":{"__date__":{"year":0,"month":0,"day":0}},"IDUSR":"******","DOMI1":""}} """ process_line(ln) self.assertDoesNotExist(Client, id=5) obj = Company.objects.get(id=5) self.assertEqual(obj.name, "Air Liquide Belgium") with translation.override('en'): s = changes_to_rst(obj.partner_ptr) # print s self.assertEqual( s, """\ +-----------+-------------+----------------------------+--------------------------------------------------------+--------------+-----------+ | User | Change Type | Object | Changes | Object type | object id | +===========+=============+============================+========================================================+==============+===========+ | watch_tim | Update | *S.A. Air Liquide Belgium* | - activity_id : None --> 19 | Organization | 5 | | | | | - bank_account1 : None --> 'GKCCBEBB:BE57551373330235' | | | | | | | - bank_account2 : None --> 'BBRUBEBB:BE12310110444892' | | | | | | | - city_id : None --> 3 | | | | | | | - country_id : None --> 'B' | | | | | | | - fax : '' --> '04/341.20.70' | | | | | | | - language : '' --> 'fr' | | | | | | | - phone : '' --> '04/349.89.89' | | | | | | | - prefix : '' --> 'S.A.' | | | | | | | - street : '' --> 'Quai des Vennes' | | | | | | | - street_no : '' --> '8' | | | | | | | - vat_id : '' --> 'BE-0441.857.467' | | | | | | | - zip_code : '' --> '4020' | | | +-----------+-------------+----------------------------+--------------------------------------------------------+--------------+-----------+ """) """ Person becomes Company """ Person(id=9932, first_name="CPAS", last_name="Andenne").save() ln = """{"method":"PUT","alias":"PAR","id":"0000009932","time":"20130503 07:38:16","user":"","data":{"IDPAR":"0000009932","FIRME":"Andenne, CPAS","NAME2":"","RUE":"Rue de l'Hopital","CP":"5300","IDPRT":"V","PAYS":"B","TEL":"","FAX":"","COMPTE1":"","NOTVA":"BE-0999.999.999","COMPTE3":"","IDPGP":"","DEBIT":"","CREDIT":"","ATTRIB":"","IDMFC":"","LANGUE":"F","IDBUD":"","PROF":"65","CODE1":"","CODE2":"","CODE3":"","DATCREA":{"__date__":{"year":1988,"month":12,"day":9}},"ALLO":"","NB1":"","NB2":" 0","IDDEV":"","MEMO":"","COMPTE2":"","RUENUM":" 22","RUEBTE":"","DEBIT2":"","CREDIT2":"","IMPDATE":{"__date__":{"year":0,"month":0,"day":0}},"ATTRIB2":"","CPTSYSI":"","EMAIL":"","MVIDATE":{"__date__":{"year":0,"month":0,"day":0}},"IDUSR":"","DOMI1":""}}""" process_line(ln) self.assertDoesNotExist(Client, id=9932) self.assertDoesNotExist(Person, id=9932) obj = Company.objects.get(id=9932) self.assertEqual(obj.name, "Andenne, CPAS") with translation.override('en'): s = changes_to_rst(obj.partner_ptr) #~ print s self.assertEqual( s, """\ =========== ============== ================= ================== ============= =========== User Change Type Object Changes Object type object id ----------- -------------- ----------------- ------------------ ------------- ----------- watch_tim Add child *Andenne, CPAS* contacts.Company Partner 9932 watch_tim Remove child contacts.Person Person 9932 =========== ============== ================= ================== ============= =========== """) """ A PAR without NoTVA becomes a Person, but if no first_name can be detected, then it is just a simple partner """ ln = """{"method":"PUT","alias":"PAR","id":"0000001267","time":"20130517 12:34:15", "user":"","data":{"IDPAR":"0000001267","FIRME":"Velopa","NAME2":"", "RUE":"Leuvenselaan","CP":"3300","IDPRT":"I","PAYS":"B","TEL":"", "FAX":"","COMPTE1":"","NOTVA":"","COMPTE3":"","IDPGP":"", "DEBIT":"","CREDIT":"","ATTRIB":"","IDMFC":"30","LANGUE":"F","IDBUD":"", "PROF":"15","CODE1":"","CODE2":"","CODE3":"", "DATCREA":{"__date__":{"year":1992,"month":1,"day":2}},"ALLO":"S.A.", "NB1":"","NB2":"","IDDEV":"","MEMO":"","COMPTE2":"","RUENUM":" 172", "RUEBTE":"","DEBIT2":"","CREDIT2":"","IMPDATE":{"__date__":{"year":1996,"month":8,"day":30}}, "ATTRIB2":"","CPTSYSI":"","EMAIL":"", "MVIDATE":{"__date__":{"year":0,"month":0,"day":0}},"IDUSR":"", "DOMI1":""}}""" self.assertDoesNotExist(Partner, id=1267) process_line(ln) obj = Partner.objects.get(id=1267) self.assertEqual(obj.name, "Velopa") #~ try: #~ process_line(ln) #~ self.fail("""Expected ValidationError: {'first_name': [u'Dieses Feld darf nicht leer sein.']}""") # ~ # NOTVA ist leer, also will watch_tim eine Person draus machen, # ~ # aber dazu bräuchte er auch einen Vornamen #~ except ValidationError as e: #~ pass #~ self.assertDoesNotExist(Partner,id=1267) ln = """{"method":"PUT","alias":"PAR","id":"0000000665","time":"20130517 12:33:58","user":"", "data":{"IDPAR":"0000000665","FIRME":"Petra","NAME2":"","RUE":"Beskensstraat 34","CP":"3520", "IDPRT":"I","PAYS":"B","TEL":"011/815911","FAX":"","COMPTE1":"","NOTVA":"BE-0426.896.703", "COMPTE3":"","IDPGP":"","DEBIT":"","CREDIT":"","ATTRIB":"","IDMFC":"30", "LANGUE":"3", "IDBUD":"","PROF":"12","CODE1":"","CODE2":"","CODE3":"", "DATCREA":{"__date__":{"year":1986,"month":8,"day":14}},"ALLO":"sprl","NB1":"","NB2":"", "IDDEV":"","MEMO":"","COMPTE2":"","RUENUM":"","RUEBTE":"","DEBIT2":"","CREDIT2":"", "IMPDATE":{"__date__":{"year":0,"month":0,"day":0}},"ATTRIB2":"","CPTSYSI":"", "EMAIL":"","MVIDATE":{"__date__":{"year":0,"month":0,"day":0}},"IDUSR":"","DOMI1":""}}""" process_line(ln) obj = Company.objects.get(id=665) self.assertEqual(obj.name, "Petra") # ~ INFO PAR:0000007826 (Client #7826 (u'MUSTERMANN Peter (7826)')) : Client becomes Person #~ WARNING Exception 'ValidationError([u'A Person cannot be parent for a Person'])' while processing changelog line: Client(id=7826, first_name="Peter", last_name="Mustermann").save() ln = """{"method":"PUT","alias":"PAR","id":"0000007826","time":"20130517 12:35:51","user":"", "data":{"IDPAR":"0000007826","FIRME":"Mustermann Peter","NAME2":"","RUE":"Burgundstraße","CP": "4700","IDPRT":"S","PAYS":"B","TEL":"","FAX":"","COMPTE1":"","NOTVA":"", "COMPTE3":"","IDPGP":"","DEBIT":"","CREDIT":"","ATTRIB":"A", "IDMFC":"30","LANGUE":"D","IDBUD":"","PROF":"82","CODE1":"", "CODE2":"","CODE3":"","DATCREA":{"__date__":{"year":2006,"month":1,"day":5}}, "ALLO":"Herrn","NB1":"","NB2":"","IDDEV":"","MEMO":"","COMPTE2":"", "RUENUM":" 9","RUEBTE":"","DEBIT2":"","CREDIT2":"", "IMPDATE":{"__date__":{"year":2009,"month":9,"day":22}}, "ATTRIB2":"","CPTSYSI":"","EMAIL":"","MVIDATE":{"__date__":{"year":0,"month":0,"day":0}}, "IDUSR":"******","DOMI1":""}}""" process_line(ln) self.assertDoesNotExist(Client, id=7826) """ 20130602 : datum_bis einer primären Begleitung eines Ehemaligen darf nicht leer sein. Wenn es das ist, soll watch_tim es auf PAR->DatCrea setzen. """ with translation.override('de'): self.assertDoesNotExist(Coaching, client_id=7826) ln = ln.replace('"NB2":""', '"NB2":"940702 234-24"') process_line(ln) obj = Client.objects.get(id=7826) self.assertEqual(obj.name, "Mustermann Peter") s = coachings_to_rst(obj) #~ print s self.assertEqual( s, """\ ================ ===== =========== ======== ======== ================== Begleitet seit bis Begleiter Primär Dienst Beendigungsgrund ---------------- ----- ----------- -------- -------- ------------------ 05.01.06 alicia Ja DSBE ================ ===== =========== ======== ======== ================== """) """ Kunde wurde in TIM nach Inaktive versetzt: """ ln = ln.replace('"IDPRT":"S"', '"IDPRT":"I"') process_line(ln) s = coachings_to_rst(obj) #~ print s self.assertEqual( s, """\ ================ ========== =========== ======== ======== ================== Begleitet seit bis Begleiter Primär Dienst Beendigungsgrund ---------------- ---------- ----------- -------- -------- ------------------ 05.01.06 05.01.06 alicia Ja DSBE ================ ========== =========== ======== ======== ================== """) """ 20131029 Begleitung wird in Lino manuell als nicht primär markiert. Dann wird Kunde in TIM (1) zurück nach S versetzt und (2) von ALICIA zu ROGER. """ coaching = rt.models.coachings.Coaching.objects.get(client=obj, primary=True) coaching.primary = False coaching.save() s = coachings_to_rst(obj) #~ print s self.assertEqual( s, """\ ================ ========== =========== ======== ======== ================== Begleitet seit bis Begleiter Primär Dienst Beendigungsgrund ---------------- ---------- ----------- -------- -------- ------------------ 05.01.06 05.01.06 alicia Nein DSBE ================ ========== =========== ======== ======== ================== """) ln = ln.replace('"IDPRT":"I"', '"IDPRT":"S"') process_line(ln) s = coachings_to_rst(obj) #~ print s self.assertEqual( s, """\ ================ ========== =========== ======== ======== ================== Begleitet seit bis Begleiter Primär Dienst Beendigungsgrund ---------------- ---------- ----------- -------- -------- ------------------ 05.01.06 05.01.06 alicia Nein DSBE 05.01.06 alicia Ja DSBE ================ ========== =========== ======== ======== ================== """) ln = ln.replace('"IDUSR":"******"', '"IDUSR":"******"') process_line(ln) s = coachings_to_rst(obj) #~ print s self.assertEqual( s, """\ ================ ========== =========== ======== ======== ================== Begleitet seit bis Begleiter Primär Dienst Beendigungsgrund ---------------- ---------- ----------- -------- -------- ------------------ 05.01.06 05.01.06 alicia Nein DSBE 05.01.06 17.05.13 alicia Nein DSBE 17.05.13 roger Ja ASD ================ ========== =========== ======== ======== ================== """) """ A non-client partner with empty PAR->NoTva will become a Person, not a Company. If the partner is in fact a company whose NoTva has just been forgotten, then watch_tim will raise a ValidationError: """ ln = """{"method":"POST","alias":"PAR","id":"0000087683","time":"20130610 11:26:30", "user":"******","data":{"IDPAR":"0000087683","FIRME":"Bellavilla","NAME2":"","RUE":"", "CP":"","IDPRT":"V","PAYS":"","TEL":"","FAX":"","COMPTE1":"","NOTVA":"","COMPTE3":"", "IDPGP":"","DEBIT":"","CREDIT":"","ATTRIB":"","IDMFC":"30","LANGUE":"D","IDBUD":"", "PROF":"00","CODE1":"","CODE2":"","CODE3":"", "DATCREA":{"__date__":{"year":2013,"month":6,"day":10}},"ALLO":"","NB1":"", "NB2":"","IDDEV":"","MEMO":"","COMPTE2":"","RUENUM":"","RUEBTE":"","DEBIT2":"", "CREDIT2":"","IMPDATE":{"__date__":{"year":0,"month":0,"day":0}},"ATTRIB2":"", "CPTSYSI":"","EMAIL":"","MVIDATE":{"__date__":{"year":0,"month":0,"day":0}}, "IDUSR":"","DOMI1":""}}""" self.assertDoesNotExist(Partner, id=87683) process_line(ln) #~ try: #~ self.fail("Expected ValidationError {'first_name': [u'Dieses Feld darf nicht leer sein.']}") #~ except ValidationError as e: obj = Partner.objects.get(id=87683) for m in Company, Person, Client, Household: self.assertDoesNotExist(m, id=87683) ln = """{"method":"PUT","alias":"PAR","id":"0000004124","time":"20130517 12:34:37", "user":"","data":{"IDPAR":"0000004124","FIRME":"Theves-Carlsberg","NAME2":"", "RUE":"Werthplatz 22","CP":"4700","IDPRT":"I","PAYS":"B","TEL":"","FAX":"", "COMPTE1":"","NOTVA":"BE-0999.999.999","COMPTE3":"","IDPGP":"","DEBIT":"", "CREDIT":"","ATTRIB":"W","IDMFC":"","LANGUE":"D","IDBUD":"","PROF":"80", "CODE1":"EP","CODE2":"","CODE3":"","DATCREA":{"__date__":{"year":1985, "month":4,"day":18}},"ALLO":"Eheleute","NB1":"THCA600115","NB2":"", "IDDEV":"","MEMO":"","COMPTE2":"","RUENUM":"","RUEBTE":"", "DEBIT2":"","CREDIT2":"","IMPDATE":{"__date__":{"year":0, "month":0,"day":0}},"ATTRIB2":"","CPTSYSI":"","EMAIL":"", "MVIDATE":{"__date__":{"year":0,"month":0,"day":0}}, "IDUSR":"******","DOMI1":""}}""" self.assertDoesNotExist(Partner, id=4124) process_line(ln) obj = Company.objects.get(id=4124) ln = ln.replace("BE-0999.999.999", "") process_line(ln) self.assertDoesNotExist(Company, id=4124) obj = Household.objects.get(id=4124) ln = """{"method":"PUT","alias":"PAR","id":"0000001315", "time":"20130811 10:33:20","user":"******","data":{"IDPAR":"0000001315", "FIRME":"C2D System House","NAME2":"", "RUE":"Rue des Champs","CP":"4630","IDPRT":"V","PAYS":"B","TEL":"04/567.89.10", "FAX":"04/365.31.10","COMPTE1":"JVBABE22:BE39645678910619", "NOTVA":"BE-0123.456.789","COMPTE3":"","IDPGP":"", "DEBIT":"","CREDIT":"","ATTRIB":"","IDMFC":"30","LANGUE":"F", "IDBUD":"","PROF":"22","CODE1":"","CODE2":"","CODE3":"", "DATCREA":{"__date__":{"year":1992,"month":7,"day":24}},"ALLO":"S.A.", "NB1":"EUPO","NB2":"","IDDEV":"","MEMO":"","COMPTE2":"", "RUENUM":" 8","RUEBTE":"","DEBIT2":"","CREDIT2":"", "IMPDATE":{"__date__":{"year":2012,"month":10,"day":25}}, "ATTRIB2":"","CPTSYSI":"","EMAIL":"*****@*****.**", "MVIDATE":{"__date__":{"year":2012,"month":1,"day":25}}, "IDUSR":"","DOMI1":""}} """ self.assertDoesNotExist(Partner, id=1315) process_line(ln) obj = Partner.objects.get(id=1315) obj = Company.objects.get(id=1315) for m in Person, Client, Household: self.assertDoesNotExist(m, id=1315) """{"method":"PUT","alias":"PAR","id":"0000001588","time":"20131001 10:38:08", "user":"******","data":{"IDPAR":"0000001588","FIRME":"Zentrum f.Aus- u. Weiterbildung des", "NAME2":"Mittelstandes","RUE":"Limburgerweg","CP":"4700","IDPRT":"V","PAYS":"B", "TEL":"087/59.39.89","FAX":"087/55.27.95","COMPTE1":"BBRUBEBB:BE16340143185374", "NOTVA":"BE-0999.999.999","COMPTE3":"","IDPGP":"","DEBIT":"","CREDIT":"", "ATTRIB":"","IDMFC":"30","LANGUE":"D","IDBUD":"","PROF":"62","CODE1":"", "CODE2":"","CODE3":"","DATCREA":{"__date__":{"year":1994,"month":11,"day":16}}, "ALLO":"G.o.E.","NB1":"","NB2":"","IDDEV":"","MEMO":"\n", "COMPTE2":"BKCPBEB1CPB:BE39129056571619","RUENUM":" 2","RUEBTE":"","DEBIT2":"", "CREDIT2":"","IMPDATE":{"__date__":{"year":2011,"month":10,"day":17}}, "ATTRIB2":"","CPTSYSI":"","EMAIL":"*****@*****.**", "MVIDATE":{"__date__":{"year":0,"month":0,"day":0}},"IDUSR":"","DOMI1":""}}""" """{"method":"PUT","alias":"PAR","id":"0000022307","time":"20131002 14:40:27","user":"******", "data":{"IDPAR":"0000022307","FIRME":"Lerho Renée","NAME2":"","RUE":"Lütticher Strasse 321 /A", "CP":"4721","IDPRT":"S","PAYS":"B","TEL":"","FAX":"","COMPTE1":"","NOTVA":"","COMPTE3":"", "IDPGP":"","DEBIT":"","CREDIT":"","ATTRIB":"","IDMFC":"30","LANGUE":"D","IDBUD":"","PROF":"91", "CODE1":"","CODE2":"","CODE3":"","DATCREA":{"__date__":{"year":2010,"month":9,"day":1}},"ALLO":"","NB1":"", "NB2":"941128 176-65","IDDEV":"","MEMO":"","COMPTE2":"", "RUENUM":" 000","RUEBTE":"","DEBIT2":"","CREDIT2":"", "IMPDATE":{"__date__":{"year":0,"month":0,"day":0}}, "ATTRIB2":"","CPTSYSI":"","EMAIL":"", "MVIDATE":{"__date__":{"year":0,"month":0,"day":0}},"IDUSR":"******","DOMI1":""}}""" """{"method":"PUT","alias":"PXS","id":"0000022307","time":"20131002 14:41:26","user":"******",
def test_suggest_cal_guests(self): """Tests a bugfix in :meth:`suggest_cal_guests <lino_xl.lib.courses.Course.suggest_cal_guests>`. """ User = settings.SITE.user_model Guest = rt.models.cal.Guest Event = rt.models.cal.Event EventType = rt.models.cal.EventType GuestRole = rt.models.cal.GuestRole Recurrencies = rt.models.cal.Recurrencies Room = rt.models.cal.Room Enrolment = rt.models.courses.Enrolment Course = rt.models.courses.Course Line = rt.models.courses.Line EnrolmentStates = rt.models.courses.EnrolmentStates Pupil = rt.models.pcsw.Client robin = User(username='******', user_type=UserTypes.admin) robin.save() ar = rt.login('robin') settings.SITE.verbose_client_info_message = False pupil = Pupil(first_name="First", last_name="Pupil") pupil.save() pupil2 = Pupil(first_name="Second", last_name="Pupil") pupil2.save() et = EventType(name="lesson") et.full_clean() et.save() gr = GuestRole(name="pupil") gr.save() room = Room(name="classroom") room.save() line = Line(name="Test", guest_role=gr, event_type=et, every_unit=Recurrencies.weekly) line.full_clean() line.save() course = Course(max_events=4, line=line, start_date=i2d(20150409), user=robin, monday=True, room=room) course.full_clean() course.save() # Two enrolments, one is requested, the other confirmed. Only # the confirmed enrolments will be inserted as guests. self.create_obj(Enrolment, course=course, state=EnrolmentStates.requested, pupil=pupil2) self.create_obj(Enrolment, course=course, state=EnrolmentStates.confirmed, pupil=pupil) wanted, unwanted = course.get_wanted_auto_events(ar) self.assertEqual( ar.response['info_message'], 'Generating events between 2015-04-13 and 2019-05-22 (max. 4).') self.assertEqual(len(wanted), 4) course.do_update_events.run_from_ui(ar) self.assertEqual(ar.response['success'], True) self.assertEqual(Event.objects.all().count(), 4) self.assertEqual(Guest.objects.all().count(), 4) # self.assertEqual(ar.response['info_message'], '') try: self.create_obj(Enrolment, course=course, state=EnrolmentStates.confirmed, pupil=pupil) self.fail("Expected ValidationError") except ValidationError as e: if six.PY2: expected = "{'__all__': [u'Un object Inscription avec ces " \ "champs Atelier et B\\xe9n\\xe9ficiaire existe " \ "d\\xe9j\\xe0.']}" else: expected = "{'__all__': ['Un object Inscription avec ces champs Atelier et Bénéficiaire existe déjà.']}" self.assertEqual(str(e), expected)
def objects(): Member = rt.models.households.Member MemberRoles = rt.models.households.MemberRoles Person = dd.plugins.households.person_model Type = rt.models.households.Type Household = rt.models.households.Household men = Person.objects.filter(gender=dd.Genders.male).order_by('-id') women = Person.objects.filter(gender=dd.Genders.female).order_by('-id') if dd.is_installed('humanlinks'): # avoid interference with persons created by humanlinks demo # because these have already their households: men = men.filter(household_members__isnull=True) men = men.filter(humanlinks_children__isnull=True) men = men.filter(humanlinks_parents__isnull=True) women = women.filter(humanlinks_children__isnull=True) women = women.filter(humanlinks_parents__isnull=True) women = women.filter(household_members__isnull=True) MEN = Cycler(men) WOMEN = Cycler(women) TYPES = Cycler(Type.objects.all()) if not len(MEN) or not len(WOMEN): raise Exception( "Not enough persons in {} and {} (all: {})".format( men, women, Person.objects.all())) # avoid automatic creation of children # loading_from_dump = settings.SITE.loading_from_dump # settings.SITE.loading_from_dump = True ses = rt.login() for i in range(5): pv = dict( head=MEN.pop(), partner=WOMEN.pop(), type=TYPES.pop()) ses.run( Person.create_household, action_param_values=pv) # yield ses.response['data_record'] # he = MEN.pop() # she = WOMEN.pop() # fam = Household(name=he.last_name + "-" + she.last_name, type_id=3) # yield fam # yield Member(household=fam, person=he, role=Role.objects.get(pk=1)) # yield Member(household=fam, person=she, role=Role.objects.get(pk=2)) i = 0 for m in Member.objects.filter(role=MemberRoles.head): i += 1 if i % 3 == 0: m.end_date = i2d(20020304) yield m pv = dict( head=m.person, partner=WOMEN.pop(), type=TYPES.pop()) ses.run( Person.create_household, action_param_values=pv) if False: # dd.is_installed('addresses'): Address = rt.models.addresses.Address children = set() for h in Household.objects.all(): for m in Member.objects.filter(household=h, primary=True): addr = Address.objects.get( partner=m.person, primary=True) if m.role == MemberRoles.head: addr.partner = h addr.full_clean() addr.save() else: addr.delete() children.add(m.person) h.sync_primary_address_() for p in children: p.sync_primary_address_()
def test01(self): # Create a room, event type, series and a course room = create(cal.Room, name="First Room") lesson = create(cal.EventType, name="Lesson", event_label="Lesson") line = create(courses.Line, name="First Line", event_type=lesson) obj = create( courses.Course, line=line, room=room, max_events=5, monday=True, state=courses.CourseStates.active, start_date=i2d(20140110), ) self.assertEqual(unicode(obj), "Activity #1") # self.assertEqual(settings.SITE.kernel.site, settings.SITE) # self.assertEqual(settings.SITE, dd.site) # self.assertEqual(settings.SITE.plugins, dd.apps) # self.assertEqual(settings.SITE.plugins.extjs, dd.apps.extjs) settings.SITE.verbose_client_info_message = True users.User(username="******", profile=UserTypes.admin, language="en").save() ses = settings.SITE.login("robin") # utility function which runs update_events and checks whether # info_message and output of cal.EventsByController are as # expected: def check_update(obj, msg1, msg2): res = ses.run(obj.do_update_events) self.assertEqual(res["success"], True) self.assertEqual(res["info_message"].strip(), msg1.strip()) ar = ses.spawn(cal.EventsByController, master_instance=obj) s = ar.to_rst(column_names="when_text state summary") # print s self.assertEqual(s.strip(), msg2.strip()) # Run do_update_events a first time check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Update Guests for Activity #1 Lesson 1... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 2... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 3... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 4... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 5... 0 row(s) have been updated. 5 row(s) have been updated.""", """ ================ =========== ========== When State Summary ---------------- ----------- ---------- Mon 13/01/2014 Suggested Lesson 1 Mon 20/01/2014 Suggested Lesson 2 Mon 27/01/2014 Suggested Lesson 3 Mon 03/02/2014 Suggested Lesson 4 Mon 10/02/2014 Suggested Lesson 5 ================ =========== ========== """, ) # Decrease max_events and check whether the superfluous events # get removed. obj.max_events = 3 check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 3). 2 row(s) have been updated.""", """ ================ =========== ========== When State Summary ---------------- ----------- ---------- Mon 13/01/2014 Suggested Lesson 1 Mon 20/01/2014 Suggested Lesson 2 Mon 27/01/2014 Suggested Lesson 3 ================ =========== ========== """, ) # Run do_update_events for 5 events a second time obj.max_events = 5 check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Update Guests for Activity #1 Lesson 4... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 5... 0 row(s) have been updated. 2 row(s) have been updated.""", """ ================ =========== ========== When State Summary ---------------- ----------- ---------- Mon 13/01/2014 Suggested Lesson 1 Mon 20/01/2014 Suggested Lesson 2 Mon 27/01/2014 Suggested Lesson 3 Mon 03/02/2014 Suggested Lesson 4 Mon 10/02/2014 Suggested Lesson 5 ================ =========== ========== """, ) # Now we want to skip the 2nd event. We click on "Move next" # on this event. Lino then moves all subsequent events # accordingly. ar = cal.EventsByController.request(master_instance=obj, known_values=dict(start_date=i2d(20140120))) e = ar.data_iterator[0] self.assertEqual(e.state, cal.EventStates.suggested) # res = ses.run(e.move_next) self.assertEqual(res["success"], True) expected = """\ Move down for Activity #1 Lesson 2... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Lesson 2 has been moved from 2014-01-20 to 2014-01-27. 1 row(s) have been updated.""" self.assertEqual(res["info_message"], expected) # The event is now in state "draft" because it has been # modified by the user. self.assertEqual(e.state, cal.EventStates.draft) # e.full_clean() # e.save() check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Lesson 2 has been moved from 2014-01-20 to 2014-01-27. 0 row(s) have been updated. """, """ ================ =========== ========== When State Summary ---------------- ----------- ---------- Mon 13/01/2014 Suggested Lesson 1 Mon 27/01/2014 Draft Lesson 2 Mon 03/02/2014 Suggested Lesson 3 Mon 10/02/2014 Suggested Lesson 4 Mon 17/02/2014 Suggested Lesson 5 ================ =========== ========== """, ) # Now we imagine that February 3 is the National Day in our # country. But that we create the rule for this only now. So # we have a conflict because Lino created an appointment on # that date. Of course the National Day must *not* move to an # alternative date. et = create(cal.EventType, name="Holiday", all_rooms=True) national_day = create( cal.RecurrentEvent, name="National Day", event_type=et, start_date=i2d(20140203), every_unit=cal.Recurrencies.yearly, ) res = ses.run(national_day.do_update_events) self.assertEqual(res["success"], True) expected = """\ Update Events for National Day... Generating events between 2014-02-03 and 2020-05-22 (max. 72). Reached upper date limit 2020-05-22 Update Guests for Recurrent event rule #1 National Day... 0 row(s) have been updated. Update Guests for Recurrent event rule #1 National Day... 0 row(s) have been updated. Update Guests for Recurrent event rule #1 National Day... 0 row(s) have been updated. Update Guests for Recurrent event rule #1 National Day... 0 row(s) have been updated. Update Guests for Recurrent event rule #1 National Day... 0 row(s) have been updated. Update Guests for Recurrent event rule #1 National Day... 0 row(s) have been updated. Update Guests for Recurrent event rule #1 National Day... 0 row(s) have been updated. 7 row(s) have been updated.""" self.assertEqual(res["info_message"], expected) ar = ses.spawn(cal.EventsByController, master_instance=national_day) s = ar.to_rst(column_names="when_text state") # print s self.assertEqual( s, """\ ================ =========== When State ---------------- ----------- Mon 03/02/2014 Suggested Tue 03/02/2015 Suggested Wed 03/02/2016 Suggested Fri 03/02/2017 Suggested Sat 03/02/2018 Suggested Sun 03/02/2019 Suggested Mon 03/02/2020 Suggested ================ =========== """, ) # the national day is now conflicting with our Lesson 3: ce = ar[0] self.assertEqual(ce.summary, "National Day") self.assertEqual(ce.start_date.year, 2014) ar = ses.spawn(cal.ConflictingEvents, master_instance=ce) s = ar.to_rst(column_names="when_text state auto_type") # print s self.assertEqual( s, """\ ==================== =========== ======= When State No. -------------------- ----------- ------- Mon 03/02/2014 Suggested 3 **Total (1 rows)** **3** ==================== =========== ======= """, ) # delete all lessons and start again with a virgin series cal.Event.objects.filter(event_type=lesson).delete() check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-13 and 2020-05-22 (max. 5). Lesson 4 wants 2014-02-03 but conflicts with [Event #8 ('Recurrent event rule #1 National Day')], moving to 2014-02-10. Update Guests for Activity #1 Lesson 1... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 2... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 3... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 4... 0 row(s) have been updated. Update Guests for Activity #1 Lesson 5... 0 row(s) have been updated. 5 row(s) have been updated. """, """ ================ =========== ========== When State Summary ---------------- ----------- ---------- Mon 13/01/2014 Suggested Lesson 1 Mon 20/01/2014 Suggested Lesson 2 Mon 27/01/2014 Suggested Lesson 3 Mon 10/02/2014 Suggested Lesson 4 Mon 17/02/2014 Suggested Lesson 5 ================ =========== ========== """, ) # we move the first lesson one week down and set it to draft: e = cal.Event.objects.get(event_type=lesson, auto_type=1) e.state = cal.EventStates.draft e.start_date = i2d(20140120) e.full_clean() e.save() check_update( obj, """ Update Events for Activity #1... Generating events between 2014-01-27 and 2020-05-22 (max. 5). Lesson 3 wants 2014-02-03 but conflicts with [Event #8 ('Recurrent event rule #1 National Day')], moving to 2014-02-10. 0 row(s) have been updated. """, """ ================ =========== ========== When State Summary ---------------- ----------- ---------- Mon 20/01/2014 Draft Lesson 1 Mon 27/01/2014 Suggested Lesson 2 Mon 10/02/2014 Suggested Lesson 3 Mon 17/02/2014 Suggested Lesson 4 Mon 24/02/2014 Suggested Lesson 5 ================ =========== ========== """, )
class Site(Site): the_demo_date = i2d(20141023)
def test_checkin_guest(self): """Test whether notifications are being emitted. - when a visitor checks in - when a client is modified - when a coaching is created or modified - when a note is created or modified """ User = settings.SITE.user_model Message = rt.models.notify.Message Note = rt.models.notes.Note NoteType = rt.models.notes.EventType Guest = rt.models.cal.Guest Event = rt.models.cal.Event EventType = rt.models.cal.EventType Client = rt.models.pcsw.Client ClientStates = rt.models.pcsw.ClientStates Coaching = rt.models.coachings.Coaching ContentType = rt.models.contenttypes.ContentType self.assertEqual(settings.SITE.use_websockets, False) robin = self.create_obj(User, username='******', user_type=UserTypes.admin, language="en") caroline = self.create_obj(User, username='******', user_type='200', language="fr") alicia = self.create_obj(User, username='******', first_name="Alicia", user_type='120', language="fr") roger = self.create_obj(User, username='******', user_type='420', language="en") ses = rt.login('robin') translation.activate('fr') first = self.create_obj(Client, first_name="First", last_name="Gérard", client_state=ClientStates.coached) second = self.create_obj(Client, first_name="Second", last_name="Gérard", client_state=ClientStates.coached) self.create_obj(Coaching, client=second, start_date=i2d(20130501), end_date=i2d(20140501), user=caroline) second_roger = self.create_obj(Coaching, client=second, start_date=i2d(20140501), user=roger) self.create_obj(Coaching, client=second, start_date=i2d(20140520), user=alicia) nt = self.create_obj(NoteType, name="System note") settings.SITE.site_config.update(system_note_type=nt) consultation = self.create_obj(EventType, name="consultation") # gr = self.create_obj(GuestRole, name="client") event = self.create_obj(Event, event_type=consultation, user=caroline) guest = self.create_obj(Guest, event=event, partner=first) self.assertEqual(str(guest), 'Présence #1 (22.05.2014)') # Checkin a guest res = ses.run(guest.checkin) # 'GÉRARD First (100) has started waiting for caroline' self.assertEqual( res, { 'message': "GÉRARD First (100) a commencé d'attendre caróline", 'success': True, 'refresh': True }) # it has caused a notification message: self.assertEqual(Message.objects.count(), 1) msg = Message.objects.all()[0] self.assertEqual(msg.user.username, 'caróline') self.assertEqual(msg.subject, "GÉRARD First (100) a commencé d'attendre caróline") # it does *not* cause a system note: self.assertEqual(Note.objects.count(), 0) # When a client is modified, all active coaches get a # notification. # Note that Caroline doesn't get a notification because her # coaching is not active. # Alicia doesn't get a notification because she did it herself. # Roger doesn't get notified because he is user_type 420 data = dict(first_name="Seconda", an="submit_detail") kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' url = '/api/pcsw/Clients/{}'.format(second.pk) self.client.force_login(alicia) res = self.client.put(url, **kwargs) self.assertEqual(res.status_code, 200) # self.assertEqual(Message.objects.count(), 2) # self.check_notifications() self.check_notifications(""" =================================================== ======= ============== Sujet Lié à Destinataire --------------------------------------------------- ------- -------------- GÉRARD First (100) a commencé d'attendre caróline caróline =================================================== ======= ============== """) # When a coaching is modified, all active coaches of that # client get a notification. Message.objects.all().delete() data = dict(start_date="02.05.2014", an="grid_put") data.update(mt=51) data.update(mk=second.pk) kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' self.client.force_login(robin) url = '/api/coachings/CoachingsByClient/{}'.format(second_roger.pk) res = self.client.put(url, **kwargs) self.assertEqual(res.status_code, 200) # self.check_notifications() self.check_notifications(""" ================================== ==================== =========== Subject Controlled by Recipient ---------------------------------- -------------------- ----------- robin a modifié róger / Gérard S *róger / Gérard S* Alicia ================================== ==================== =========== """) # AssignCoach. we are going to Assign caroline as coach for # first client. # Request URL:http://127.0.0.1:8000/api/newcomers/AvailableCoachesByClient/5?_dc=1469707129689&fv=EVERS%20Eberhart%20(127)%20assigned%20to%20Hubert%20Huppertz%20&fv=EVERS%20Eberhart%20(127)%20is%20now%20coached%20by%20Hubert%20Huppertz%20for%20Laufende%20Beihilfe.&fv=false&mt=48&mk=127&an=assign_coach&sr=5 # Request Method:GET # fv:EVERS Eberhart (127) assigned to Hubert Huppertz # fv:EVERS Eberhart (127) is now coached by Hubert Huppertz for Laufende Beihilfe. # fv:false # mt:48 # mk:127 # an:assign_coach # sr:5 Message.objects.all().delete() # self.assertEqual(Coaching.objects.count(), 1) # self.check_coachings() self.check_coachings(""" ==== ====================== ============== ============ ========== ========= ID Client Coached from until Coach Primary ---- ---------------------- -------------- ------------ ---------- --------- 1 GÉRARD Seconda (101) 01/05/2013 01/05/2014 caróline No 2 GÉRARD Seconda (101) 02/05/2014 róger No 3 GÉRARD Seconda (101) 20/05/2014 Alicia No ==== ====================== ============== ============ ========== ========= """) self.assertEqual(Note.objects.count(), 0) data = dict(fv=["First GÉRARD assigned to caróline", "Body", 'false'], an="assign_coach") data.update(mt=ContentType.objects.get_for_model(Client).pk) data.update(mk=first.pk) kwargs = dict(data=data) # kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' self.client.force_login(alicia) url = '/api/newcomers/AvailableCoachesByClient/{}'.format(caroline.pk) res = self.client.get(url, **kwargs) self.assertEqual(res.status_code, 200) self.check_notifications(""" =================================== ======= ============== Sujet Lié à Destinataire ----------------------------------- ------- -------------- First GÉRARD assigned to caróline caróline =================================== ======= ============== """) # self.check_coachings("") self.check_coachings(""" ==== ====================== ======================== ============ ============= ========== ID Bénéficiaire En intervention depuis au Intervenant Primaire ---- ---------------------- ------------------------ ------------ ------------- ---------- 1 GÉRARD Seconda (101) 01/05/2013 01/05/2014 caróline Non 2 GÉRARD Seconda (101) 02/05/2014 róger Non 3 GÉRARD Seconda (101) 20/05/2014 Alicia Non 4 GÉRARD First (100) 22/05/2014 caróline Oui ==== ====================== ======================== ============ ============= ========== """) self.check_notes(""" ==== ======== ==================== =================================== ID Auteur Bénéficiaire Sujet ---- -------- -------------------- ----------------------------------- 1 Alicia GÉRARD First (100) First GÉRARD assigned to caróline ==== ======== ==================== =================================== """) # Mark client as former # Request URL:http://127.0.0.1:8000/api/pcsw/Clients/181?_dc=1469714189945&an=mark_former&sr=181 # Request Method:GET # an:mark_former Message.objects.all().delete() Note.objects.all().delete() data = dict(an="mark_former") kwargs = dict(data=data) # kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' self.client.force_login(alicia) url = '/api/pcsw/Clients/{}'.format(second.pk) res = self.client.get(url, **kwargs) self.assertEqual(res.status_code, 200) res = AttrDict(json.loads(res.content)) self.assertEqual(res.message, 'This will end 2 coachings of GÉRARD Seconda (101).') self.assertEqual(res.xcallback['title'], "Confirmation") kwargs = dict() kwargs['REMOTE_USER'] = '******' self.client.force_login(alicia) url = '/callbacks/{}/yes'.format(res.xcallback['id']) res = self.client.get(url, **kwargs) self.assertEqual(res.status_code, 200) res = AttrDict(json.loads(res.content)) self.assertEqual( res.message, 'Alicia a classé GÉRARD Seconda (101) comme <b>Ancien</b>.') self.assertTrue(res.success) self.check_notifications(""" =========================================================== ======================== ============== Sujet Lié à Destinataire ----------------------------------------------------------- ------------------------ -------------- Alicia a classé GÉRARD Seconda (101) comme <b>Ancien</b>. *GÉRARD Seconda (101)* róger =========================================================== ======================== ============== """) # check two coachings have now an end_date set: # self.check_coachings() self.check_coachings(""" ==== ====================== ======================== ============ ============= ========== ID Bénéficiaire En intervention depuis au Intervenant Primaire ---- ---------------------- ------------------------ ------------ ------------- ---------- 1 GÉRARD Seconda (101) 01/05/2013 01/05/2014 caróline Non 2 GÉRARD Seconda (101) 02/05/2014 22/05/2014 róger Non 3 GÉRARD Seconda (101) 20/05/2014 22/05/2014 Alicia Non 4 GÉRARD First (100) 22/05/2014 caróline Oui ==== ====================== ======================== ============ ============= ========== """) # self.check_notes() self.check_notes(""" ==== ======== ====================== =========================================================== ID Auteur Bénéficiaire Sujet ---- -------- ---------------------- ----------------------------------------------------------- 2 Alicia GÉRARD Seconda (101) Alicia a classé GÉRARD Seconda (101) comme <b>Ancien</b>. ==== ======== ====================== =========================================================== """) # # RefuseClient # Message.objects.all().delete() Note.objects.all().delete() self.create_obj(Coaching, client=first, start_date=i2d(20130501), user=roger) first.client_state = ClientStates.newcomer first.save() data = dict(fv=["20", ""], an="refuse_client") kwargs = dict(data=data) # kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' self.client.force_login(alicia) url = '/api/pcsw/Clients/{}'.format(first.pk) res = self.client.get(url, **kwargs) self.assertEqual(res.status_code, 200) # self.check_notifications("") #if six.PY2: self.check_notifications(""" ========================================================= ====================== ============== Sujet Lié à Destinataire --------------------------------------------------------- ---------------------- -------------- Alicia a classé GÉRARD First (100) comme <b>Refusé</b>. *GÉRARD First (100)* caróline Alicia a classé GÉRARD First (100) comme <b>Refusé</b>. *GÉRARD First (100)* róger ========================================================= ====================== ============== """) # self.check_notes() self.check_notes(""" ==== ======== ==================== ========================================================= ID Auteur Bénéficiaire Sujet ---- -------- -------------------- --------------------------------------------------------- 3 Alicia GÉRARD First (100) Alicia a classé GÉRARD First (100) comme <b>Refusé</b>. ==== ======== ==================== ========================================================= """) # When a note is created, all active coaches of that # client get a notification. Message.objects.all().delete() data = dict() data.update(mt=51) data.update(mk=second.pk) data.update(an='submit_insert') data.update(subject="test", projectHidden=second.pk) kwargs = dict(data=data) kwargs['REMOTE_USER'] = '******' self.client.force_login(alicia) url = '/api/notes/NotesByProject/{}'.format(second.pk) res = self.client.post(url, **kwargs) self.assertEqual(res.status_code, 200) res = AttrDict(json.loads(res.content)) self.assertEqual(res.data_record['id'], 4) new_note_pk = res.data_record['id'] # self.check_notifications() self.check_notifications(""" ============================== ================== ============== Sujet Lié à Destinataire ------------------------------ ------------------ -------------- Alicia created Event/Note #4 *Observation #4* róger ============================== ================== ============== """) Message.objects.all().delete() data = dict() data.update(mt=51) data.update(mk=second.pk) data.update(an='submit_detail') data.update(subject="test 2", body="<p>Bla bla bla</p>", projectHidden=second.pk) kwargs = dict(data=urlencode(data)) # kwargs = dict(data=data) kwargs['REMOTE_USER'] = '******' self.client.force_login(alicia) url = '/api/notes/NotesByProject/{}'.format(new_note_pk) res = self.client.put(url, **kwargs) self.assertEqual(res.status_code, 200) # self.check_notifications() # self.check_notifications("Aucun enregistrement") self.check_notifications(""" =============================== ================== ============== Sujet Lié à Destinataire ------------------------------- ------------------ -------------- Alicia modified Event/Note #4 *Observation #4* róger =============================== ================== ============== """) self.assertEqual(Message.objects.count(), 1) msg = Message.objects.all()[0] # print msg.body self.assertEquivalent( msg.body, """ <div><p>Subject: test 2<br/>Client: [client 101] (Seconda GÉRARD)</p><p>Alicia modified [note 4] (test 2):</p><ul><li><b>Body</b> : 1 lines added</li><li><b>Subject</b> : test --> test 2</li></ul></div> """)
def test_checkin_guest(self): """Test whether notifications are being emitted. - when a visitor checks in - when a client is modified - when a coaching is modified """ User = settings.SITE.user_model Message = rt.models.notify.Message Note = rt.models.notes.Note NoteType = rt.models.notes.EventType Guest = rt.models.cal.Guest Event = rt.models.cal.Event EventType = rt.models.cal.EventType Client = rt.models.pcsw.Client Coaching = rt.models.pcsw.Coaching ContentType = rt.models.contenttypes.ContentType self.create_obj( User, username='******', profile=UserTypes.admin) caroline = self.create_obj( User, username='******', profile='200') alicia = self.create_obj( User, username='******', first_name="Alicia", profile='100') roger = self.create_obj( User, username='******', profile='400') ses = rt.login('robin') first = self.create_obj( Client, first_name="First", last_name="Client") second = self.create_obj( Client, first_name="Second", last_name="Client") self.create_obj( Coaching, client=second, start_date=i2d(20130501), end_date=i2d(20140501), user=caroline) second_roger = self.create_obj( Coaching, client=second, start_date=i2d(20140501), user=roger) self.create_obj( Coaching, client=second, start_date=i2d(20140520), user=alicia) nt = self.create_obj(NoteType, name="System note") sc = settings.SITE.site_config sc.system_note_type = nt sc.save() consultation = self.create_obj(EventType, name="consultation") # gr = self.create_obj(GuestRole, name="client") event = self.create_obj( Event, event_type=consultation, user=caroline) guest = self.create_obj(Guest, event=event, partner=first) self.assertEqual(str(guest), 'Presence #1 (22.05.2014)') # Checkin a guest res = ses.run(guest.checkin) self.assertEqual(res, { 'message': '', 'success': True, 'refresh': True}) # it has caused a notification message: self.assertEqual(Message.objects.count(), 1) # id does *not* cause a system note: self.assertEqual(Note.objects.count(), 0) # When a client is modified, all active coaches get a # notification. # Note that Caroline doesn't get a notification because this # coaching is not active. # Alicia doesn't get a notification because she did it herself. data = dict(first_name="Seconda", an="submit_detail") kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' url = '/api/pcsw/Clients/{}'.format(second.pk) res = self.client.put(url, **kwargs) self.assertEqual(res.status_code, 200) self.assertEqual(Message.objects.count(), 2) # self.check_notifications() self.check_notifications(""" +------------------------------------------------------------------------+------------------------+-----------+ | Body | Controlled by | Recipient | +========================================================================+========================+===========+ | | | caroline | +------------------------------------------------------------------------+------------------------+-----------+ | [CLIENT Seconda (101)](javascript:Lino.pcsw.Clients.detail.run\(null,{ | *CLIENT Seconda (101)* | roger | | "record_id": 101 }\)) has been modified by Alicia: | | | | | | | | * **Name** : 'Client Second' --> 'Client Seconda' | | | | * **First name** : 'Second' --> 'Seconda' | | | +------------------------------------------------------------------------+------------------------+-----------+ """) # When a coaching is modified, all active coaches of that # client get a notification. Message.objects.all().delete() data = dict(start_date="02.05.2014", an="grid_put") data.update(mt=51) data.update(mk=second.pk) kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' url = '/api/pcsw/CoachingsByClient/{}'.format(second_roger.pk) res = self.client.put(url, **kwargs) self.assertEqual(res.status_code, 200) self.check_notifications(""" +-----------------------------------------------------+------------------------+-----------+ | Body | Controlled by | Recipient | +=====================================================+========================+===========+ | **roger / Client S** has been modified by Alicia: | *CLIENT Seconda (101)* | roger | | | | | | * **Coached from** : 2014-05-01 --> 2014-05-02 | | | +-----------------------------------------------------+------------------------+-----------+ """) # AssignCoach. we are going to Assign caroline as coach for # first client. # Request URL:http://127.0.0.1:8000/api/newcomers/AvailableCoachesByClient/5?_dc=1469707129689&fv=EVERS%20Eberhart%20(127)%20assigned%20to%20Hubert%20Huppertz%20&fv=EVERS%20Eberhart%20(127)%20is%20now%20coached%20by%20Hubert%20Huppertz%20for%20Laufende%20Beihilfe.&fv=false&mt=48&mk=127&an=assign_coach&sr=5 # Request Method:GET # fv:EVERS Eberhart (127) assigned to Hubert Huppertz # fv:EVERS Eberhart (127) is now coached by Hubert Huppertz for Laufende Beihilfe. # fv:false # mt:48 # mk:127 # an:assign_coach # sr:5 Message.objects.all().delete() # self.assertEqual(Coaching.objects.count(), 1) self.check_coachings(""" ==== ====================== ============== ============ ========== ========= ID Client Coached from until Coach Primary ---- ---------------------- -------------- ------------ ---------- --------- 1 CLIENT Seconda (101) 01/05/2013 01/05/2014 caroline No 2 CLIENT Seconda (101) 02/05/2014 roger No 3 CLIENT Seconda (101) 20/05/2014 Alicia No ==== ====================== ============== ============ ========== ========= """) self.assertEqual(Note.objects.count(), 0) data = dict( fv=["First CLIENT assigned to caroline", "Body", 'false'], an="assign_coach") data.update(mt=ContentType.objects.get_for_model(Client).pk) data.update(mk=first.pk) kwargs = dict(data=data) # kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' url = '/api/newcomers/AvailableCoachesByClient/{}'.format( caroline.pk) res = self.client.get(url, **kwargs) self.assertEqual(res.status_code, 200) # self.check_notifications() self.check_notifications(""" ======================================== =============== =========== Body Controlled by Recipient ---------------------------------------- --------------- ----------- First CLIENT assigned to caroline Body caroline ======================================== =============== =========== """) self.check_coachings(""" ==== ====================== ============== ============ ========== ========= ID Client Coached from until Coach Primary ---- ---------------------- -------------- ------------ ---------- --------- 1 CLIENT Seconda (101) 01/05/2013 01/05/2014 caroline No 2 CLIENT Seconda (101) 02/05/2014 roger No 3 CLIENT Seconda (101) 20/05/2014 Alicia No 4 CLIENT First (100) 22/05/2014 caroline No ==== ====================== ============== ============ ========== ========= """) self.check_notes(""" ==== ======== ==================== =================================== ID Author Client Subject ---- -------- -------------------- ----------------------------------- 1 Alicia CLIENT First (100) First CLIENT assigned to caroline ==== ======== ==================== =================================== """) # Mark client as former # Request URL:http://127.0.0.1:8000/api/pcsw/Clients/181?_dc=1469714189945&an=mark_former&sr=181 # Request Method:GET # an:mark_former Message.objects.all().delete() Note.objects.all().delete() data = dict(an="mark_former") kwargs = dict(data=data) # kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' url = '/api/pcsw/Clients/{}'.format(second.pk) res = self.client.get(url, **kwargs) self.assertEqual(res.status_code, 200) res = AttrDict(json.loads(res.content)) self.assertEqual( res.message, 'This will end 2 coachings of CLIENT Seconda (101).') self.assertEqual(res.xcallback['title'], "Confirmation") kwargs = dict() kwargs['REMOTE_USER'] = '******' url = '/callbacks/{}/yes'.format(res.xcallback['id']) res = self.client.get(url, **kwargs) self.assertEqual(res.status_code, 200) res = AttrDict(json.loads(res.content)) self.assertEqual( res.message, 'Alicia marked CLIENT Seconda (101) as <b>Former</b>.') self.assertTrue(res.success) self.check_notifications(""" =================================================== ======================== =========== Body Controlled by Recipient --------------------------------------------------- ------------------------ ----------- Alicia marked CLIENT Seconda (101) as **Former**. *CLIENT Seconda (101)* roger =================================================== ======================== =========== """) # check two coachings have now an end_date set: self.check_coachings(""" ==== ====================== ============== ============ ========== ========= ID Client Coached from until Coach Primary ---- ---------------------- -------------- ------------ ---------- --------- 1 CLIENT Seconda (101) 01/05/2013 01/05/2014 caroline No 2 CLIENT Seconda (101) 02/05/2014 22/05/2014 roger No 3 CLIENT Seconda (101) 20/05/2014 22/05/2014 Alicia No 4 CLIENT First (100) 22/05/2014 caroline No ==== ====================== ============== ============ ========== ========= """) self.check_notes(""" ==== ======== ====================== ====================================================== ID Author Client Subject ---- -------- ---------------------- ------------------------------------------------------ 2 Alicia CLIENT Seconda (101) Alicia marked CLIENT Seconda (101) as <b>Former</b>. ==== ======== ====================== ====================================================== """) # # RefuseClient # Message.objects.all().delete() Note.objects.all().delete() data = dict(fv=["20", ""], an="refuse_client") kwargs = dict(data=data) # kwargs = dict(data=urlencode(data)) kwargs['REMOTE_USER'] = '******' url = '/api/pcsw/Clients/{}'.format(first.pk) res = self.client.get(url, **kwargs) self.assertEqual(res.status_code, 200) self.check_notifications(""" ======================================================================== ====================== =========== Body Controlled by Recipient ------------------------------------------------------------------------ ---------------------- ----------- Alicia marked CLIENT First (100) as **Refused**. PCSW is not competent *CLIENT First (100)* caroline ======================================================================== ====================== =========== """) self.check_notes(""" ==== ======== ==================== ===================================================== ID Author Client Subject ---- -------- -------------------- ----------------------------------------------------- 3 Alicia CLIENT First (100) Alicia marked CLIENT First (100) as <b>Refused</b>. ==== ======== ==================== ===================================================== """)
from lino.api import ad from ..settings import * from lino.utils import i2d SITE = Site(globals(), the_demo_date=i2d(20141023), webdav_protocol='davlink') ALLOWED_HOSTS = ['*'] DEBUG = True SECRET_KEY = "20227" # see :djangoticket:`20227`
def test_suggest_cal_guests(self): """Tests a bugfix in :meth:`suggest_cal_guests <lino_cosi.lib.courses.Course.suggest_cal_guests>`. """ User = settings.SITE.user_model Guest = rt.modules.cal.Guest Event = rt.modules.cal.Event EventType = rt.modules.cal.EventType GuestRole = rt.modules.cal.GuestRole Recurrencies = rt.modules.cal.Recurrencies Room = rt.modules.cal.Room Enrolment = rt.models.courses.Enrolment Course = rt.models.courses.Course Line = rt.models.courses.Line EnrolmentStates = rt.models.courses.EnrolmentStates Pupil = rt.modules.pcsw.Client robin = User(username='******', profile=UserTypes.admin) robin.save() ar = rt.login('robin') settings.SITE.verbose_client_info_message = False pupil = Pupil(first_name="First", last_name="Pupil") pupil.save() pupil2 = Pupil(first_name="Second", last_name="Pupil") pupil2.save() et = EventType(name="lesson") et.full_clean() et.save() gr = GuestRole(name="pupil") gr.save() room = Room(name="classroom") room.save() line = Line( name="Test", guest_role=gr, event_type=et, every_unit=Recurrencies.weekly) line.full_clean() line.save() course = Course( max_events=4, line=line, start_date=i2d(20150409), user=robin, monday=True, room=room) course.full_clean() course.save() # Two enrolments, one is requested, the other confirmed. Only # the confirmed enrolments will be inserted as guests. self.create_obj(Enrolment, course=course, state=EnrolmentStates.requested, pupil=pupil2) self.create_obj(Enrolment, course=course, state=EnrolmentStates.confirmed, pupil=pupil) wanted, unwanted = course.get_wanted_auto_events(ar) self.assertEqual( ar.response['info_message'], 'Generating events between 2015-04-13 and 2019-05-22 (max. 4).') self.assertEqual(len(wanted), 4) course.do_update_events.run_from_ui(ar) self.assertEqual(ar.response['success'], True) self.assertEqual(Event.objects.all().count(), 4) self.assertEqual(Guest.objects.all().count(), 4) # self.assertEqual(ar.response['info_message'], '') try: self.create_obj(Enrolment, course=course, state=EnrolmentStates.confirmed, pupil=pupil) self.fail("Expected ValidationError") except ValidationError as e: if AFTER18: expected = "{'__all__': [u'Un object Inscription avec ces " \ "champs Atelier et B\\xe9n\\xe9ficiaire existe " \ "d\\xe9j\\xe0.']}" else: expected = "{'__all__': [u'Un(e) Inscription avec ce Atelier et " \ "B\\xe9n\\xe9ficiaire existe d\\xe9j\\xe0.']}" self.assertEqual(str(e), expected)