""" AUTHOR: Khushal P Soonderji DATE: Saturday, 7th Dec., 2024. OBJECTIVE: To define how payment transactions will be stored in the database. REFERENCES: N/A DOWNLOADS: N/A """ # ***************************************************************************************************************** # ***** **** # *** IMPORT *** # ***** **** # ***************************************************************************************************************** # To make sibling directories accessible for imports: import sys sys.path.append(".") sys.path.append("..") # For making data behaviour_models: from pydantic import BaseModel, Field, field_validator, PastDatetime, AwareDatetime from typing import Optional, Literal, Union, List, Any # My utils: from utils_v2.string import regex from utils_v2.date_time import date_time # To work with MongoDB: from bson.objectid import ObjectId # To work with date and time: import datetime # To work with currencies: import pycountry # ***************************************************************************************************************** # ***** **** # *** MACROS / ONE-TIME INIT *** # ***** **** # ***************************************************************************************************************** # --- Nothing Yet # ***************************************************************************************************************** # ***** **** # *** VARIABLES *** # ***** **** # ***************************************************************************************************************** # --- Nothing Yet # ***************************************************************************************************************** # ***** **** # *** FUNCTIONS *** # ***** **** # ***************************************************************************************************************** class PaymentEvent(BaseModel): eventTs: AwareDatetime = Field( description = "to know the date and time (utc) of this update", frozen = True ) initByPG: bool = Field( description = "to figure out whether the payment gateway initiated this event or we did", frozen = True ) httpCode: int | None = Field( description = "the http code generated by the event", frozen = True, examples = [200, 400, 401] ) payload: dict = Field( description = "the json payload or set of query params received from an event from the payment gateway", frozen = True ) # ┏┓ ┏• # ┃ ┏┓┏┓╋┓┏┓ # ┗┛┗┛┛┗┛┗┗┫ # ┛ class Config: extra = "allow" arbitrary_types_allowed = True # ┓┏ ┓• ┓ • # ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓ # ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗ @field_validator("eventTs", mode = "before") def parse_date_time(cls, value): return date_time.parse_date_time(input_value = value, timezone = date_time.TIMEZONE_UTC) # --------------------------------------------------------------------------------------------------------------------- class CorePaymentModel(BaseModel): paymentId: ObjectId = Field( description = "the id of the document in mongodb that holds this information", frozen = True, default = None, alias = "_id" ) paymentStatus: Literal[ "initFailed", # ... When we tried to initiate the request, but the payment gateway (PG) rejected it. "initiated", # .... When we made a successful payment request, or the customer initiated one from the PG. "failed", # ....... When the customer tried paying, but it failed (e.g.: because of an incorrect pin). "rejected", # ..... When the customer explicitly rejected the payment. "authorized", # ... When the customer made the payment (but it hasn't been settled in your account yet). "settled", # ...... When the PG sends the money to your account. "refunded", # ..... When the money was refunded to the client. ] = Field( description = "the status of the payment request to see what stage of the process we are in", frozen = False ) lastEventTs: AwareDatetime = Field( description = "the time (utc) at which the latest payment event occurred", frozen = True ) tokenId: ObjectId = Field( description = "the id of the auth token that is associated with this payment", frozen = True ) amount: float | int = Field( description = "the amount of money being requested" ) currencyCode: str = Field( description = "the three-letter ISO 4217 code to identify the currency", frozen = True, examples = ["INR", "USD", "KES"] ) metadata: dict | None = Field( description = "any arbitrary amount of data to identify the user and payment details", frozen = True ) tags: List[Any] = Field( description = "a list of keywords to apply to this file/dir to filter it later", frozen = False, default = [], examples = ["renewal", "subscription"] ) client: Literal["razorpay", "safaricomMPesaExpress"] = Field( description = "the third-part client that was used", frozen = True ) clientPaymentReferenceId: int | str = Field( description = "the reference id given by the third-party client", frozen = False, default = None ) events: List[PaymentEvent] = Field( description = "an array of all the events that happened in the process of this payment", frozen = False ) # ┏┓ ┏• # ┃ ┏┓┏┓╋┓┏┓ # ┗┛┗┛┛┗┛┗┗┫ # ┛ class Config: extra = "allow" arbitrary_types_allowed = True def model_dump(self, *args, **kwargs): return super().model_dump(*args, by_alias = True, **kwargs) # ┓┏ ┓• ┓ • # ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓ # ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗ @field_validator("lastEventTs", mode = "before") def parse_date_time(cls, value): return date_time.parse_date_time(input_value = value, timezone = date_time.TIMEZONE_UTC) @field_validator("tokenId", mode = "before") def parse_oid(cls, value): try: if isinstance(value, str): value = ObjectId(value) except: pass return value @field_validator("currencyCode", mode = "before") def validate_currency(cls, value): currency = pycountry.currencies.get(alpha_3 = value) if currency is None: raise ValueError("invalid currency code, please use iso 4217 standard") return value @field_validator("tags", mode = "before") def validate_tags(cls, value): if value is None: value = [] return value # ***************************************************************************************************************** # ***** **** # *** MAIN PROGRAM *** # ***** **** # ***************************************************************************************************************** if __name__ == "__main__": from utils_v2.string import json now = date_time.get_current_utc_date_time(as_string = False) payment = CorePaymentModel( paymentStatus = "authorized", tokenId = "67519cf3a7804fcbc6f12452", amount = 1.00, currencyCode = "INR", metadata = { "userId": 1, "name": "Bhopli" }, client = "razorpay", clientPaymentReferenceId = "txn_123_abc", lastEventTs = now, events = [ PaymentEvent( eventTs = now - datetime.timedelta(minutes = 1, seconds = 12), initByPG = True, httpCode = None, payload = { "status": "captured", "from": "Barfi", } ), PaymentEvent( eventTs = now, initByPG = True, httpCode = None, payload = { "status": "authorized", "from": "Barfi", "amount": -100.00, "description": "meow" } ) ] ) print("PAYMENT TXN. MODEL:", json.to_string(payment.model_dump(), default = str))