Beispiel #1
0
def get_bureau_letters(request):
    if "url" in request.headers:
        url = request.headers["url"]
    elif "id" in request.headers:
        url = get_url_from_id(request.headers["id"], "single_bureau", request)
    else:
        return JsonResponse(
            {"error": "Provide proper URL / ID in header"},
            status=status.HTTP_400_BAD_REQUEST,
        )

    letters_bureau = LetterBureau.objects.filter(bureau_url=url)
    try:
        letters_client_ids = []
        for letter_bureau in letters_bureau:
            letter_client_id = get_id_from_url(letter_bureau.letter_client_url)
            letters_client_ids.append(ObjectId(letter_client_id))
        letter_client = LetterClient.objects.filter(_id__in=letters_client_ids)
        print(letter_client)
        letters = LetterClientSerializer(letter_client,
                                         context={"request": request},
                                         many=True)

        return JsonResponse(letters.data, safe=False)
    except LetterBureau.DoesNotExist:
        return JsonResponse(
            {"error": "Letter Bureau does not exist"},
            status=status.HTTP_404_NOT_FOUND,
        )
Beispiel #2
0
def get_client_letters(request):
    if "url" in request.headers:
        url = request.headers["url"]
        client_id = get_id_from_url(url)
    elif "id" in request.headers:
        client_id = request.headers["id"]
    else:
        return JsonResponse(
            {"error": "Provide proper URL / ID in header"},
            status=status.HTTP_400_BAD_REQUEST,
        )

    try:
        client_sub_url = Client.objects.values_list(
            "letter_sub_url", flat=True).get(_id=ObjectId(client_id))
        letters_client = LetterClient.objects.filter(
            letter_sub_url=client_sub_url)
        letters = LetterClientSerializer(letters_client,
                                         context={"request": request},
                                         many=True)
        # for letter_client in letters_client:
        #     letter_serializer = LetterClientSerializer(
        #         letter_client, context={"request": request}
        #     )
        #     letters.append(letter_serializer.data)

        return JsonResponse(letters.data, safe=False)
    except Client.DoesNotExist:
        return JsonResponse(
            {"error": "Client does not exist"},
            status=status.HTTP_404_NOT_FOUND,
        )
Beispiel #3
0
    def create(self, request):
        data = JSONParser().parse(request)
        try:
            client = setup_client()
        except KeyError:
            return JsonResponse(
                {
                    "error":
                    "Cannot make razorpay subscription. Check your credentials"
                },
                status=status.HTTP_403_FORBIDDEN,
            )
        pricing_id = get_id_from_url(data["pricing_url"])
        client_id = get_id_from_url(data["client_url"])
        try:
            rzp_customer_id = get_client_rzp_info(client_id)["id"]
            rzp_pricing_id = get_pricing_rzp_info(pricing_id)["id"]
        except KeyError:
            return JsonResponse(
                {
                    "error":
                    "Cannot fetch razorpay plan or customer. Check your credentials"
                },
                status=status.HTTP_403_FORBIDDEN,
            )

        # duration = Pricing.objects.filter(_id=ObjectId(pricing_id)).values('duration')[0]['duration']
        # expiry_by = (timezone.now() + timedelta(days=30)).replace(tzinfo=timezone.utc).timestamp()
        sub_data = {
            "plan_id": rzp_pricing_id,
            "customer_id": rzp_customer_id,
            "total_count": 1,
            # "expiry_by": int(expiry_by),
        }

        res = client.subscription.create(data=sub_data)
        data["rzp_sub_id"] = res["id"]

        sub_serializer = SubscriptionSerializer(data=data,
                                                context={"request": request})
        if sub_serializer.is_valid():
            sub_serializer.save()
            sub_serializer.data['razorpay'] = res
            return JsonResponse(sub_serializer.data, status=status.HTTP_200_OK)
        else:
            return JsonResponse(sub_serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
Beispiel #4
0
    def validate_bureau_url(self, bureau_url):
        bureau_id = get_id_from_url(bureau_url)
        try:
            Bureau.objects.get(_id=ObjectId(bureau_id))
        except errors.InvalidId:
            raise serializers.ValidationError('Provide proper ID')
        except Bureau.DoesNotExist:
            raise serializers.ValidationError('Bureau does not exist')

        return bureau_url
Beispiel #5
0
    def validate_letter_client_url(self, letter_client_url):
        letter_client_id = get_id_from_url(letter_client_url)
        try:
            LetterClient.objects.get(_id=ObjectId(letter_client_id))
        except errors.InvalidId:
            raise serializers.ValidationError('Provide proper ID')
        except LetterClient.DoesNotExist:
            raise serializers.ValidationError('Letter Client does not exist')

        return letter_client_url
Beispiel #6
0
    def validate_pricing_url(self, pricing_url):
        pricing_id = get_id_from_url(pricing_url)
        try:
            Pricing.objects.get(_id=ObjectId(pricing_id))
        except errors.InvalidId:
            raise serializers.ValidationError('Provide proper ID')
        except Pricing.DoesNotExist:
            raise serializers.ValidationError('Pricing does not exist')

        return pricing_url
Beispiel #7
0
    def validate_client_url(self, client_url):
        client_id = get_id_from_url(client_url)
        try:
            Client.objects.get(_id=ObjectId(client_id))
        except errors.InvalidId:
            raise serializers.ValidationError('Provide proper ID')
        except Client.DoesNotExist:
            raise serializers.ValidationError('Client does not exist')

        return client_url
Beispiel #8
0
def send_emails():
    current_time = datetime.now().replace(tzinfo=pytz.UTC)
    letter_bureaus = LetterBureau.objects.filter(next_run_at__lt=current_time)
    print("In Email Service", letter_bureaus)
    for letter_bureau in letter_bureaus:
        client = Client.objects.get(letter_sub_url=LetterClient.objects.filter(
            _id=ObjectId(get_id_from_url(letter_bureau.letter_client_url)
                         )).values("letter_sub_url")[0]["letter_sub_url"])
        send_mail(letter_bureau, client)
        print(f"Email sent to Bureau: {letter_bureau}")
        letter_bureau.save()
Beispiel #9
0
def create_letter_sub(sender, instance=None, created=False, **kwargs):
    if created:
        client_id = get_id_from_url(instance.client_url)
        pricing_id = get_id_from_url(instance.pricing_url)
        try:
            pricing = Pricing.objects.filter(_id=ObjectId(pricing_id)).values(
                "letters_count", "bureaus_count")[0]
            letters_count = pricing["letters_count"]
            bureaus_count = pricing["bureaus_count"]
            letter_sub = LetterSubscription.objects.create(
                letters_count=letters_count,
                initial_letters_count=letters_count,
                bureaus_count=bureaus_count,
            )
            letter_sub_id = str(letter_sub._id)
            letter_sub_url = f"http://127.0.0.1:8000/api/l/letter_sub/{letter_sub_id}/"

            Client.objects.filter(_id=ObjectId(client_id)).update(
                letter_sub_url=letter_sub_url)
        except errors.InvalidId:
            raise TypeError("Object ID is invalid")
Beispiel #10
0
    def has_permission(self, request, view):
        try:
            if 'url' in request.headers.keys():
                id = get_id_from_url(request.headers['url'])
            else:
                id = request.headers['id']

            token = Client.objects.values_list('session_token',
                                               flat=True).get(_id=ObjectId(id))

            return token == request.headers['token']
        except:
            return False
Beispiel #11
0
def post_letters(request):
    bad_req = status.HTTP_400_BAD_REQUEST
    not_found = status.HTTP_404_NOT_FOUND

    data = json.loads(request.data['data'])
    id_proof = request.data['id_proof']
    print(type(id_proof))

    client_url = data.pop("client_url", "")
    if client_url == "":
        client_id = data.pop("client_id", "")
        if client_id == "":
            return JsonResponse(
                {"error": "Please provide either client url or id"},
                status=bad_req,
            )
    else:
        client_id = get_id_from_url(client_url)

    try:
        client = Client.objects.get(_id=ObjectId(client_id))
        client.id_proof = id_proof
        client.save()
    except Client.DoesNotExist:
        return JsonResponse({"error": "Client does not exist"},
                            status=not_found)
    except errors.InvalidId:
        return JsonResponse({"error": "Provide proper ID"}, status=bad_req)

    letter_sub_url = client.letter_sub_url
    letter_sub_id = get_id_from_url(letter_sub_url)
    if letter_sub_url == "":
        return JsonResponse(
            {"error": "Client does not have any subscription"},
            status=status.HTTP_403_FORBIDDEN,
        )

    mappings = data.pop("mappings", [])
    bureau_ids = []
    letter_ids = []
    creditor_names = []
    account_nos = []
    mention_dates = []

    if len(mappings) > 0:
        for mapping in mappings:
            account_no = mapping.pop("account_no", "")
            creditor_name = mapping.pop("creditor_name", "")
            mention_date = parse_date(mapping.pop("mention_date", ""))
            bureau_url = mapping.pop("bureau_url", "")
            letter_url = mapping.pop("letter_url", "")

            # if not isinstance(mention_date, datetime.date):
            #     return JsonResponse(
            #         {"error": "Please provide proper date string with format %Y-%m-%d"},
            #         status=bad_req,
            #     )

            mention_dates.append(mention_date)
            account_nos.append(account_no)
            creditor_names.append(creditor_name)

            if bureau_url == "":
                bureau_id = mapping.pop("bureau_id", "")
                if bureau_id == "":
                    return JsonResponse(
                        {"error": "Please provide either bureau url or id"},
                        status=bad_req,
                    )
            else:
                bureau_id = get_id_from_url(bureau_url)

            if letter_url == "":
                letter_id = mapping.pop("letter_id", "")
                if letter_id == "":
                    return JsonResponse(
                        {"error": "Please provide either letter url or id"},
                        status=bad_req,
                    )
            else:
                letter_id = get_id_from_url(letter_url)

            try:
                Bureau.objects.get(_id=bureau_id)
                Letter.objects.get(_id=letter_id)
            except Bureau.DoesNotExist:
                JsonResponse(
                    {"error": f"Bureau with {bureau_id} does not exist"},
                    status=not_found,
                )
            except Letter.DoesNotExist:
                JsonResponse(
                    {"error": f"Letter with {letter_id} does not exist"},
                    status=not_found,
                )

            try:
                bureau_ids.append(ObjectId(bureau_id))
                letter_ids.append(ObjectId(letter_id))
            except errors.InvalidId:
                return JsonResponse(
                    {"error": "Provide proper ID"},
                    status=bad_req,
                )

        # unique_bureau_ids = list(set(bureau_ids))
        unique_letter_ids = list(set(letter_ids))

        letter_sub = LetterSubscription.objects.filter(
            _id=ObjectId(letter_sub_id))
        can_proceed, msg = validate_sub_count(
            letter_sub,
            # len(unique_bureau_ids),
            len(unique_letter_ids),
        )

        if not can_proceed:
            return JsonResponse({"error": msg}, status=bad_req)

        letter_client_mappings = []
        for letter_id in unique_letter_ids:
            letter_url = get_url_from_id(letter_id, "single_letter", request)
            letter_client = LetterClient.objects.create(
                letter_sub_url=letter_sub_url,
                letter_url=letter_url,
                account_no=account_no,
                creditor_name=creditor_name,
                mention_date=mention_date,
            )
            print("Created letter client")
            letter_client_mappings.append({letter_id: letter_client._id})

        for bureau_id, letter_id, creditor_name, account_no, mention_date in zip(
                bureau_ids, letter_ids, creditor_names, account_nos,
                mention_dates):
            letter_client_id = get_letter_client_id(letter_client_mappings,
                                                    letter_id)
            letter_client_url = get_url_from_id(letter_client_id,
                                                "single_letter_client",
                                                request)

            letter_bureau = LetterBureau(letter_client_url=letter_client_url,
                                         bureau_url=bureau_url)
            letter_bureau.pdf_file = create_letter(
                letter_id,
                bureau_id,
                client,
                Letter,
                Bureau,
                account_no=account_no,
                creditor_name=creditor_name,
                mention_date=mention_date,
            )
            duration = 'm'
            letter_bureau.save(duration)
            send_mail(letter_bureau, client)
        reduce_sub_count(
            letter_sub,
            # len(unique_bureau_ids),
            len(unique_letter_ids),
        )
    else:
        JsonResponse({"error": "Please provide atleast one letter and bureau"},
                     status=bad_req)
    return JsonResponse({
        "success": True,
        "msg": "Letters created and sent successfully"
    })