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 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 update_from_ldap(self): """Fetch missing name from LDAP""" if not self.first_name or not self.last_name: if self.username_is_sciper(): last_name, first_name, email = get_attrs_of_sciper(self.username) if last_name: self.last_name = last_name if first_name: self.first_name = first_name if email: self.email = email self.save()
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()) 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) 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 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()) 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 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 })