def handle(self, *args, **options): data = json.loads(sys.stdin.read()) root_user = TruffeUser.objects.get(username=179189) expenseclaim_ct = ContentType.objects.get(app_label="accounting_tools", model="expenseclaim") status_mapping = {'1': '0_draft', '2': '2_agep_validable', '3': '4_archived'} for ndf_data in data['data']: try: ay = AccountingYear.objects.get(name=ndf_data['accounting_year__name']) except: print u"AccountingYear not found !!", ndf_data['accounting_year__name'] ay = None if ay: try: costcenter = CostCenter.objects.get(account_number=ndf_data['costcenter__account_number'], accounting_year=ay) except: print u"CostCenter not found !!", ndf_data['costcenter__account_number'] costcenter = None if costcenter: try: user = TruffeUser.objects.get(username=ndf_data['creator_username']) except TruffeUser.DoesNotExist: print "Creation of user {!r}".format(ndf_data['creator_username']) user = TruffeUser(username=ndf_data['creator_username'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper(ndf_data['creator_username']) user.save() except Exception as e: print "user is root_user", e user = root_user ndf, created = ExpenseClaim.objects.get_or_create(costcenter=costcenter, accounting_year=ay, user=user, status=status_mapping[ndf_data['status']], comment=ndf_data['commentaire'], name=ndf_data['name'], nb_proofs=ndf_data['nb_just']) if created: ExpenseClaimLogging(who=user, what='imported', object=ndf).save() print "+ {!r}".format(ndf.name) if ndf_data['linked_info']: linked, created = LinkedInfo.objects.get_or_create(object_id=ndf.pk, content_type=expenseclaim_ct, user_pk=user.pk, **ndf_data['linked_info']) if created: print " (I) {!r} {!r}".format(linked.first_name, linked.last_name) for line_data in ndf_data['lines']: account = Account.objects.get(account_number=line_data['account__account_number'], accounting_year=ay) __, created = ExpenseClaimLine.objects.get_or_create(expense_claim=ndf, label=line_data['name'], account=account, proof=line_data['just'], order=line_data['order'], value=line_data['amount'], value_ttc=line_data['amount'], tva=0) if created: print " (+) {!r}".format(line_data['name']) for file_data in ndf_data['uploads']: if not os.path.isfile(os.path.join('media', 'uploads', '_generic', 'ExpenseClaim', file_data.split('/')[-1])): print " (!) Missing file {}".format(file_data) else: __, created = ExpenseClaimFile.objects.get_or_create(uploader=user, object=ndf, file=os.path.join('uploads', '_generic', 'ExpenseClaim', file_data.split('/')[-1]), defaults={'upload_date': now()}) if created: print " (L) {!r}".format(file_data)
def handle(self, *args, **options): data = json.loads(sys.stdin.read()) paris_tz = pytz.timezone("Europe/Paris") for unit_data in data['data']: try: unit = Unit.objects.get(name=unit_data['name']) except: print u"Unit not found !!", (unit_data['name'], unit_data['id_epfl']) unit = None members_role_data = unit_data['last_members_role'] if members_role_data and members_role_data['name']: try: role = Role.objects.get(id_epfl=members_role_data['id_epfl']) except: print u"Role not found !! %s (%s)" % (members_role_data['name'], members_role_data['id_epfl']) role = Role(name="None") # No role linked else: role = Role(name="None") # No role linked if unit and role: for mset_data in unit_data['membersets']: # Remove old set MemberSet.objects.filter(name=mset_data['name'], unit=unit).delete() mset, __ = MemberSet.objects.get_or_create(name=mset_data['name'], unit=unit, handle_fees=True, ldap_visible=False) mset.generates_accred = (role.name != "None") if mset.generates_accred: mset.generated_accred_type = role mset.save() print "Worked on group for ", unit, "with role", role, mset.name.encode('utf8', errors='ignore') for mship_data in mset_data['members']: try: user = TruffeUser.objects.get(username=mship_data['username']) except: print mship_data print u"User not found %s, will create..." % (mship_data['username'],) user = TruffeUser(username=mship_data['username'], is_active=True, first_name=mship_data['first_name'], last_name=mship_data['last_name'], email=mship_data['email']) user.save() if mship_data['start_date'] == 'None': print 'Membership with start = None oO ? (user %s) ' % user else: mship, __ = Membership.objects.get_or_create(user=user, group=mset) mship.start_date = paris_tz.localize(datetime.datetime.strptime(mship_data['start_date'], '%Y-%m-%d %H:%M:%S')) mship.payed_fees = mship_data['payed_fees'] mship.save() print "(+)", user
def accreds_add(request): update_current_unit(request, request.GET.get("upk")) unit = get_current_unit(request) if not Accreditation.static_rights_can("CREATE", request.user, unit): raise Http404 from units.forms2 import AccreditationAddForm from units.models import Role done = False if request.method == "POST": # If the form has been submitted... form = AccreditationAddForm(request.user, request.POST) if form.is_valid(): # If the form is valid accred = form.save(commit=False) accred.unit = unit # Try to find the user. If he dosen't exists, create it. try: user = TruffeUser.objects.get(username=form.cleaned_data["user"].strip()) except TruffeUser.DoesNotExist: user = TruffeUser() user.username = form.cleaned_data["user"].strip() user.last_name, user.first_name, user.email = get_attrs_of_sciper(user.username) user.is_active = True user.save() accred.user = user accred.save() AccreditationLog(accreditation=accred, who=request.user, type="created").save() # Check if validation is needed accred.check_if_validation_needed(request) accred.save() accred.user.clear_rights_cache() messages.success(request, _(u"Accréditation sauvegardée !")) done = True else: form = AccreditationAddForm(request.user) validables = Role.objects.filter(deleted=False, need_validation=True) return render( request, "units/accreds/add.html", {"form": form, "done": done, "unit": unit, "validables": validables} )
def handle(self, *args, **options): data = json.loads(sys.stdin.read()) root_user = TruffeUser.objects.get(username=179189) withdrawal_ct = ContentType.objects.get(app_label="accounting_tools", model="withdrawal") status_mapping = {'1': '0_draft', '2': '1_agep_validable', '3': '2_withdrawn', '4': '4_archived'} for rcash_data in data['data']: try: ay = AccountingYear.objects.get(name=rcash_data['accounting_year__name']) except: print u"AccountingYear not found !!", rcash_data['accounting_year__name'] ay = None if ay: try: costcenter = CostCenter.objects.get(account_number=rcash_data['costcenter__account_number'], accounting_year=ay) except: print u"CostCenter not found !!", rcash_data['costcenter__account_number'] costcenter = None if costcenter: try: user = TruffeUser.objects.get(username=rcash_data['creator_username']) except TruffeUser.DoesNotExist: print "Creation of user {!r}".format(rcash_data['creator_username']) user = TruffeUser(username=rcash_data['creator_username'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper(rcash_data['creator_username']) user.save() except Exception as e: print "user is root_user", e user = root_user if rcash_data['withdrawn_date'] == "None": rcash_data['withdrawn_date'] = rcash_data['desired_date'] # Histoire de fixer le problème salement rcash, created = Withdrawal.objects.get_or_create(user=user, costcenter=costcenter, accounting_year=ay, status=status_mapping[rcash_data['status']], amount=rcash_data['amount'], name=rcash_data['name'], description=rcash_data['description'], desired_date=rcash_data['desired_date'], withdrawn_date=rcash_data['withdrawn_date']) if created: WithdrawalLogging(who=user, what='imported', object=rcash).save() print "+ {!r}".format(rcash.name) if rcash_data['linked_info']: linked, created = LinkedInfo.objects.get_or_create(object_id=rcash.pk, content_type=withdrawal_ct, user_pk=user.pk, **rcash_data['linked_info']) if created: print " (I) {!r} {!r}".format(linked.first_name, linked.last_name) for file_data in rcash_data['uploads']: if not os.path.isfile(os.path.join('media', 'uploads', '_generic', 'Withdrawal', file_data.split('/')[-1])): print " (!) Missing file {}".format(file_data) else: __, created = WithdrawalFile.objects.get_or_create(uploader=user, object=rcash, file=os.path.join('uploads', '_generic', 'Withdrawal', file_data.split('/')[-1]), defaults={'upload_date': now()}) if created: print " (L) {!r}".format(file_data)
def accreds_add(request): update_current_unit(request, request.GET.get('upk')) unit = get_current_unit(request) if not Accreditation.static_rights_can('CREATE', request.user, unit): raise Http404 from units.forms2 import AccreditationAddForm from units.models import Role done = False if request.method == 'POST': # If the form has been submitted... form = AccreditationAddForm(request.user, request.POST) if form.is_valid(): # If the form is valid accred = form.save(commit=False) accred.unit = unit # Try to find the user. If he dosen't exists, create it. try: user = TruffeUser.objects.get(username=form.cleaned_data['user'].strip()) except TruffeUser.DoesNotExist: user = TruffeUser() user.username = form.cleaned_data['user'].strip() user.last_name, user.first_name, user.email = get_attrs_of_sciper(user.username) user.is_active = True user.save() accred.user = user accred.save() AccreditationLog(accreditation=accred, who=request.user, type='created').save() # Check if validation is needed accred.check_if_validation_needed(request) accred.save() accred.user.clear_rights_cache() messages.success(request, _(u'Accréditation sauvegardée !')) done = True else: form = AccreditationAddForm(request.user) validables = Role.objects.filter(deleted=False, need_validation=True) return render(request, 'units/accreds/add.html', {'form': form, 'done': done, 'unit': unit, 'validables': validables})
def import_members(request, pk): from members.models import MemberSet, Membership, MemberSetLogging memberset = get_object_or_404(MemberSet, pk=pk) if not memberset.rights_can('EDIT', request.user): raise Http404 logs = [] if request.method == 'POST': form = MembershipImportForm(request.user, memberset, request.POST, request.FILES) if form.is_valid(): edition_extra_data = {} try: imp_file = json.loads(request.FILES['imported'].read()) for user_data in imp_file: if isinstance(user_data, (int, str, unicode)): username = str(user_data) fees = False elif type(user_data) is list: username = user_data[0] fees = len(user_data) > 1 and user_data[1] else: continue try: user = TruffeUser.objects.get(username=username) except TruffeUser.DoesNotExist: if re.match('^\d{6}$', username): user = TruffeUser(username=username, is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper(username) user.save() else: logs.append(('danger', username, _(u'Impossible de créer l\'utilisateur'))) user = None if user: if memberset.membership_set.filter(user=user, end_date=None).exists(): logs.append(('warning', user, _(u'L\'utilisateur est déjà membre de ce groupe'))) else: # Copy the fees status if asked payed_fees = form.cleaned_data.get('copy_fees_status', False) and fees Membership(group=memberset, user=user, payed_fees=payed_fees).save() logs.append(('success', user, _(u'Utilisateur ajouté avec succès'))) edition_extra_data[user.get_full_name()] = ["None", "Membre"] MemberSetLogging(who=request.user, what='edited', object=memberset, extra_data=json.dumps({'edited': edition_extra_data})).save() except ValueError: logs.append(('danger', _(u'ERREUR'), _(u'Le fichier ne peut pas être lu correctement, l\'import a été annulé'))) else: form = MembershipImportForm(request.user, memberset) logs.sort(key=lambda x: x[0]) return render(request, 'members/membership/import.html', {'form': form, 'logs': logs, 'group': memberset, 'display_list_panel': True})
def membership_add(request, pk): from members.models import MemberSet, MemberSetLogging memberset = get_object_or_404(MemberSet, pk=pk) if not memberset.rights_can('EDIT', request.user): raise Http404 done = False done_user = None if request.method == 'POST': form = MembershipAddForm(request.user, memberset, request.POST) if form.is_valid(): # Try to find the user. If he dosen't exists, create it. try: user = TruffeUser.objects.get( username=form.cleaned_data['user']) except TruffeUser.DoesNotExist: user = TruffeUser(username=form.cleaned_data['user'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper( user.username) user.save() if memberset.membership_set.filter(user=user, end_date=None).exists(): pass else: membership = form.save(commit=False) membership.group = memberset membership.user = user membership.save() MemberSetLogging( who=request.user, what='edited', object=memberset, extra_data='{"edited": {"%s": ["None", "Membre"]}}' % (user.get_full_name(), )).save() done_user = user done = True form = MembershipAddForm(request.user, memberset) else: form = MembershipAddForm(request.user, memberset) return render(request, 'members/membership/add.html', { 'form': form, 'done': done, 'done_user': done_user, 'group': memberset })
def import_members_list(request, pk): from members.models import MemberSet, Membership, MemberSetLogging memberset = get_object_or_404(MemberSet, pk=pk) if not memberset.rights_can('EDIT', request.user): raise Http404 logs = [] if request.method == 'POST': form = MembershipImportListForm(request.POST, request.FILES) if form.is_valid(): edition_extra_data = {} for username in form.cleaned_data['data'].split('\n'): username = username.strip() if username: try: user = TruffeUser.objects.get(username=username) except TruffeUser.DoesNotExist: if re.match('^\d{6}$', username): user = TruffeUser(username=username, is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper(username) user.save() else: logs.append(('danger', username, _(u'Impossible de créer l\'utilisateur'))) user = None if user: if memberset.membership_set.filter(user=user, end_date=None).exists(): logs.append(('warning', user, _(u'L\'utilisateur est déjà membre de ce groupe'))) else: Membership(group=memberset, user=user, payed_fees=form.cleaned_data['fee_status']).save() logs.append(('success', user, _(u'Utilisateur ajouté avec succès'))) edition_extra_data[user.get_full_name()] = ["None", "Membre"] MemberSetLogging(who=request.user, what='edited', object=memberset, extra_data=json.dumps({'edited': edition_extra_data})).save() else: form = MembershipImportListForm() logs.sort(key=lambda x: x[0]) return render(request, 'members/membership/import_list.html', {'form': form, 'logs': logs, 'group': memberset, 'display_list_panel': True})
def membership_add(request, pk): from members.models import MemberSet, MemberSetLogging memberset = get_object_or_404(MemberSet, pk=pk) if not memberset.rights_can('EDIT', request.user): raise Http404 done = False done_user = None if request.method == 'POST': form = MembershipAddForm(request.user, memberset, request.POST) if form.is_valid(): # Try to find the user. If he dosen't exists, create it. try: user = TruffeUser.objects.get(username=form.cleaned_data['user']) except TruffeUser.DoesNotExist: user = TruffeUser(username=form.cleaned_data['user'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper(user.username) user.save() if memberset.membership_set.filter(user=user).count(): pass else: membership = form.save(commit=False) membership.group = memberset membership.user = user membership.save() MemberSetLogging(who=request.user, what='edited', object=memberset, extra_data='{"edited": {"%s": ["None", "Membre"]}}' % (user.get_full_name(),)).save() done_user = user done = True form = MembershipAddForm(request.user, memberset) else: form = MembershipAddForm(request.user, memberset) return render(request, 'members/membership/add.html', {'form': form, 'done': done, 'done_user': done_user, 'group': memberset})
def handle(self, *args, **options): data = json.loads(sys.stdin.read()) paris_tz = pytz.timezone("Europe/Paris") root_user = TruffeUser.objects.get(username=179189) cashbook_ct = ContentType.objects.get(app_label="accounting_tools", model="cashbook") status_mapping = { '1': '0_draft', '2': '1_unit_validable', '3': '4_archived' } helper_mapping = { 1: '0_withdraw', 2: '1_deposit', 3: '2_sell', 4: '4_buy', 5: '3_invoice', 6: '6_input', 7: '7_output', 8: '5_reimburse' } for jdc_data in data['data']: try: ay = AccountingYear.objects.get( name=jdc_data['accounting_year__name']) except: print u"AccountingYear not found !!", jdc_data[ 'accounting_year__name'] ay = None if ay: try: costcenter = CostCenter.objects.get( account_number=jdc_data['costcenter__account_number'], accounting_year=ay) except: print u"CostCenter not found !!", jdc_data[ 'costcenter__account_number'] costcenter = None if costcenter: try: if jdc_data['creator_username'] is None: jdc_data['creator_username'] = 195835 user = TruffeUser.objects.get( username=jdc_data['creator_username']) except TruffeUser.DoesNotExist: print "Creation of user {!r}".format( jdc_data['creator_username']) user = TruffeUser( username=jdc_data['creator_username'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper( jdc_data['creator_username']) user.save() except Exception as e: print "user is root_user", e user = root_user jdc, created = CashBook.objects.get_or_create( costcenter=costcenter, accounting_year=ay, user=user, status=status_mapping[jdc_data['status']], comment=jdc_data['commentaire'], name=jdc_data['name'], nb_proofs=jdc_data['nb_just']) if created: CashBookLogging(who=user, what='imported', object=jdc).save() print "+ {!r}".format(jdc.name) if jdc_data['linked_info']: try: linked, created = LinkedInfo.objects.get_or_create( object_id=jdc.pk, content_type=cashbook_ct, user_pk=user.pk, **jdc_data['linked_info']) if created: print " (I) {!r} {!r}".format( linked.first_name, linked.last_name) except Exception as e: print e print u"LinkedInfo not found !!", jdc_data[ 'linked_info'] if jdc_data['rcash']: try: withdrawal = Withdrawal.objects.get( **jdc_data['rcash']) if jdc.proving_object != withdrawal: jdc.proving_object = withdrawal jdc.save() print " (R) {!r}".format(withdrawal.name) except: print u"Rcash not found !! {!r}".format( jdc_data['rcash']) if jdc_data['credit_card']: try: creditcard = ImportedCreditCard.objects.get( **jdc_data['credit_card']) jdc.proving_object = creditcard jdc.save() print " (C) {!r}".format(creditcard.name) except: print u"Creditcard not found !! {!r}".format( jdc_data['credit_card']) for line_data in jdc_data['lines']: try: account = Account.objects.get( account_number=line_data[ 'account__account_number'], accounting_year=ay) date = paris_tz.localize( datetime.datetime.strptime( line_data['date'], '%Y-%m-%d')) __, created = CashBookLine.objects.get_or_create( cashbook=jdc, label=line_data['name'], proof=line_data['just'], account=account, order=line_data['order'], value=line_data['amount'], value_ttc=line_data['amount'], tva=0, date=date, helper=helper_mapping[line_data['help']]) if created: print " (+) {!r}".format(line_data['name']) except: print u"Account not found !! {!r}".format( line_data['account__account_number']) for file_data in jdc_data['uploads']: if not os.path.isfile( os.path.join('media', 'uploads', '_generic', 'CashBook', file_data.split('/')[-1])): print " (!) Missing file {}".format(file_data) else: __, created = CashBookFile.objects.get_or_create( uploader=user, object=jdc, file=os.path.join('uploads', '_generic', 'CashBook', file_data.split('/')[-1]), defaults={'upload_date': now()}) if created: print " (L) {!r}".format(file_data)
def handle(self, *args, **options): data = json.loads(sys.stdin.read()) root_user = TruffeUser.objects.get(username=179189) expenseclaim_ct = ContentType.objects.get(app_label="accounting_tools", model="expenseclaim") status_mapping = { '1': '0_draft', '2': '2_agep_validable', '3': '4_archived' } for ndf_data in data['data']: try: ay = AccountingYear.objects.get( name=ndf_data['accounting_year__name']) except: print u"AccountingYear not found !!", ndf_data[ 'accounting_year__name'] ay = None if ay: try: costcenter = CostCenter.objects.get( account_number=ndf_data['costcenter__account_number'], accounting_year=ay) except: print u"CostCenter not found !!", ndf_data[ 'costcenter__account_number'] costcenter = None if costcenter: try: user = TruffeUser.objects.get( username=ndf_data['creator_username']) except TruffeUser.DoesNotExist: print "Creation of user {!r}".format( ndf_data['creator_username']) user = TruffeUser( username=ndf_data['creator_username'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper( ndf_data['creator_username']) user.save() except Exception as e: print "user is root_user", e user = root_user ndf, created = ExpenseClaim.objects.get_or_create( costcenter=costcenter, accounting_year=ay, user=user, status=status_mapping[ndf_data['status']], comment=ndf_data['commentaire'], name=ndf_data['name'], nb_proofs=ndf_data['nb_just']) if created: ExpenseClaimLogging(who=user, what='imported', object=ndf).save() print "+ {!r}".format(ndf.name) if ndf_data['linked_info']: linked, created = LinkedInfo.objects.get_or_create( object_id=ndf.pk, content_type=expenseclaim_ct, user_pk=user.pk, **ndf_data['linked_info']) if created: print " (I) {!r} {!r}".format( linked.first_name, linked.last_name) for line_data in ndf_data['lines']: account = Account.objects.get(account_number=line_data[ 'account__account_number'], accounting_year=ay) __, created = ExpenseClaimLine.objects.get_or_create( expense_claim=ndf, label=line_data['name'], account=account, proof=line_data['just'], order=line_data['order'], value=line_data['amount'], value_ttc=line_data['amount'], tva=0) if created: print " (+) {!r}".format(line_data['name']) for file_data in ndf_data['uploads']: if not os.path.isfile( os.path.join('media', 'uploads', '_generic', 'ExpenseClaim', file_data.split('/')[-1])): print " (!) Missing file {}".format(file_data) else: __, created = ExpenseClaimFile.objects.get_or_create( uploader=user, object=ndf, file=os.path.join('uploads', '_generic', 'ExpenseClaim', file_data.split('/')[-1]), defaults={'upload_date': now()}) if created: print " (L) {!r}".format(file_data)
def setup_testing_users_units(): from units.models import Unit, Role, Accreditation now = timezone.now() admin_user = TruffeUser.objects.create_superuser(username='******', password='******', first_name='admin', last_name='admin') admin_user.mobile = "0123456789" admin_user.adresse = "rue machin" admin_user.nom_banque = "Postfinance" admin_user.iban_ou_ccp = "0009876543210" admin_user.save() Unit(id=2, name='My unit', description='unit very nice', is_commission=True, is_equipe=True).save() user1 = TruffeUser.objects.create_user(username='******', password='******', first_name='user1', last_name='user1') user1.mobile = "0123456789" user1.adresse = "rue machin" user1.nom_banque = "Postfinance" user1.iban_ou_ccp = "0009876543210" user1.save() user2 = TruffeUser.objects.create_user(username='******', password='******', first_name='user2', last_name='user2') user2.mobile = "0123456789" user2.adresse = "rue machin" user2.nom_banque = "Postfinance" user2.iban_ou_ccp = "0009876543210" user2.save() user3 = TruffeUser.objects.create_user(username='******', password='******', first_name='user3', last_name='user3') user3.mobile = "0123456789" user3.adresse = "rue machin" user3.nom_banque = "Postfinance" user3.iban_ou_ccp = "0009876543210" user3.save() user4 = TruffeUser.objects.create_user(username='******', password='******', first_name='user4', last_name='user4') user4.mobile = "0123456789" user4.adresse = "rue machin" user4.nom_banque = "Postfinance" user4.iban_ou_ccp = "0009876543210" user4.save() Role(id=1, name="role0", order=1, need_validation=False).save() Role(id=2, name="role1", order=2, need_validation=False, access='PRESIDENCE').save() Role(id=3, name="role2", order=3, need_validation=False, access='TRESORERIE').save() Role(id=4, name="role3", order=4, need_validation=False, access='SECRETARIAT').save() Role(id=5, name="role4", order=5, need_validation=False, access='INFORMATIQUE').save() Accreditation(unit_id=settings.ROOT_UNIT_PK, user=admin_user, role_id=1, need_validation=True).save() Accreditation(unit_id=2, user=user1, role_id=2, need_validation=False).save() Accreditation(unit_id=2, user=user2, role_id=3, need_validation=False).save() Accreditation(unit_id=2, user=user3, role_id=4, need_validation=False).save() Accreditation(unit_id=2, user=user4, role_id=5, need_validation=False).save() system_user = TruffeUser(pk=settings.SYSTEM_USER_PK, username='******', first_name='system', last_name='system', is_active=True, is_superuser=True, last_login=now, date_joined=now) system_user.set_password('system') system_user.save() return admin_user
def handle(self, *args, **options): data = json.loads(sys.stdin.read()) paris_tz = pytz.timezone("Europe/Paris") for unit_data in data['data']: try: unit = Unit.objects.get(name=unit_data['name']) except: print(u"Unit not found !!", (unit_data['name'], unit_data['id_epfl'])) unit = None members_role_data = unit_data['last_members_role'] if members_role_data and members_role_data['name']: try: role = Role.objects.get( id_epfl=members_role_data['id_epfl']) except: print(u"Role not found !! %s (%s)" % (members_role_data['name'], members_role_data['id_epfl'])) role = Role(name="None") # No role linked else: role = Role(name="None") # No role linked if unit and role: for mset_data in unit_data['membersets']: # Remove old set MemberSet.objects.filter(name=mset_data['name'], unit=unit).delete() mset, __ = MemberSet.objects.get_or_create( name=mset_data['name'], unit=unit, handle_fees=True, ldap_visible=False) mset.generates_accred = (role.name != "None") if mset.generates_accred: mset.generated_accred_type = role mset.save() print("Worked on group for ", unit, "with role", role, mset.name.encode('utf8', errors='ignore')) for mship_data in mset_data['members']: try: user = TruffeUser.objects.get( username=mship_data['username']) except: print(mship_data) print(u"User not found %s, will create..." % (mship_data['username'], )) user = TruffeUser( username=mship_data['username'], is_active=True, first_name=mship_data['first_name'], last_name=mship_data['last_name'], email=mship_data['email']) user.save() if mship_data['start_date'] == 'None': print( 'Membership with start = None oO ? (user %s) ' % user) else: mship, __ = Membership.objects.get_or_create( user=user, group=mset) mship.start_date = paris_tz.localize( datetime.datetime.strptime( mship_data['start_date'], '%Y-%m-%d %H:%M:%S')) mship.payed_fees = mship_data['payed_fees'] mship.save() print("(+)", user)
def memberset_api(request, pk): from members.models import MemberSet, MemberSetLogging, Membership key = request.META.get('HTTP_X_TRUFFE2_KEY', request.GET.get('key')) if not key: raise Http404 memberset = get_object_or_404(MemberSet, pk=pk) if not memberset.api_secret_key: raise Http404 if key != memberset.api_secret_key: raise Http404 system_user = TruffeUser.objects.get(pk=settings.SYSTEM_USER_PK) result = {'error': 'WRONG_METHOD'} if request.method == 'GET': result = [] for member in memberset.membership_set.filter(end_date=None): data = { 'sciper': member.user.username, 'added_date': str(member.start_date) } if memberset.handle_fees: data['payed_fees'] = member.payed_fees result.append(data) result = {'members': result} if request.method in ['PUT', 'POST', 'DELETE']: try: body_data = json.loads(request.body.decode()) except: r = HttpResponse(json.dumps({'error': 'JSON_PARSE_ERROR'})) r.content_type = 'application/json' return r if request.method == 'PUT': if 'member' not in body_data: result = {'error': 'MISSING_MEMBER'} else: if 'sciper' not in body_data['member']: result = {'error': 'MISSING_SCIPER'} else: try: user = TruffeUser.objects.get( username=body_data['member']['sciper']) except TruffeUser.DoesNotExist: user = TruffeUser(username=body_data['member']['sciper'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper( user.username) if not user.email: result = {'error': 'WRONG_SCIPER'} user = None else: user.save() if user: membership, created = Membership.objects.get_or_create( user=user, group=memberset, end_date=None) result = {'result': 'ALREADY_OK'} if memberset.handle_fees and 'payed_fees' in body_data[ 'member'] and membership.payed_fees != body_data[ 'member']['payed_fees']: membership.payed_fees = body_data['member'][ 'payed_fees'] membership.save() result = {'result': 'UPDATED_FEE'} if not created: MemberSetLogging( who=system_user, what='edited', object=memberset, extra_data= '{"edited": {"Cotisation %s": ["%s ", "%s"]}}' % (membership.user.get_full_name(), not membership.payed_fees, membership.payed_fees)).save() if created: MemberSetLogging( who=system_user, what='edited', object=memberset, extra_data='{"edited": {"%s": ["None", "Membre"]}}' % (user.get_full_name(), )).save() result = {'result': 'CREATED'} if request.method == 'DELETE': if 'member' not in body_data: result = {'error': 'MISSING_MEMBER'} else: if 'sciper' not in body_data['member']: result = {'error': 'MISSING_SCIPER'} else: try: user = TruffeUser.objects.get( username=body_data['member']['sciper']) except TruffeUser.DoesNotExist: user = None result = {'error': 'UNKNOWN_USER'} if user: membership = Membership.objects.filter( group=memberset, user=user, end_date=None).first() if membership: membership.end_date = now() membership.save() MemberSetLogging( who=system_user, what='edited', object=memberset, extra_data='{"edited": {"%s": ["Membre", "None"]}}' % (membership.user.get_full_name(), )).save() result = {'result': 'REMOVED'} else: result = {'result': 'ALREADY_OK'} if request.method == 'POST': if 'members' not in body_data: result = {'error': 'MISSING_MEMBER'} else: added = [] updated = [] already_ok = [] errors = [] deleted = [] members_ok = [] for member_data in body_data['members']: if 'sciper' not in member_data: errors.append({'sciper': '?', 'error': 'MISSING_SCIPER'}) else: try: user = TruffeUser.objects.get( username=member_data['sciper']) except TruffeUser.DoesNotExist: user = TruffeUser(username=member_data['sciper'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper( user.username) if not user.email: errors.append({ 'sciper': member_data['sciper'], 'error': 'WRONG_SCIPER' }) user = None else: user.save() if user: membership, created = Membership.objects.get_or_create( user=user, group=memberset, end_date=None) result = 'ALREADY_OK' if memberset.handle_fees and 'payed_fees' in member_data and membership.payed_fees != member_data[ 'payed_fees']: membership.payed_fees = member_data['payed_fees'] membership.save() result = 'UPDATED_FEE' if not created: MemberSetLogging( who=system_user, what='edited', object=memberset, extra_data= '{"edited": {"Cotisation %s": ["%s ", "%s"]}}' % (membership.user.get_full_name(), not membership.payed_fees, membership.payed_fees)).save() if created: MemberSetLogging( who=system_user, what='edited', object=memberset, extra_data= '{"edited": {"%s": ["None", "Membre"]}}' % (user.get_full_name(), )).save() result = 'CREATED' if result == 'ALREADY_OK': already_ok.append(member_data['sciper']) elif result == 'UPDATED_FEE': updated.append(member_data['sciper']) elif result == 'CREATED': added.append(member_data['sciper']) members_ok.append(membership.pk) for old_membership in Membership.objects.filter( group=memberset, end_date=None).exclude(pk__in=members_ok): old_membership.end_date = now() old_membership.save() MemberSetLogging( who=system_user, what='edited', object=memberset, extra_data='{"edited": {"%s": ["Membre", "None"]}}' % (old_membership.user.get_full_name(), )).save() deleted.append(old_membership.user.username) result = { 'created': added, 'updated': updated, 'already_ok': already_ok, 'deleted': deleted, 'errors': errors, } r = HttpResponse(json.dumps(result)) r.content_type = 'application/json' return r
def import_members_list(request, pk): from members.models import MemberSet, Membership, MemberSetLogging memberset = get_object_or_404(MemberSet, pk=pk) if not memberset.rights_can('EDIT', request.user): raise Http404 logs = [] if request.method == 'POST': form = MembershipImportListForm(request.POST, request.FILES) if form.is_valid(): edition_extra_data = {} for username in form.cleaned_data['data'].split('\n'): username = username.strip() if username: try: user = TruffeUser.objects.get(username=username) except TruffeUser.DoesNotExist: if re.match(r'^\d{6}$', username): user = TruffeUser(username=username, is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper( username) user.save() else: logs.append( ('danger', username, _(u'Impossible de créer l\'utilisateur'))) user = None if user: if memberset.membership_set.filter( user=user, end_date=None).exists(): logs.append(( 'warning', user, _(u'L\'utilisateur est déjà membre de ce groupe' ))) else: Membership(group=memberset, user=user, payed_fees=form. cleaned_data['fee_status']).save() logs.append(('success', user, _(u'Utilisateur ajouté avec succès'))) edition_extra_data[user.get_full_name()] = [ "None", "Membre" ] MemberSetLogging(who=request.user, what='edited', object=memberset, extra_data=json.dumps( {'edited': edition_extra_data})).save() else: form = MembershipImportListForm() logs.sort(key=lambda x: x[0]) return render(request, 'members/membership/import_list.html', { 'form': form, 'logs': logs, 'group': memberset, 'display_list_panel': True })
def handle(self, *args, **options): data = json.loads(sys.stdin.read()) paris_tz = pytz.timezone("Europe/Paris") root_user = TruffeUser.objects.get(username=179189) cashbook_ct = ContentType.objects.get(app_label="accounting_tools", model="cashbook") status_mapping = {"1": "0_draft", "2": "1_unit_validable", "3": "4_archived"} helper_mapping = { 1: "0_withdraw", 2: "1_deposit", 3: "2_sell", 4: "4_buy", 5: "3_invoice", 6: "6_input", 7: "7_output", 8: "5_reimburse", } for jdc_data in data["data"]: try: ay = AccountingYear.objects.get(name=jdc_data["accounting_year__name"]) except: print u"AccountingYear not found !!", jdc_data["accounting_year__name"] ay = None if ay: try: costcenter = CostCenter.objects.get( account_number=jdc_data["costcenter__account_number"], accounting_year=ay ) except: print u"CostCenter not found !!", jdc_data["costcenter__account_number"] costcenter = None if costcenter: try: if jdc_data["creator_username"] is None: jdc_data["creator_username"] = 195835 user = TruffeUser.objects.get(username=jdc_data["creator_username"]) except TruffeUser.DoesNotExist: print "Creation of user {!r}".format(jdc_data["creator_username"]) user = TruffeUser(username=jdc_data["creator_username"], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper(jdc_data["creator_username"]) user.save() except Exception as e: print "user is root_user", e user = root_user jdc, created = CashBook.objects.get_or_create( costcenter=costcenter, accounting_year=ay, user=user, status=status_mapping[jdc_data["status"]], comment=jdc_data["commentaire"], name=jdc_data["name"], nb_proofs=jdc_data["nb_just"], ) if created: CashBookLogging(who=user, what="imported", object=jdc).save() print "+ {!r}".format(jdc.name) if jdc_data["linked_info"]: try: linked, created = LinkedInfo.objects.get_or_create( object_id=jdc.pk, content_type=cashbook_ct, user_pk=user.pk, **jdc_data["linked_info"] ) if created: print " (I) {!r} {!r}".format(linked.first_name, linked.last_name) except Exception as e: print e print u"LinkedInfo not found !!", jdc_data["linked_info"] if jdc_data["rcash"]: try: withdrawal = Withdrawal.objects.get(**jdc_data["rcash"]) if jdc.proving_object != withdrawal: jdc.proving_object = withdrawal jdc.save() print " (R) {!r}".format(withdrawal.name) except: print u"Rcash not found !! {!r}".format(jdc_data["rcash"]) if jdc_data["credit_card"]: try: creditcard = ImportedCreditCard.objects.get(**jdc_data["credit_card"]) jdc.proving_object = creditcard jdc.save() print " (C) {!r}".format(creditcard.name) except: print u"Creditcard not found !! {!r}".format(jdc_data["credit_card"]) for line_data in jdc_data["lines"]: try: account = Account.objects.get( account_number=line_data["account__account_number"], accounting_year=ay ) date = paris_tz.localize(datetime.datetime.strptime(line_data["date"], "%Y-%m-%d")) __, created = CashBookLine.objects.get_or_create( cashbook=jdc, label=line_data["name"], proof=line_data["just"], account=account, order=line_data["order"], value=line_data["amount"], value_ttc=line_data["amount"], tva=0, date=date, helper=helper_mapping[line_data["help"]], ) if created: print " (+) {!r}".format(line_data["name"]) except: print u"Account not found !! {!r}".format(line_data["account__account_number"]) for file_data in jdc_data["uploads"]: if not os.path.isfile( os.path.join("media", "uploads", "_generic", "CashBook", file_data.split("/")[-1]) ): print " (!) Missing file {}".format(file_data) else: __, created = CashBookFile.objects.get_or_create( uploader=user, object=jdc, file=os.path.join("uploads", "_generic", "CashBook", file_data.split("/")[-1]), defaults={"upload_date": now()}, ) if created: print " (L) {!r}".format(file_data)
def import_members(request, pk): from members.models import MemberSet, Membership, MemberSetLogging memberset = get_object_or_404(MemberSet, pk=pk) if not memberset.rights_can('EDIT', request.user): raise Http404 logs = [] if request.method == 'POST': form = MembershipImportForm(request.user, memberset, request.POST, request.FILES) if form.is_valid(): edition_extra_data = {} try: imp_file = json.loads( request.FILES['imported'].read().decode()) for user_data in imp_file: if isinstance(user_data, (int, str, str)): username = str(user_data) fees = False elif type(user_data) is list: username = user_data[0] fees = len(user_data) > 1 and user_data[1] else: continue try: user = TruffeUser.objects.get(username=username) except TruffeUser.DoesNotExist: if re.match(r'^\d{6}$', username): user = TruffeUser(username=username, is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper( username) user.save() else: logs.append( ('danger', username, _(u'Impossible de créer l\'utilisateur'))) user = None if user: if memberset.membership_set.filter( user=user, end_date=None).exists(): logs.append(( 'warning', user, _(u'L\'utilisateur est déjà membre de ce groupe' ))) else: # Copy the fees status if asked payed_fees = form.cleaned_data.get( 'copy_fees_status', False) and fees Membership(group=memberset, user=user, payed_fees=payed_fees).save() logs.append(('success', user, _(u'Utilisateur ajouté avec succès'))) edition_extra_data[user.get_full_name()] = [ "None", "Membre" ] MemberSetLogging(who=request.user, what='edited', object=memberset, extra_data=json.dumps({ 'edited': edition_extra_data })).save() except ValueError: logs.append(( 'danger', _(u'ERREUR'), _(u'Le fichier ne peut pas être lu correctement, l\'import a été annulé' ))) else: form = MembershipImportForm(request.user, memberset) logs.sort(key=lambda x: x[0]) return render(request, 'members/membership/import.html', { 'form': form, 'logs': logs, 'group': memberset, 'display_list_panel': True })
def handle(self, *args, **options): data = json.loads(sys.stdin.read()) root_user = TruffeUser.objects.get(username=179189) withdrawal_ct = ContentType.objects.get(app_label="accounting_tools", model="withdrawal") status_mapping = { '1': '0_draft', '2': '1_agep_validable', '3': '2_withdrawn', '4': '4_archived' } for rcash_data in data['data']: try: ay = AccountingYear.objects.get( name=rcash_data['accounting_year__name']) except: print u"AccountingYear not found !!", rcash_data[ 'accounting_year__name'] ay = None if ay: try: costcenter = CostCenter.objects.get( account_number=rcash_data[ 'costcenter__account_number'], accounting_year=ay) except: print u"CostCenter not found !!", rcash_data[ 'costcenter__account_number'] costcenter = None if costcenter: try: user = TruffeUser.objects.get( username=rcash_data['creator_username']) except TruffeUser.DoesNotExist: print "Creation of user {!r}".format( rcash_data['creator_username']) user = TruffeUser( username=rcash_data['creator_username'], is_active=True) user.last_name, user.first_name, user.email = get_attrs_of_sciper( rcash_data['creator_username']) user.save() except Exception as e: print "user is root_user", e user = root_user if rcash_data['withdrawn_date'] == "None": rcash_data['withdrawn_date'] = rcash_data[ 'desired_date'] # Histoire de fixer le problème salement rcash, created = Withdrawal.objects.get_or_create( user=user, costcenter=costcenter, accounting_year=ay, status=status_mapping[rcash_data['status']], amount=rcash_data['amount'], name=rcash_data['name'], description=rcash_data['description'], desired_date=rcash_data['desired_date'], withdrawn_date=rcash_data['withdrawn_date']) if created: WithdrawalLogging(who=user, what='imported', object=rcash).save() print "+ {!r}".format(rcash.name) if rcash_data['linked_info']: linked, created = LinkedInfo.objects.get_or_create( object_id=rcash.pk, content_type=withdrawal_ct, user_pk=user.pk, **rcash_data['linked_info']) if created: print " (I) {!r} {!r}".format( linked.first_name, linked.last_name) for file_data in rcash_data['uploads']: if not os.path.isfile( os.path.join('media', 'uploads', '_generic', 'Withdrawal', file_data.split('/')[-1])): print " (!) Missing file {}".format(file_data) else: __, created = WithdrawalFile.objects.get_or_create( uploader=user, object=rcash, file=os.path.join('uploads', '_generic', 'Withdrawal', file_data.split('/')[-1]), defaults={'upload_date': now()}) if created: print " (L) {!r}".format(file_data)