Example #1
0
def members_cel_subscription(request):

    serializer = serializers.MembersSubscriptionSerializer(data=request.data)
    serializer.is_valid(
        raise_exception=True)  # log.critical(serializer.errors)
    try:
        dolibarr = DolibarrAPI(api_key=request.user.profile.dolibarr_token)
        member = dolibarr.get(model='members', login=str(request.user))
    except DolibarrAPIException as e:
        return Response(
            {
                'error':
                'Unable to resolve user in dolibarr! error : {}'.format(e)
            },
            status=status.HTTP_400_BAD_REQUEST)

    current_member = dolibarr.get(model='members', id=member[0]['id'])
    try:
        cyclos = CyclosAPI(token=request.user.profile.cyclos_token, mode='cel')
    except CyclosAPIException:
        return Response({'error': 'Unable to connect to Cyclos!'},
                        status=status.HTTP_400_BAD_REQUEST)

    if current_member['type'].lower() == 'particulier':
        member_name = '{} {}'.format(current_member['firstname'],
                                     current_member['lastname'])
    else:
        member_name = current_member['company']

    try:
        data = cyclos.post(method='user/search', data={'keywords': 'Z00001'})
        euskal_moneta_cyclos_id = data['result']['pageItems'][0]['id']
    except (KeyError, IndexError, CyclosAPIException) as e:
        log.critical(e)
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    query_data = {
        'type':
        str(settings.CYCLOS_CONSTANTS['payment_types']
            ['virement_inter_adherent']),
        'amount':
        serializer.data['amount'],
        'currency':
        str(settings.CYCLOS_CONSTANTS['currencies']['eusko']),
        'from':
        cyclos.user_id,
        'to':
        euskal_moneta_cyclos_id,
        'description':
        'Cotisation - {} - {}'.format(current_member['login'], member_name),
    }
    cyclos.post(method='payment/perform', data=query_data)

    # Register new subscription
    data_res_subscription = {
        'start_date': serializer.data['start_date'].strftime('%s'),
        'end_date': serializer.data['end_date'].strftime('%s'),
        'amount': serializer.data['amount'],
        'label': serializer.data['label']
    }

    try:
        res_id_subscription = dolibarr.post(
            model='members/{}/subscriptions'.format(member[0]['id']),
            data=data_res_subscription)
    except Exception as e:
        log.critical("data_res_subscription: {}".format(data_res_subscription))
        log.critical(e)
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
    if str(res_id_subscription) == '-1':
        return Response({'data returned': str(res_id_subscription)},
                        status=status.HTTP_409_CONFLICT)
    # Register new payment
    payment_account = 4
    payment_type = 'VIR'
    data_res_payment = {
        'date': arrow.now('Europe/Paris').timestamp,
        'type': payment_type,
        'label': serializer.data['label'],
        'amount': serializer.data['amount']
    }
    model_res_payment = 'accounts/{}/lines'.format(payment_account)
    try:
        res_id_payment = dolibarr.post(model=model_res_payment,
                                       data=data_res_payment)

        log.info("res_id_payment: {}".format(res_id_payment))
    except DolibarrAPIException as e:
        log.critical("model: {}".format(model_res_payment))
        log.critical("data_res_payment: {}".format(data_res_payment))
        log.critical(e)
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    # Link this new subscription with this new payment
    data_link_sub_payment = {'fk_bank': res_id_payment}
    model_link_sub_payment = 'subscriptions/{}'.format(res_id_subscription)
    try:
        res_id_link_sub_payment = dolibarr.patch(model=model_link_sub_payment,
                                                 data=data_link_sub_payment)

        log.info("res_id_link_sub_payment: {}".format(res_id_link_sub_payment))
    except DolibarrAPIException as e:
        log.critical("model: {}".format(model_link_sub_payment))
        log.critical("data_link_sub_payment: {}".format(data_link_sub_payment))
        log.critical(e)
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    # Link this payment with the related-member
    data_link_payment_member = {
        'label':
        '{} {}'.format(member[0]['firstname'], member[0]['lastname']),
        'type':
        'member',
        'url_id':
        member[0]['id'],
        'url':
        '{}/adherents/card.php?rowid={}'.format(settings.DOLIBARR_PUBLIC_URL,
                                                member[0]['id'])
    }
    model_link_payment_member = 'accounts/{}/lines/{}/links'.format(
        payment_account, res_id_payment)
    try:
        res_id_link_payment_member = dolibarr.post(
            model=model_link_payment_member, data=data_link_payment_member)

        log.info("res_id_link_payment_member: {}".format(
            res_id_link_payment_member))
    except DolibarrAPIException as e:
        log.critical("model: {}".format(model_link_payment_member))
        log.critical(
            "data_link_payment_member: {}".format(data_link_payment_member))
        log.critical(e)
        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    res = {
        'id_subscription': res_id_subscription,
        'id_payment': res_id_payment,
        'link_sub_payment': res_id_link_sub_payment,
        'id_link_payment_member': res_id_link_payment_member,
        'member': current_member
    }

    return Response(res, status=status.HTTP_201_CREATED)
Example #2
0
def validate_first_connection(request):
    """
    validate_first_connection
    """
    serializer = serializers.ValidFirstConnectionSerializer(data=request.data)
    serializer.is_valid(
        raise_exception=True)  # log.critical(serializer.errors)

    try:
        token_data = jwt.decode(request.data['token'],
                                settings.JWT_SECRET,
                                issuer='first-connection',
                                audience='guest')
    except jwt.InvalidTokenError:
        return Response({'error': 'Unable to read token!'},
                        status=status.HTTP_400_BAD_REQUEST)

    try:
        dolibarr = DolibarrAPI()
        dolibarr_token = dolibarr.login(
            login=settings.APPS_ANONYMOUS_LOGIN,
            password=settings.APPS_ANONYMOUS_PASSWORD)
        # We check if the user already exist, if he already exist we return a 400
        try:
            dolibarr.get(model='users',
                         login=token_data['login'],
                         api_key=dolibarr_token)
            return Response({'error': 'User already exist!'},
                            status=status.HTTP_201_CREATED)
        except DolibarrAPIException:
            pass

        # 1) Créer une réponse à une SecurityQuestion (créer aussi une SecurityAnswer).
        if serializer.data.get('question_id', False):
            # We got a question_id
            q = models.SecurityQuestion.objects.get(
                id=serializer.data['question_id'])

        elif serializer.data.get('question_text', False):
            # We didn't got a question_id, but a question_text: we need to create a new SecurityQuestion object
            q = models.SecurityQuestion.objects.create(
                question=serializer.data['question_text'])

        else:
            return Response(
                {
                    'status':
                    ('Error: You need to provide at least one thse two fields: '
                     'question_id or question_text')
                },
                status=status.HTTP_400_BAD_REQUEST)

        res = models.SecurityAnswer.objects.create(owner=token_data['login'],
                                                   question=q)
        res.set_answer(raw_answer=serializer.data['answer'])
        res.save()

        if not res:
            Response({'error': 'Unable to save security answer!'},
                     status=status.HTTP_400_BAD_REQUEST)

        # 2) Dans Dolibarr, créer un utilisateur lié à l'adhérent
        member = dolibarr.get(model='members',
                              login=token_data['login'],
                              api_key=dolibarr_token)

        create_user = '******'.format(member[0]['id'])
        create_user_data = {'login': token_data['login']}

        # user_id will be the ID for this new user
        user_id = dolibarr.post(model=create_user,
                                data=create_user_data,
                                api_key=dolibarr_token)

        # 3) Dans Dolibarr, ajouter ce nouvel utilisateur dans le groupe "Adhérents"
        user_group_model = 'users/{}/setGroup/{}'.format(
            user_id, settings.DOLIBARR_CONSTANTS['groups']['adherents'])
        user_group_res = dolibarr.get(model=user_group_model,
                                      api_key=dolibarr_token)
        if not user_group_res == 1:
            raise EuskalMonetaAPIException

        # 4) Dans Cyclos, activer l'utilisateur
        cyclos = CyclosAPI(mode='login')
        cyclos_token = cyclos.login(auth_string=b64encode(
            bytes(
                '{}:{}'.format(settings.APPS_ANONYMOUS_LOGIN,
                               settings.APPS_ANONYMOUS_PASSWORD),
                'utf-8')).decode('ascii'))

        cyclos_user_id = cyclos.get_member_id_from_login(
            member_login=token_data['login'], token=cyclos_token)

        active_user_data = {
            'user': cyclos_user_id,  # ID de l'utilisateur
            'status': 'ACTIVE'
        }
        cyclos.post(method='userStatus/changeStatus',
                    data=active_user_data,
                    token=cyclos_token)

        # 5) Dans Cyclos, initialiser le mot de passe d'un utilisateur
        password_data = {
            'user':
            cyclos_user_id,  # ID de l'utilisateur
            'type':
            str(settings.CYCLOS_CONSTANTS['password_types']['login_password']),
            'newPassword':
            request.data['new_password'],  # saisi par l'utilisateur
            'confirmNewPassword':
            request.data['confirm_password'],  # saisi par l'utilisateur
        }
        cyclos.post(method='password/change',
                    data=password_data,
                    token=cyclos_token)

        return Response({'status': 'success'})

    except (EuskalMonetaAPIException, DolibarrAPIException, CyclosAPIException,
            KeyError, IndexError):
        return Response({'error': 'Unable to get user data for this login!'},
                        status=status.HTTP_400_BAD_REQUEST)