Esempio n. 1
0
    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)
Esempio n. 2
0
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}
    )
Esempio n. 3
0
    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)
Esempio n. 4
0
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})
Esempio n. 5
0
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})
Esempio n. 6
0
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})
Esempio n. 7
0
    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)
Esempio n. 8
0
    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))
Esempio n. 9
0
    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))