(20241216) Payments requesting started, callback noting started.
This commit is contained in:
@@ -61,7 +61,7 @@ from bson import ObjectId
|
||||
from pymongo import InsertOne, UpdateOne, ReplaceOne
|
||||
|
||||
# To work with LLMs:
|
||||
from controllers.core.ai.llm import LLMController
|
||||
from controllers.core.ai.llm import CoreLLMController
|
||||
from models.core.ai.llm import LLMInput, LLMOutput
|
||||
|
||||
# To work with datatypes:
|
||||
@@ -191,7 +191,7 @@ class MailController:
|
||||
self,
|
||||
mongo_conn: AsyncMongo,
|
||||
user_info: CoreUserInfoModel,
|
||||
llm: LLMController,
|
||||
llm: CoreLLMController,
|
||||
message: CoreMessageModel
|
||||
) -> LLMOutput:
|
||||
|
||||
@@ -319,7 +319,7 @@ class MailController:
|
||||
mail_client: AsyncGMailClient,
|
||||
google_tokens: GoogleAuthTokens,
|
||||
message_id: str,
|
||||
llm: LLMController = None,
|
||||
llm: CoreLLMController = None,
|
||||
force_sync: bool = False
|
||||
) -> MailSyncOneResult:
|
||||
|
||||
@@ -411,7 +411,7 @@ class MailController:
|
||||
user_info: CoreUserInfoModel,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
mail_client: AsyncGMailClient,
|
||||
llm: LLMController = None,
|
||||
llm: CoreLLMController = None,
|
||||
force_sync: bool = False,
|
||||
start_date: datetime.datetime = None,
|
||||
end_date: datetime.datetime = None,
|
||||
@@ -524,7 +524,7 @@ class MailController:
|
||||
mongo_conn: AsyncMongo,
|
||||
user_info: CoreUserInfoModel,
|
||||
token_key: ObjectId | str,
|
||||
llm: LLMController = None,
|
||||
llm: CoreLLMController = None,
|
||||
force_sync: bool = False,
|
||||
start_date: datetime.datetime = None,
|
||||
end_date: datetime.datetime = None,
|
||||
|
||||
+127
-79
@@ -47,9 +47,10 @@ from utils_v2.database.async_mongo_v2 import AsyncMongo, AsyncMongoStorage
|
||||
# Data models:
|
||||
from models.core.user import CoreUserInfoModel
|
||||
from models.core.auth_token import CoreAuthTokenModel
|
||||
from models.core.payment import CorePaymentModel, PaymentEvent
|
||||
from models.core.payment import CorePaymentModel, PaymentEvent, CustomerDetails
|
||||
from models.api.finstitutions.payments.request import (
|
||||
PaymentRequestOneResult
|
||||
PGPaymentRequestData,
|
||||
PaymentRequestOneResult,
|
||||
)
|
||||
|
||||
# Payment Clients:
|
||||
@@ -176,83 +177,118 @@ class PaymentController:
|
||||
# ┛┗┗ ┗┫┗┻┗ ┛┗ ┣┛┗┻┗┫┛┗┗┗ ┛┗┗┛
|
||||
# ┗ ┛
|
||||
|
||||
# @staticmethod
|
||||
# async def __request_from_safaricom_m_pesa_express(
|
||||
# http_client: httpx.AsyncClient,
|
||||
# auth_token: CoreAuthTokenModel,
|
||||
# payment: Union[SafaricomMPesaExpressRequest],
|
||||
# callback_url: str
|
||||
# ) -> PaymentRequestOneResult:
|
||||
#
|
||||
# # Start by assuming failure:
|
||||
# request_result = PaymentRequestOneResult()
|
||||
#
|
||||
# # Create the client:
|
||||
# client = SafaricomMPesaExpress(
|
||||
# auth = MPesaExpressAuthorization(
|
||||
# consumerKey = auth_token.auth["consumerKey"],
|
||||
# consumerSecret = auth_token.auth["consumerSecret"],
|
||||
# businessShortCode = auth_token.auth["businessShortCode"],
|
||||
# appPasskey = auth_token.auth["appPasskey"]
|
||||
# ),
|
||||
# http_client = http_client
|
||||
# )
|
||||
#
|
||||
# # Make the payment request:
|
||||
# client_response = await client.request_payment(
|
||||
# amount = payment.amount,
|
||||
# party_a = payment.partyA,
|
||||
# type = payment.transactionType,
|
||||
# reference = payment.accountReference,
|
||||
# description = payment.transactionDescription,
|
||||
# callback_url = callback_url,
|
||||
# payer_no = payment.phoneNo,
|
||||
# party_b = payment.partyB
|
||||
# )
|
||||
#
|
||||
# # Construct the payment details:
|
||||
# payment_details = CorePaymentModel(
|
||||
# user = None,
|
||||
# lastEventTs = date_time.get_current_utc_date_time(as_string = False),
|
||||
# lastPaymentStatus = "initiated" if client_response.success else "initFailed",
|
||||
# tokenId = auth_token.authTokenId,
|
||||
# amount = payment.amount,
|
||||
# curencyCode = "KES",
|
||||
# # metadata = payment.
|
||||
# )
|
||||
#
|
||||
# # Done here:
|
||||
# request_result.success = client_response.success
|
||||
# request_result.message = client_response.message
|
||||
# request_result.message = client_response.message
|
||||
# return request_result
|
||||
#
|
||||
# async def request_payment(
|
||||
# self,
|
||||
# mongo_conn: AsyncMongo,
|
||||
# http_client: httpx.AsyncClient,
|
||||
# auth_token: CoreAuthTokenModel,
|
||||
# payment: Union[SafaricomMPesaExpressRequest],
|
||||
# callback_url: str
|
||||
# ) -> PaymentRequestOneResult:
|
||||
#
|
||||
# # Start by assuming failure:
|
||||
# request_result = PaymentRequestOneResult()
|
||||
#
|
||||
# # Now we route the message to the appropriate client:
|
||||
# match auth_token.client:
|
||||
# case "safaricomMPesaExpress":
|
||||
# request_result = await self.__request_from_safaricom_m_pesa_express(
|
||||
# http_client = http_client,
|
||||
# auth_token = auth_token,
|
||||
# payment = payment,
|
||||
# callback_url = callback_url
|
||||
# )
|
||||
# case _:
|
||||
# request_result.message = f"invalid client {auth_token.client}"
|
||||
#
|
||||
# # Done here:
|
||||
# return request_result
|
||||
@staticmethod
|
||||
async def __request_from_safaricom_m_pesa_express(
|
||||
mongo_conn: AsyncMongo,
|
||||
http_client: httpx.AsyncClient,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
payment_request: PGPaymentRequestData,
|
||||
payment_id: ObjectId,
|
||||
callback_url: str
|
||||
) -> PaymentRequestOneResult:
|
||||
|
||||
# Start by assuming failure:
|
||||
result = PaymentRequestOneResult()
|
||||
|
||||
# Create the client:
|
||||
client = SafaricomMPesaExpress(
|
||||
auth = MPesaExpressAuthorization(
|
||||
consumerKey = auth_token.auth["consumerKey"],
|
||||
consumerSecret = auth_token.auth["consumerSecret"],
|
||||
businessShortCode = auth_token.auth["businessShortCode"],
|
||||
appPasskey = auth_token.auth["appPasskey"]
|
||||
),
|
||||
http_client = http_client
|
||||
)
|
||||
|
||||
# Make the payment request:
|
||||
client_response = await client.request_payment(
|
||||
amount = payment_request.amount,
|
||||
party_a = payment_request.customerNo,
|
||||
type = "CustomerPayBillOnline",
|
||||
reference = payment_request.reference,
|
||||
description = payment_request.description,
|
||||
callback_url = callback_url,
|
||||
payer_no = payment_request.payerNo,
|
||||
party_b = auth_token.auth["businessShortCode"]
|
||||
)
|
||||
|
||||
# Add this event to the payment's document:
|
||||
event_note_success = await current_app.core_payment_controller.add_event(
|
||||
mongo_conn = mongo_conn,
|
||||
payment_id = payment_id,
|
||||
event = PaymentEvent(
|
||||
paymentStatus = "initiated" if client_response.success else "initFailed",
|
||||
initByPG = False,
|
||||
httpCode = client_response.httpCode,
|
||||
headers = await client_response.get_headers(),
|
||||
payload = await client_response.get_json()
|
||||
)
|
||||
)
|
||||
|
||||
# Done here:
|
||||
result.success = client_response.success and event_note_success
|
||||
result.message = "; ".join([
|
||||
"payment request successfully" if client_response.success else "payment request failed",
|
||||
"event noted successfully" if event_note_success else "payment event noting failed",
|
||||
])
|
||||
return result
|
||||
|
||||
async def request_payment(
|
||||
self,
|
||||
mongo_conn: AsyncMongo,
|
||||
http_client: httpx.AsyncClient,
|
||||
auth_token: CoreAuthTokenModel,
|
||||
user_info: CoreUserInfoModel,
|
||||
payment_request: PGPaymentRequestData,
|
||||
) -> PaymentRequestOneResult:
|
||||
|
||||
# Start by assuming failure:
|
||||
request_result = PaymentRequestOneResult()
|
||||
|
||||
# Create a basic database entry to note down the intended payment:
|
||||
payment_id = await current_app.core_payment_controller.init(
|
||||
mongo_conn = mongo_conn,
|
||||
payment = CorePaymentModel(
|
||||
user = user_info,
|
||||
customer = CustomerDetails(
|
||||
name = payment_request.customerName,
|
||||
contactNo = payment_request.customerNo,
|
||||
payerNo = payment_request.payerNo,
|
||||
email = payment_request.email
|
||||
),
|
||||
lastPaymentStatus = "queued",
|
||||
tokenId = auth_token.authTokenId,
|
||||
amount = payment_request.amount,
|
||||
currencyCode = payment_request.currencyCode,
|
||||
metadata = payment_request.metadata,
|
||||
tags = ["payment", "safaricom", "mPesaExpress", "kenya"],
|
||||
client = auth_token.client,
|
||||
clientPaymentReferenceId = None,
|
||||
events = []
|
||||
)
|
||||
)
|
||||
if payment_id is None:
|
||||
request_result.message = "failed to queue the payment"
|
||||
return request_result
|
||||
else: request_result.message = "payment has been queued for processing"
|
||||
|
||||
# Now we route the request to the appropriate client:
|
||||
match auth_token.client:
|
||||
case "safaricomMPesaExpress":
|
||||
request_result = await self.__request_from_safaricom_m_pesa_express(
|
||||
http_client = http_client,
|
||||
mongo_conn = mongo_conn,
|
||||
auth_token = auth_token,
|
||||
payment_request = payment_request,
|
||||
callback_url = f"https://api.thecaoffice.com/finstitutions/payments/callback/{payment_id}",
|
||||
payment_id = payment_id
|
||||
)
|
||||
case _:
|
||||
request_result = None
|
||||
|
||||
# Done here:
|
||||
return request_result
|
||||
|
||||
# ┓ • ┓ ┏┓ ┏┓
|
||||
# ┃ ┓┏╋ ┏┓┏┓┏┫ ┃┓┏┓╋ ┃┃┏┓┓┏┏┳┓┏┓┏┓╋┏
|
||||
@@ -299,6 +335,18 @@ class PaymentController:
|
||||
payment_id = payment_id
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def get_payment_internal(
|
||||
mongo_conn: AsyncMongo,
|
||||
payment_id: ObjectId | str
|
||||
) -> CorePaymentModel | None:
|
||||
|
||||
# Simply call the core model:
|
||||
return await current_app.core_payment_controller.get_payment_internal(
|
||||
mongo_conn = mongo_conn,
|
||||
payment_id = payment_id
|
||||
)
|
||||
|
||||
# ┳┳ ┓
|
||||
# ┃┃┏┓┏┫┏┓╋┏┓
|
||||
# ┗┛┣┛┗┻┗┻┗┗
|
||||
|
||||
@@ -85,7 +85,7 @@ from langchain_openai import ChatOpenAI
|
||||
# *****************************************************************************************************************
|
||||
|
||||
|
||||
class LLMController(BaseModel):
|
||||
class CoreLLMController(BaseModel):
|
||||
|
||||
AI_USAGE_COLLECTION = "_aiUsage"
|
||||
|
||||
|
||||
@@ -134,10 +134,14 @@ class CorePaymentController(BaseModel):
|
||||
:return: The object id of the inserted document.
|
||||
"""
|
||||
|
||||
# Receive te JSON:
|
||||
payment_json = payment.model_dump()
|
||||
payment_json.pop("_id")
|
||||
|
||||
# Simply insert the document:
|
||||
return await mongo_conn.insert_one(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
document = payment,
|
||||
document = payment_json,
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
@@ -253,6 +257,34 @@ class CorePaymentController(BaseModel):
|
||||
# we return it as our data model:
|
||||
return CorePaymentModel(**record)
|
||||
|
||||
async def get_payment_internal(
|
||||
self,
|
||||
mongo_conn: AsyncMongo,
|
||||
payment_id: ObjectId | str,
|
||||
) -> CorePaymentModel | None:
|
||||
|
||||
"""
|
||||
NOTE: DO NOT USE THIS IN USER-FACING APIS. USE THIS INTERNALLY TO FETCH RECORDS.
|
||||
Gets one payment detail if you know its payment id.
|
||||
:param mongo_conn: The instance of the database connector to use for the operation.
|
||||
:param payment_id: The id of the payment detail that needs to be read.
|
||||
:return: The contents of that one payment detail in a structured format.
|
||||
"""
|
||||
|
||||
# We fetch the whole payload of that one message:
|
||||
record = await mongo_conn.find_one(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
filter = {"_id": ObjectId(payment_id)},
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
# If no such message was found:
|
||||
if record is None: return None
|
||||
|
||||
# If a record was found,
|
||||
# we return it as our data model:
|
||||
return CorePaymentModel(**record)
|
||||
|
||||
# ┏┓┳┓┳┳┳┓ ┳┳ ┓
|
||||
# ┃ ┣┫┃┃┃┃ ━━ ┃┃┏┓┏┫┏┓╋┏┓
|
||||
# ┗┛┛┗┗┛┻┛ ┗┛┣┛┗┻┗┻┗┗
|
||||
@@ -265,7 +297,8 @@ class CorePaymentController(BaseModel):
|
||||
self,
|
||||
mongo_conn: AsyncMongo,
|
||||
payment_id: ObjectId | str,
|
||||
event: PaymentEvent
|
||||
event: PaymentEvent,
|
||||
client_reference_id: str = None
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
@@ -273,14 +306,28 @@ class CorePaymentController(BaseModel):
|
||||
:param mongo_conn: The instance of the database connector to use for the operation.
|
||||
:param payment_id: The id of the payment detail that needs to be read.
|
||||
:param event: The event that occurred. This will typically be generated by the third-party client.
|
||||
:param client_reference_id: The way the client identifies this payment. You need to pass this only on the first
|
||||
event. Typically, when you initiate the payment request.
|
||||
:return: True if successfully noted, else False.
|
||||
"""
|
||||
|
||||
# Prepare the update document:
|
||||
update_json = {
|
||||
"$push": {
|
||||
"events": event.model_dump()
|
||||
},
|
||||
"$set": {
|
||||
"lastEventTs": date_time.get_current_ist_date_time(as_string = False),
|
||||
"lastPaymentStatus": event.paymentStatus
|
||||
}
|
||||
}
|
||||
if client_reference_id: update_json["$set"]["clientPaymentReferenceId"] = client_reference_id
|
||||
|
||||
# Try to update the existing record:
|
||||
return await mongo_conn.update_one(
|
||||
collection = self.PAYMENTS_COLLECTION,
|
||||
filter = {"_id": ObjectId(payment_id)},
|
||||
update = {"$push": {"events": event}},
|
||||
update = update_json,
|
||||
upsert = False,
|
||||
raise_exception = True
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user