def test_ipn_invalid_fail(self): responses.add(responses.POST, 'https://www.sandbox.paypal.com/cgi-bin/webscr', body='INVALID', status=200) responseId = str(ObjectId()) response = Response( id=ObjectId(responseId), form=self.formId, date_modified=datetime.datetime.now(), date_created=datetime.datetime.now(), value={"a":"b", "email": "*****@*****.**"}, paymentInfo={"total": .5, "currency": "USD","items": [{"name": "a", "description": "b", "amount": .25, "quantity": 1}, {"name": "a2", "description": "b2", "amount": .25, "quantity": 1}]} ).save() ipn_value = f"mc_gross=0.50&protection_eligibility=Eligible&address_status=confirmed&item_number1=Base Registration&payer_id=VE2HLZ5ZKU7BE&address_street=123 ABC Street&payment_date=06:42:00 Jun 30, 2018 PDT&payment_status=Completed&charset=windows-1252&address_zip=30022&first_name=Ashwin&mc_fee=0.31&address_country_code=US&address_name=outplayed apps¬ify_version=3.9&custom={responseId}&payer_status=unverified&[email protected]&address_country=United States&num_cart_items=1&address_city=Johns creek&verify_sign=AWkT50gtrA0iXnh55b939tXXlAFYAfxG.wdPFrayvThp7Tw1hro.K3JV&[email protected]&txn_id=6TS1068787252245S&payment_type=instant&payer_business_name=outplayed apps&last_name=Ramaswami&address_state=GA&item_name1=Base Registration&[email protected]&payment_fee=0.31&quantity1=1&receiver_id=T4A6C58SP7PP2&txn_type=cart&mc_gross_1=0.50&mc_currency=USD&residence_country=US&test_ipn=1&transaction_subject=&payment_gross=0.50&ipn_track_id=d61ac3d69a842" response = self.send_ipn(responseId, ipn_value, fail=True) self.assertIn('Rejected by PayPal', response) response = self.view_response(responseId) self.assertTrue("payment_status_detail" not in response) self.assertEqual(len(response["payment_trail"]), 1) detail_history_one = response["payment_trail"][0] detail_history_one.pop("date") # detail_history_one.pop("date_created") # detail_history_one.pop("date_modified") self.assertEqual(detail_history_one, { "value": {'mc_gross': '0.50', 'protection_eligibility': 'Eligible', 'address_status': 'confirmed', 'item_number1': 'Base Registration', 'payer_id': 'VE2HLZ5ZKU7BE', 'address_street': '123 ABC Street', 'payment_date': '06:42:00 Jun 30, 2018 PDT', 'payment_status': 'Completed', 'charset': 'windows-1252', 'address_zip': '30022', 'first_name': 'Ashwin', 'mc_fee': '0.31', 'address_country_code': 'US', 'address_name': 'outplayed apps', 'notify_version': '3.9', 'custom': responseId, 'payer_status': 'unverified', 'business': '*****@*****.**', 'address_country': 'United States', 'num_cart_items': '1', 'address_city': 'Johns creek', 'verify_sign': 'AWkT50gtrA0iXnh55b939tXXlAFYAfxG.wdPFrayvThp7Tw1hro.K3JV', 'payer_email': '*****@*****.**', 'txn_id': '6TS1068787252245S', 'payment_type': 'instant', 'payer_business_name': 'outplayed apps', 'last_name': 'Ramaswami', 'address_state': 'GA', 'item_name1': 'Base Registration', 'receiver_email': '*****@*****.**', 'payment_fee': '0.31', 'quantity1': '1', 'receiver_id': 'T4A6C58SP7PP2', 'txn_type': 'cart', 'mc_gross_1': '0.50', 'mc_currency': 'USD', 'residence_country': 'US', 'test_ipn': '1', 'payment_gross': '0.50', 'ipn_track_id': 'd61ac3d69a842'}, 'method': 'paypal_ipn', 'status': 'ERROR', 'id': 'Rejected by PayPal: https://www.sandbox.paypal.com/cgi-bin/webscr', '_cls': 'chalicelib.models.PaymentTrailItem'} ) self.assertTrue("email_trail" not in response) self.assertEqual(response["paid"], False) self.assertEqual(response["amount_paid"], "0")
def test_create_response(self): oid = ObjectId() response = Response(id=oid, date_created=datetime.datetime.now()) response.save() self.assertEqual(response.id, oid) self.assertEqual(response.to_son().to_dict()["_cls"], "chalicelib.models.Response")
def test_ipn_refund(self): responses.add(responses.POST, 'https://www.sandbox.paypal.com/cgi-bin/webscr', body='VERIFIED', status=200) responseId = str(ObjectId()) response = Response( id=ObjectId(responseId), form=self.formId, date_modified=datetime.datetime.now(), date_created=datetime.datetime.now(), value={"a":"b", "email": "*****@*****.**"}, paymentInfo={"total": .5, "currency": "USD","items": [{"name": "a", "description": "b", "amount": .25, "quantity": 1}, {"name": "a2", "description": "b2", "amount": .25, "quantity": 1}]}, payment_status_detail=[PaymentStatusDetailItem(amount="1080.00", method="paypal_ipn", currency="USD", id="id1", date=datetime.datetime.now())], paid=True, amount_paid="1080.0" ).save() ipn_value = f"mc_gross=-1080.00&protection_eligibility=Eligible&item_number1=Double Room&payer_id=A4CSL993V3BDG&address_street=1 Main St&payment_date=07:43:04 Jun 23, 2019 PDT&payment_status=Refunded&charset=windows-1252&address_zip=95131&mc_shipping=0.00&mc_handling=0.00&first_name=test&mc_fee=-31.32&address_country_code=US&address_name=test buyer¬ify_version=3.9&reason_code=refund&custom={responseId}&[email protected]&address_country=United States&mc_handling1=0.00&address_city=San Jose&verify_sign=Ajpb2sm-lsDSWA5XwZfLh0PpsG6IAYl-yqrJx2GLHimSQ3aPkkfr3i2Y&[email protected]&mc_shipping1=0.00&tax1=0.00&parent_txn_id=23X19291EC9014330&txn_id=69B89632XK721821J&payment_type=instant&last_name=buyer&address_state=CA&item_name1=Double Room ($1200/person)&[email protected]&payment_fee=-31.32&shipping_discount=0.00&quantity1=1&receiver_id=T4A6C58SP7PP2&insurance_amount=0.00&discount=120.00&mc_gross_1=1200.00&mc_currency=USD&residence_country=US&test_ipn=1&shipping_method=Default&transaction_subject=&payment_gross=-1080.00&ipn_track_id=539cae4d23348" response = self.send_ipn(responseId, ipn_value) response = self.view_response(responseId) self.assertTrue("payment_status_detail" in response) self.assertEqual(len(response["payment_trail"]), 1) detail_history_one = response["payment_trail"][0] detail_history_one.pop("date") # TODO: why do these two not exist? detail_history_one.pop("date_created") detail_history_one.pop("date_modified") self.assertEqual(detail_history_one, {'value': {'mc_gross': '-1080.00', 'protection_eligibility': 'Eligible', 'item_number1': 'Double Room', 'payer_id': 'A4CSL993V3BDG', 'address_street': '1 Main St', 'payment_date': '07:43:04 Jun 23, 2019 PDT', 'payment_status': 'Refunded', 'charset': 'windows-1252', 'address_zip': '95131', 'mc_shipping': '0.00', 'mc_handling': '0.00', 'first_name': 'test', 'mc_fee': '-31.32', 'address_country_code': 'US', 'address_name': 'test buyer', 'notify_version': '3.9', 'reason_code': 'refund', 'custom': responseId, 'business': '*****@*****.**', 'address_country': 'United States', 'mc_handling1': '0.00', 'address_city': 'San Jose', 'verify_sign': 'Ajpb2sm-lsDSWA5XwZfLh0PpsG6IAYl-yqrJx2GLHimSQ3aPkkfr3i2Y', 'payer_email': '*****@*****.**', 'mc_shipping1': '0.00', 'tax1': '0.00', 'parent_txn_id': '23X19291EC9014330', 'txn_id': '69B89632XK721821J', 'payment_type': 'instant', 'last_name': 'buyer', 'address_state': 'CA', 'item_name1': 'Double Room ($1200/person)', 'receiver_email': '*****@*****.**', 'payment_fee': '-31.32', 'shipping_discount': '0.00', 'quantity1': '1', 'receiver_id': 'T4A6C58SP7PP2', 'insurance_amount': '0.00', 'discount': '120.00', 'mc_gross_1': '1200.00', 'mc_currency': 'USD', 'residence_country': 'US', 'test_ipn': '1', 'shipping_method': 'Default', 'payment_gross': '-1080.00', 'ipn_track_id': '539cae4d23348'}, 'method': 'paypal_ipn', 'status': 'SUCCESS', 'id': '69B89632XK721821J', '_cls': 'chalicelib.models.PaymentTrailItem'}) self.assertTrue("email_trail" in response) self.assertEqual(len(response["email_trail"]), 1) self.assertEqual(response["paid"], False) self.assertEqual(response["amount_paid"], "0.0")
def form_response_export(formId): """Export response""" """In progress, not done yet.""" from ..main import app form = Form.objects.get({ "_id": ObjectId(formId) }).only("formOptions", "cff_permissions") app.check_permissions(form, "Responses_Export") # responses = Response.objects.raw({"form": Form}).values() return {"res": responses} return Response(body="hello world!", status_code=200, headers={"Content-Type": "text/plain"})
def test_invalid_merchant_id(self): responseId = str(ObjectId()) response = Response( id=ObjectId(responseId), form=self.formId, date_modified=datetime.datetime.now(), date_created=datetime.datetime.now(), value={ "a": "b", "email": "*****@*****.**" }, paymentInfo={ "total": 0.5, "currency": "USD", "items": [ { "name": "a", "description": "b", "amount": 0.25, "quantity": 1 }, { "name": "a2", "description": "b2", "amount": 0.25, "quantity": 1 }, ], }, ).save() self.make_request(responseId, SAMPLE_BODY, fail=True) response = self.view_response(responseId) detail_payment_one = response["payment_trail"][0] detail_payment_one.pop("date") detail_payment_one.pop("date_created") detail_payment_one.pop("date_modified") self.assertEqual(detail_payment_one["status"], "ERROR") self.assertEqual(detail_payment_one["id"], "CCAvenue config not found for merchant id: mid123.")
def test_update_ccavenue_hash_with_template_avlues(self): merchant_id = str(uuid.uuid4()) response = Response( amount_paid=20, paymentInfo={ "currency": "INR", "total": "50" }, value={"name": "Abc 123"}, ) config = CCAvenueConfig( access_code="access_code", merchant_id=merchant_id, SECRET_working_key="SECRET_working_key", ).save() ccavenuePaymentMethodInfo = { "merchant_id": merchant_id, "billing_name": "{{value.name}}", "billing_address": "{{value.name}}", "billing_city": "{{value.name}}", "billing_state": "{{value.name}}", "billing_zip": "{{value.name}}", "billing_tel": "{{value.name}}", "billing_email": "{{value.name}}", } response = decrypt( update_ccavenue_hash("formId", ccavenuePaymentMethodInfo, response)["encRequest"], "SECRET_working_key", ) self.assertEqual(response["merchant_id"], merchant_id) self.assertEqual(response["billing_name"], "Abc 123") self.assertEqual(response["billing_address"], "Abc 123") self.assertEqual(response["billing_city"], "Abc 123") self.assertEqual(response["billing_state"], "Abc 123") self.assertEqual(response["billing_zip"], "Abc 123") self.assertEqual(response["billing_tel"], "Abc 123") self.assertEqual(response["billing_email"], "Abc 123")
def test_update_ccavenue_hash_with_subaccount(self): """Does changing the subaccount id affect the response? """ merchant_id = str(uuid.uuid4()) response = Response(amount_paid=20, paymentInfo={ "currency": "INR", "total": "50" }) config = CCAvenueConfig( access_code="access_code", merchant_id=merchant_id, SECRET_working_key="SECRET_working_key", ).save() ccavenuePaymentMethodInfo1 = update_ccavenue_hash( "formId", {"merchant_id": merchant_id}, response) ccavenuePaymentMethodInfo2 = update_ccavenue_hash( "formId", {"merchant_id": merchant_id}, response) ccavenuePaymentMethodInfo3 = update_ccavenue_hash( "formId", { "merchant_id": merchant_id, "sub_account_id": "sub_account_id" }, response, ) response1 = decrypt(ccavenuePaymentMethodInfo1["encRequest"], "SECRET_working_key") del response1["order_id"] response2 = decrypt(ccavenuePaymentMethodInfo2["encRequest"], "SECRET_working_key") del response2["order_id"] response3 = decrypt(ccavenuePaymentMethodInfo3["encRequest"], "SECRET_working_key") del response3["order_id"] self.assertEqual(response1, response2) self.assertNotEqual(response2, response3)
def test_ipn_subscr_failed(self): responses.add( responses.POST, "https://www.sandbox.paypal.com/cgi-bin/webscr", body="VERIFIED", status=200, ) responseId = str(ObjectId()) response = Response( id=ObjectId(responseId), form=self.formId, date_modified=datetime.datetime.now(), date_created=datetime.datetime.now(), value={"a": "b", "email": "*****@*****.**"}, paymentInfo={ "total": 0.5, "currency": "USD", "items": [ {"name": "a", "description": "b", "amount": 0.25, "quantity": 1}, {"name": "a2", "description": "b2", "amount": 0.25, "quantity": 1}, ], }, ).save() ipn_value = f"mc_gross=0.50&protection_eligibility=Eligible&address_status=confirmed&item_number1=Base Registration&payer_id=VE2HLZ5ZKU7BE&address_street=123 ABC Street&payment_date=06:42:00 Jun 30, 2018 PDT&payment_status=Completed&charset=windows-1252&address_zip=30022&first_name=Ashwin&mc_fee=0.31&address_country_code=US&address_name=outplayed apps¬ify_version=3.9&custom={responseId}&payer_status=unverified&[email protected]&address_country=United States&num_cart_items=1&address_city=Johns creek&verify_sign=AWkT50gtrA0iXnh55b939tXXlAFYAfxG.wdPFrayvThp7Tw1hro.K3JV&[email protected]&payment_type=instant&payer_business_name=outplayed apps&last_name=Ramaswami&address_state=GA&item_name1=Base Registration&[email protected]&payment_fee=0.31&quantity1=1&receiver_id=T4A6C58SP7PP2&txn_type=subscr_failed&mc_gross_1=0.50&mc_currency=USD&residence_country=US&test_ipn=1&transaction_subject=&payment_gross=0.50&ipn_track_id=d61ac3d69a842" response = self.send_ipn(responseId, ipn_value) response = self.view_response(responseId) self.assertTrue("payment_status_detail" not in response) self.assertEqual(len(response["payment_trail"]), 1) detail_history_one = response["payment_trail"][0] detail_history_one.pop("date") self.assertEqual(detail_history_one["status"], "ERROR") self.assertEqual( detail_history_one["id"], "txn_type is not supported and must be manually handled.", )
def test_template_format_date(self): self.assertEqual( fill_string_from_template(Response(value={"date": "2000-10-10"}), "{{value.date | format_date}}"), "Oct 10, 2000", )
def setUp(self): self.response = Response(**RESPONSE)
if isinstance(o, Decimal): return float(o) return super(DecimalEncoder, self).default(o) for response in query['Items']: response = json.loads(json.dumps(response, cls=DecimalEncoder)) res = Response( date_created=dateutil.parser.parse(response["date_created"]), date_modified=dateutil.parser.parse(response["date_last_modified"]), form=ObjectId(formIdNew), paymentInfo=response["paymentInfo"], value=response["value"], paid=response["PAID"], payment_trail=[ PaymentTrailItem(date=dateutil.parser.parse(i["date"]), value=i["value"], status=i["status"], id=i["value"]["txn_id"], method="paypal_ipn") for i in response.get("IPN_HISTORY", []) ] or [], payment_status_detail=[ PaymentStatusDetailItem(date=dateutil.parser.parse(i["date"]), amount=i["amount"], currency=i["currency"], method="paypal_ipn" if i["method"] == "paypal" else i["method"]) for i in response.get("PAYMENT_HISTORY", []) ] or []) res.save()
def test_ipn_verified_success(self): responses.add( responses.POST, "https://www.sandbox.paypal.com/cgi-bin/webscr", body="VERIFIED", status=200, ) responseId = str(ObjectId()) response = Response( id=ObjectId(responseId), form=self.formId, date_modified=datetime.datetime.now(), date_created=datetime.datetime.now(), value={"a": "b", "email": "*****@*****.**"}, paymentInfo={ "total": 0.5, "currency": "USD", "items": [ {"name": "a", "description": "b", "amount": 0.25, "quantity": 1}, {"name": "a2", "description": "b2", "amount": 0.25, "quantity": 1}, ], }, ).save() ipn_value = f"mc_gross=0.50&protection_eligibility=Eligible&address_status=confirmed&item_number1=Base Registration&payer_id=VE2HLZ5ZKU7BE&address_street=123 ABC Street&payment_date=06:42:00 Jun 30, 2018 PDT&payment_status=Completed&charset=windows-1252&address_zip=30022&first_name=Ashwin&mc_fee=0.31&address_country_code=US&address_name=outplayed apps¬ify_version=3.9&custom={responseId}&payer_status=unverified&[email protected]&address_country=United States&num_cart_items=1&address_city=Johns creek&verify_sign=AWkT50gtrA0iXnh55b939tXXlAFYAfxG.wdPFrayvThp7Tw1hro.K3JV&[email protected]&txn_id=6TS1068787252245S&payment_type=instant&payer_business_name=outplayed apps&last_name=Ramaswami&address_state=GA&item_name1=Base Registration&[email protected]&payment_fee=0.31&quantity1=1&receiver_id=T4A6C58SP7PP2&txn_type=cart&mc_gross_1=0.50&mc_currency=USD&residence_country=US&test_ipn=1&transaction_subject=&payment_gross=0.50&ipn_track_id=d61ac3d69a842" self.send_ipn(responseId, ipn_value) response = self.view_response(responseId) detail_payment_one = response["payment_status_detail"][0] detail_payment_one.pop("date") detail_payment_one.pop("date_created") detail_payment_one.pop("date_modified") self.assertEqual( detail_payment_one, { "currency": "USD", "amount": "0.50", "method": "paypal_ipn", "id": "6TS1068787252245S", "_cls": "chalicelib.models.PaymentStatusDetailItem", }, ) detail_history_one = response["payment_trail"][0] detail_history_one.pop("date") detail_history_one.pop("date_created") detail_history_one.pop("date_modified") self.assertEqual( detail_history_one, { "value": { "mc_gross": "0.50", "protection_eligibility": "Eligible", "address_status": "confirmed", "item_number1": "Base Registration", "payer_id": "VE2HLZ5ZKU7BE", "address_street": "123 ABC Street", "payment_date": "06:42:00 Jun 30, 2018 PDT", "payment_status": "Completed", "charset": "windows-1252", "address_zip": "30022", "first_name": "Ashwin", "mc_fee": "0.31", "address_country_code": "US", "address_name": "outplayed apps", "notify_version": "3.9", "custom": responseId, "payer_status": "unverified", "business": "*****@*****.**", "address_country": "United States", "num_cart_items": "1", "address_city": "Johns creek", "verify_sign": "AWkT50gtrA0iXnh55b939tXXlAFYAfxG.wdPFrayvThp7Tw1hro.K3JV", "payer_email": "*****@*****.**", "txn_id": "6TS1068787252245S", "payment_type": "instant", "payer_business_name": "outplayed apps", "last_name": "Ramaswami", "address_state": "GA", "item_name1": "Base Registration", "receiver_email": "*****@*****.**", "payment_fee": "0.31", "quantity1": "1", "receiver_id": "T4A6C58SP7PP2", "txn_type": "cart", "mc_gross_1": "0.50", "mc_currency": "USD", "residence_country": "US", "test_ipn": "1", "payment_gross": "0.50", "ipn_track_id": "d61ac3d69a842", }, "method": "paypal_ipn", "status": "SUCCESS", "id": "6TS1068787252245S", "_cls": "chalicelib.models.PaymentTrailItem", }, ) self.assertTrue(len(response["email_trail"]) > 0) self.assertEqual(response["paid"], True) self.assertEqual(response["amount_paid"], "0.5")
def test_ipn_refund(self): responses.add( responses.POST, "https://www.sandbox.paypal.com/cgi-bin/webscr", body="VERIFIED", status=200, ) responseId = str(ObjectId()) response = Response( id=ObjectId(responseId), form=self.formId, date_modified=datetime.datetime.now(), date_created=datetime.datetime.now(), value={"a": "b", "email": "*****@*****.**"}, paymentInfo={ "total": 0.5, "currency": "USD", "items": [ {"name": "a", "description": "b", "amount": 0.25, "quantity": 1}, {"name": "a2", "description": "b2", "amount": 0.25, "quantity": 1}, ], }, payment_status_detail=[ PaymentStatusDetailItem( amount="1080.00", method="paypal_ipn", currency="USD", id="id1", date=datetime.datetime.now(), ) ], paid=True, amount_paid="1080.0", ).save() ipn_value = f"mc_gross=-1080.00&protection_eligibility=Eligible&item_number1=Double Room&payer_id=A4CSL993V3BDG&address_street=1 Main St&payment_date=07:43:04 Jun 23, 2019 PDT&payment_status=Refunded&charset=windows-1252&address_zip=95131&mc_shipping=0.00&mc_handling=0.00&first_name=test&mc_fee=-31.32&address_country_code=US&address_name=test buyer¬ify_version=3.9&reason_code=refund&custom={responseId}&[email protected]&address_country=United States&mc_handling1=0.00&address_city=San Jose&verify_sign=Ajpb2sm-lsDSWA5XwZfLh0PpsG6IAYl-yqrJx2GLHimSQ3aPkkfr3i2Y&[email protected]&mc_shipping1=0.00&tax1=0.00&parent_txn_id=23X19291EC9014330&txn_id=69B89632XK721821J&payment_type=instant&last_name=buyer&address_state=CA&item_name1=Double Room ($1200/person)&[email protected]&payment_fee=-31.32&shipping_discount=0.00&quantity1=1&receiver_id=T4A6C58SP7PP2&insurance_amount=0.00&discount=120.00&mc_gross_1=1200.00&mc_currency=USD&residence_country=US&test_ipn=1&shipping_method=Default&transaction_subject=&payment_gross=-1080.00&ipn_track_id=539cae4d23348" response = self.send_ipn(responseId, ipn_value) response = self.view_response(responseId) self.assertTrue("payment_status_detail" in response) self.assertEqual(len(response["payment_trail"]), 1) detail_history_one = response["payment_trail"][0] detail_history_one.pop("date") # TODO: why do these two not exist? detail_history_one.pop("date_created") detail_history_one.pop("date_modified") self.assertEqual( detail_history_one, { "value": { "mc_gross": "-1080.00", "protection_eligibility": "Eligible", "item_number1": "Double Room", "payer_id": "A4CSL993V3BDG", "address_street": "1 Main St", "payment_date": "07:43:04 Jun 23, 2019 PDT", "payment_status": "Refunded", "charset": "windows-1252", "address_zip": "95131", "mc_shipping": "0.00", "mc_handling": "0.00", "first_name": "test", "mc_fee": "-31.32", "address_country_code": "US", "address_name": "test buyer", "notify_version": "3.9", "reason_code": "refund", "custom": responseId, "business": "*****@*****.**", "address_country": "United States", "mc_handling1": "0.00", "address_city": "San Jose", "verify_sign": "Ajpb2sm-lsDSWA5XwZfLh0PpsG6IAYl-yqrJx2GLHimSQ3aPkkfr3i2Y", "payer_email": "*****@*****.**", "mc_shipping1": "0.00", "tax1": "0.00", "parent_txn_id": "23X19291EC9014330", "txn_id": "69B89632XK721821J", "payment_type": "instant", "last_name": "buyer", "address_state": "CA", "item_name1": "Double Room ($1200/person)", "receiver_email": "*****@*****.**", "payment_fee": "-31.32", "shipping_discount": "0.00", "quantity1": "1", "receiver_id": "T4A6C58SP7PP2", "insurance_amount": "0.00", "discount": "120.00", "mc_gross_1": "1200.00", "mc_currency": "USD", "residence_country": "US", "test_ipn": "1", "shipping_method": "Default", "payment_gross": "-1080.00", "ipn_track_id": "539cae4d23348", }, "method": "paypal_ipn", "status": "SUCCESS", "id": "69B89632XK721821J", "_cls": "chalicelib.models.PaymentTrailItem", }, ) self.assertTrue("email_trail" in response) self.assertEqual(len(response["email_trail"]), 1) self.assertEqual(response["paid"], False) self.assertEqual(response["amount_paid"], "0.0")
res = Response( date_created=dateutil.parser.parse(response["date_created"]), date_modified=dateutil.parser.parse(response["date_last_modified"]), form=ObjectId(formIdNew), paymentInfo=response["paymentInfo"], value=response["value"], paid=response["PAID"], payment_trail=[ PaymentTrailItem( date=dateutil.parser.parse(i["date"]), value=i["value"], status=i["status"], id=i["value"]["txn_id"], method="paypal_ipn", ) if "txn_id" in i["value"] else PaymentTrailItem( date=dateutil.parser.parse(i["date"]), value=i["value"], status=i["status"], id=i["value"]["order_id"], method="ccavenue", ) # todo: do we need to handle manual payments from v1? for i in response.get("IPN_HISTORY", []) ] or [], payment_status_detail=[ PaymentStatusDetailItem( date=dateutil.parser.parse(i["date"]), amount=i["amount"], currency=i["currency"], method="paypal_ipn" if i["method"] == "paypal" else i["method"], ) for i in PAYMENT_HISTORY ] or [], )
def setUp(self): super(FormResponses, self).setUp() self.formId = self.create_form() form = Form.objects.get({"_id": ObjectId(self.formId)}) to_create = [Response(form=form, paid=True) for i in range(0, 50)] Response.objects.bulk_create(to_create)
def form_response_new(formId): """ Payload: { "data": formData, "modifyLink": "...", "responseId"?: "asdsadasd" } If responseId is defined, it is an update. Otherwise, it is an existing submission. """ from ..main import app email_sent = False responseId = app.current_request.json_body.get("responseId", None) if not responseId: responseId = ObjectId() newResponse = True else: responseId = ObjectId(responseId) newResponse = False form = Form.objects.get({"_id": ObjectId(formId)}) response_data = app.current_request.json_body["data"] response_data = process_response_data_images(response_data) postprocess = form.formOptions.postprocess if postprocess and "patches" in postprocess and type( postprocess["patches"]) is list: response_data = patch_predicate(response_data, postprocess["patches"]) counter_value = None counter = form.formOptions.counter if newResponse and counter and "enabled" in counter and counter[ "enabled"] == True: counter_value = get_counter(formId) modify_link = app.current_request.json_body.get('modifyLink', '') paymentInfo = form.formOptions.paymentInfo confirmationEmailInfo = form.formOptions.confirmationEmailInfo paymentMethods = fill_paymentMethods_with_data( form.formOptions.paymentMethods, response_data) def calc_item_total_to_paymentInfo(paymentInfoItem, paymentInfo): paymentInfoItem['amount'] = calculate_price( paymentInfoItem.get('amount', '0'), response_data) paymentInfoItem['quantity'] = calculate_price( paymentInfoItem.get('quantity', '0'), response_data) paymentInfo[ 'total'] += paymentInfoItem['amount'] * paymentInfoItem['quantity'] if "couponCode" in paymentInfoItem and paymentInfoItem[ "amount"] * paymentInfoItem["quantity"] != 0: slots_maximum = calculate_price( paymentInfoItem.get("couponCodeMaximum", "-1"), response_data) if slots_maximum != -1: slots_requested = calculate_price( paymentInfoItem.get("couponCodeCount", "1"), response_data) slots_used = form.couponCodes_used.get( paymentInfoItem["couponCode"], 0) slots_available = slots_maximum - slots_used slots_remaining = slots_available - slots_requested if slots_remaining < 0: message = "Coupon code maximum reached.\nSubmitting this form will cause you to exceed the coupon code maximum.\nNumber of spots remaining: {}".format( int(slots_available)) return False, { "res": { "success": False, "message": message, "fields_to_clear": ["couponCode"] } } form.couponCodes_used[paymentInfoItem[ "couponCode"]] = slots_used + slots_requested Form.objects.raw({ "_id": form.id }).update({ "$set": { f"couponCodes_used.{paymentInfoItem['couponCode']}": slots_used + slots_requested } }) return True, {} paymentInfoItemsWithTotal = [] paymentInfoItemsInstallment = [] paymentInfo['total'] = 0 for paymentInfoItem in paymentInfo.setdefault('items', []): paymentInfoItem.setdefault("name", "Payment Item") paymentInfoItem.setdefault("description", "Payment Item") paymentInfoItem.setdefault("quantity", "1") if paymentInfoItem.get("installment", False) == True: # Don't count "installment" payments towards the total. paymentInfoItemsInstallment.append(paymentInfoItem) continue if "$total" in paymentInfoItem.get( "amount", "0") or "$total" in paymentInfoItem.get( "quantity", "0"): # Take care of this at the end. paymentInfoItemsWithTotal.append(paymentInfoItem) continue success, error = calc_item_total_to_paymentInfo( paymentInfoItem, paymentInfo) if success is False: return error # Now take care of items for round off, etc. -- which need the total value to work. response_data["total"] = float(paymentInfo["total"]) for paymentInfoItem in paymentInfoItemsWithTotal: success, error = calc_item_total_to_paymentInfo( paymentInfoItem, paymentInfo) if success is False: return error # Take care of installment payments now. response_data["total"] = float(paymentInfo["total"]) for paymentInfoItem in paymentInfoItemsInstallment: paymentInfoItem['amount'] = calculate_price( paymentInfoItem.get('amount', '0'), response_data) paymentInfoItem['quantity'] = calculate_price( paymentInfoItem.get('quantity', '0'), response_data) response_data.pop("total", None) paymentInfo['items'] = [ item for item in paymentInfo['items'] if item['quantity'] * item['amount'] != 0 ] userId = app.get_current_user_id() paid = paymentInfo["total"] == 0 if newResponse: response = Response(form=form, id=responseId, date_created=datetime.datetime.now(), modify_link=modify_link + "?responseId=" + str(responseId) if modify_link else "", counter=counter_value) if get(form, "formOptions.loginRequired", False ) is True and userId is not "cm:cognitoUserPool:anonymousUser": user = get_user_or_create_one(userId) response.user = userId # Only one response per user. try: Response.objects.get({ "form": ObjectId(formId), "user": userId }) raise Exception( f"Response with userId {userId} already exists!") except DoesNotExist: pass else: response = Response.objects.get({"_id": responseId}) response.update_trail.append( UpdateTrailItem(old=response.value, new=response_data, date=datetime.datetime.now(), update_type="update")) if (response.paid == True and paymentInfo["total"] <= response.paymentInfo["total"]): paid = True if form.id != response.form.id: raise UnauthorizedError( f"Response {response.id} does not belong to form {form.id}; it belongs to form {response.form.id}." ) if response.user and response.user.id != userId: app.check_permissions(form, 'Responses_Edit') # raise UnauthorizedError(f"User {userId} does not own response {response.id} (owner is {response.user.id})") if newResponse or (not newResponse and paid): response.value = response_data response.date_modified = datetime.datetime.now() response.paymentInfo = paymentInfo response.paid = paid if not newResponse: response.update_trail.append( UpdateTrailItem(date=datetime.datetime.now(), update_type="apply_update")) if paid and confirmationEmailInfo: # If total amount is zero (user uses coupon code to get for free) send_confirmation_email(response, confirmationEmailInfo) email_sent = True # todo: fix this, should auto_email come even if not paid? if "auto_email" in paymentMethods and get( paymentMethods, "auto_email.enabled", True) == True and type( get(paymentMethods, "autoEmail.confirmationEmailInfo") is dict): send_confirmation_email( response, get(paymentMethods, "auto_email.confirmationEmailInfo")) email_sent = True response.save() if "description" in paymentInfo and type( paymentInfo["description"]) is str: paymentInfo["description"] = fill_string_from_template( response, paymentInfo["description"]) if "ccavenue" in paymentMethods and response.paid == False: paymentMethods["ccavenue"] = update_ccavenue_hash( formId, paymentMethods["ccavenue"], response) return { "res": { "value": response_data, "paid": paid, "success": True, "action": "insert", "email_sent": email_sent, "responseId": str(responseId), "paymentInfo": paymentInfo, "paymentMethods": paymentMethods } } elif not newResponse: # Update. response.date_modified = datetime.datetime.now() # Not using pending_update for now. # response.pending_update = { # "value": response_data, # "paymentInfo": paymentInfo, # } response.value = response_data response.paymentInfo = paymentInfo response.paid = paid response.save() if "description" in paymentInfo and type( paymentInfo["description"]) is str: paymentInfo["description"] = fill_string_from_template( response, paymentInfo["description"]) if "ccavenue" in paymentMethods and response.paid == False: paymentMethods["ccavenue"] = update_ccavenue_hash( formId, paymentMethods["ccavenue"], response) return { "res": { "value": response_data, "paid": paid, "success": True, "action": "update", "email_sent": email_sent, "responseId": str(responseId), "paymentInfo": paymentInfo, "paymentMethods": paymentMethods, "amt_received": { "currency": paymentInfo["currency"], "total": float(response.amount_paid or 0) } } }
def setUp(self): super(TestEmail, self).setUp() self.formId = self.create_form() self.response = Response(**RESPONSE)