Skip to content

Instantly share code, notes, and snippets.

@adejorosam
Created November 29, 2024 09:21
Show Gist options
  • Save adejorosam/7ac44dd286bc91323f97e81d97c4347e to your computer and use it in GitHub Desktop.
Save adejorosam/7ac44dd286bc91323f97e81d97c4347e to your computer and use it in GitHub Desktop.
withdrawal flow
<?php
namespace CardinalstoneRestServer\models;
use CardinalstoneRestServer\models\Model;
use CardinalstoneRestServer\models\MutualFundModel as mutualFundModel;
use CardinalstoneRestServer\models\ForeignEquityModel;
use CardinalstoneRestServer\services\JWTToken;
use CardinalstoneRestServer\services\mail\Mailer;
use CardinalstoneRestServer\middleware\Uploader;
use Psr\Container\ContainerInterface;
use Carbon\Carbon;
use Slim\Http\UploadedFile;
// use CardinalstoneRestServer\services\mail\Mailer;
/**
* Description of CustomerModel
*
* @author ukah ewomazino
*/
class CustomerModel extends Model
{
private $newAccountFields = [
"Title",
"lastName",
"firstName",
"otherNames",
"dateOfBirth",
"gender",
"address",
"city",
"country",
"state",
"LGA",
"emailAddress",
"phoneNumber",
"homePhone",
"occupation",
"companyName",
"employmentType",
"politicallyExposed",
"bankName",
"bankAcctNumber",
"BVNNumber",
"identityNumber",
"identityType",
"expiryDate",
"nextOfKin",
"relationship",
"contactAddress",
"nextOfKinPhone",
"nextOfKinEmail",
"businessInvolvement",
"involvementType",
];
private $businessInvolvement = [
ASSETMGMT_DB_NAME => "Asset",
STOCKBROKING_DB_NAME => "Brokerage",
CAM_DB_NAME => "CAM",
];
private $filesType = [
"passport" => "Passport",
"signature" => "Signature",
"proofOfAddress" => "Proof of address",
"identityDocument" => "Identity document",
"certificateOfIncoporation" => "Certificate of Incorporation",
"CACDocuments" => "CAC Documents",
"memorandomAndArticleOfIncorporation" => " Memorandum and article of Incoporation",
];
/**
* Default Constructor
* @author ewomazino.ukah <[email protected]>
*/
public function __construct(ContainerInterface $container)
{
parent::__construct($container);
}
public function paystackKeyTable()
{
return $this->container
->capsule
->table('paystack_key');
}
public function paystackWebhookLogTable()
{
return $this->container
->capsule
->table('paystack_webhook_log');
}
/*public function CSFClientsTable()
{
return $this->container
->capsule
->table('csf_customers');
}
public function getCSFClients()
{
return $this->CSFClientsTable()
->get()
->pluck('CustID')
->toArray();
}
*/
public function paystackPaymentTable()
{
return $this->container
->capsule
->table('paystack_payment_transactions');
}
public function paystackAuditTable()
{
return $this->container
->capsule
->table('paystack_audit');
}
public function redemptionTable() //properly renamed from table to redemptionTable by Tayo
{
return $this->container
->capsule
->table('mutualfunds_redemption');
}
public function redemptionPayoutTable()
{
return $this->container
->capsule
->table('zenith_redemption_payout');
}
public function zenithDVFTable()
{
return $this->container
->capsule
->table('zenith_dvf');
}
public function zenithDVFSettlementTable()
{
return $this->container
->capsule
->table('zenith_dvf_instruction');
}
public function zenithBondsTable()
{
return $this->container
->capsule
->table('zenith_bonds');
}
public function zenithBondsSettlementTable()
{
return $this->container
->capsule
->table('zenith_bonds_instruction');
}
public function zenithTbillsTable()
{
return $this->container
->capsule
->table('zenith_tbills');
}
public function zenithTbillsSettlementTable()
{
return $this->container
->capsule
->table('zenith_tbills_instruction');
}
public function zenithEquityTable()
{
return $this->container
->capsule
->table('zenith_equity');
}
public function zenithEquitySettlementTable()
{
return $this->container
->capsule
->table('zenith_equity_instruction');
}
public function redemptionAuthorizerTable()
{
return $this->container
->capsule
->table('redemption_authorizer');
}
public function adUserTable()
{
return $this->container
->capsule
->table('ad_user');
}
public function globalBudgetTable()
{
return $this->container
->capsule
->table('global_budget');
}
public function monthlyBudgetTable()
{
return $this->container
->capsule
->table('monthly_budget');
}
public function IAMonthlyBudgetTable()
{
return $this->container
->capsule
->table('ia_monthly_budget');
}
public function marginStock()
{
return $this->container
->capsule
->table('margin_stock');
}
public function transferPinTable()
{
return $this->container
->capsule
->table('transferPin');
}
public function KYCTable()
{
return $this->container
->capsule
->table('kyc_table');
}
public function assetClass_SectorTable()
{
return $this->container
->capsule
->table('assetClass_Sector');
}
public function countryTable()
{
return $this->container
->capsule
->table('country');
}
public function forgotPasswordTable()
{
return $this->container
->capsule
->table('forgot_password');
}
public function stateTable()
{
return $this->container
->capsule
->table('state');
}
public function voucherTable()
{
return $this->container
->capsule
->table('voucher');
}
public function cityTable()
{
return $this->container
->capsule
->table('city');
}
public function lgaTable()
{
return $this->container
->capsule
->table('lga');
}
public function walletTable()
{
return $this->container
->capsule
->table('wallet');
}
public function walletLimitTable()
{
return $this->container
->capsule
->table('wallet_limit_table');
}
public function CAMRateTable()
{
return $this->container
->capsule
->table('cam_rates');
}
public function YochaaRateTable()
{
return $this->container
->capsule
->table('yochaa_rates');
}
public function IAExceptionsTable()
{
return $this->container
->capsule
->table('ia_staff_exceptions');
}
public function getIAExceptions($iaOfficerName)
{
return $this->IAExceptionsTable()
->where('ia_officer_name', $iaOfficerName)
->get()
->pluck('staff_id')
->toArray();
}
public function transferTable()
{
return $this->container
->capsule
->table('transfer_recipient');
}
public function CAMProductTable()
{
return $this->container
->capsule
->table('cam_products');
}
public function cpTable()
{
return $this->container
->capsule
->table('cp');
}
public function notificationTable()
{
return $this->container
->capsule
->table('notifications');
}
public function updateNotification($payload)
{
// $equityFund = $this->equityFundTable()->where([["paymentRef","=", $payload['reference']]])->first();
$this->notificationTable()->where([["id","=", $payload['notificationId']]])
->update([
'status' => true,
]);
return ['code' => 200, 'message' => 'Notification table updated'];
}
public function tbillsTable()
{
return $this->container
->capsule
->table('tbills');
}
public function CAMDealTable()
{
return $this->container
->capsule
->table('cam_deals');
}
public function CAMDealBreakTable()
{
return $this->container
->capsule
->table('cam_deals_break');
}
public function stockRecommendationTable()
{
return $this->container
->capsule
->table('stock_recommendation');
}
public function infowareLogTable()
{
return $this->container
->capsule
->table('infoware_logs');
}
public function deviceDetailsTable()
{
return $this->container
->capsule
->table('deviceDetails');
}
public function emailVerificationsTable()
{
return $this->container
->capsule
->table('email_verification');
}
public function riskAssesmentProfileTable(){
return $this->container
->capsule
->table('investor_profile_details');
}
public function addRiskAssessment($payload)
{
$this->id = $this->riskAssesmentProfileTable()
->insertGetId([
'firstName' => $payload['firstName'],
'lastName' => $payload['lastName'],
'addressLine1' => $payload['addressLine1'],
'addressLine2' => $payload['addressLine2'],
'city' => $payload['city'],
'state' => $payload['state'],
'zipCode' => $payload['zipCode'],
'industry' => $payload['industry'],
'age' => $payload['age'],
'asset' => $payload['asset'],
'position' => $payload['position'],
'usage' => $payload['usage'],
'objective' => $payload['objective'],
'tolerance' => $payload['tolerance'],
'mutual-funds' => $payload['mutual-funds'],
'money-market' => $payload['money-market'],
'foreign-currency' => $payload['foreign-currency'],
'impact' => $payload['impact'],
'equities-securities' => $payload['equities-securities'],
'derivatives' => $payload['derivatives'],
'alternatives' => $payload['alternatives'],
'horizon' => $payload['horizon'],
'need' => $payload['need'],
'risk_category' => $payload['category'],
'score' => $payload['score'],
'asset_origin' => $payload['asset_origin'],
'fixed_income_allocation' => $payload['fixed_income_allocation'],
'fixed_income_value' => $payload['fixed_income_value'],
'real_estate_value' => $payload['real_estate_value'],
'real_estate_allocation' => $payload['real_estate_allocation'],
'growth_ranking' => $payload['growth_ranking'],
'limits_and_restrictions' => $payload['limits_and_restrictions'],
'liquidity_ranking' => $payload['liquidity_ranking'],
'income_ranking' => $payload['income_ranking'],
'capital_preservation_ranking' => $payload['capital_preservation_ranking'],
'equities_value' => $payload['equities_value'],
'equities_allocation' => $payload['equities_allocation'],
'cash_value' => $payload['cash_value'],
'cash_allocation' => $payload['cash_allocation']
]);
return;
}
public function fetchAllAssessments()
{
$assesments = $this->riskAssesmentProfileTable()
->get();
$assesments = json_decode(json_encode($assesments), true);
return ['code' => 200, 'message' => 'Assesments successfully fetched.', 'data' => $assesments ?? []];
}
public function verifyEmail($payload)
{
$otp = $this->emailVerificationsTable()
->where([
["emailAddress", "=", $payload["emailAddress"] ],
["otp", "=", $payload["otp"] ],
["username", "=", $payload["CustID"]]
])->first();
if($otp)
{
return (["code" => 200, "message" => "OTP successfully verified"]);
}else{
return (["code" => 400, "message" => "OTP not valid"]);
}
}
public function getOTPRecord($payload)
{
$otp = $this->emailVerificationsTable()
->where("username", "=", $payload["CustID"])->first();
if($otp)
{
return (["code" => 200, "data" => $otp]);
}
else{
return (["code" => 400, "data" => null]);
}
}
public function getOTPRecord_($payload)
{
$otp = $this->emailVerificationsTable()
->where("CustID", "=", $payload["CustID"])->first();
if($otp)
{
return (["code" => 200, "data" => $otp]);
}
else{
return (["code" => 400, "data" => null]);
}
}
public function updateRegistrationOTP($payload)
{
$otp = $this->emailVerificationsTable()
->where([["username", "=", $payload["CustID"]]])
->update([
"used" => 1,
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}
public function CSFinanceClientsTable()
{
return $this->container
->capsule
->table('csf_customers');
}
public function getCSFCustomers()
{
return $this->CSFinanceClientsTable()
->get()
->pluck('CustID')
->toArray();
}
public function withdrawFromWalletToEquity($payload)
{
$lockKey = "lock:equity:" . $payload['CustID'];
$lockTimeout = 60 * 5; // Lock timeout in seconds, adjust as needed
//check if limit is okay
try
{
$cache = container('cache')->fetch($lockKey);
if($cache === false)
{
acquireLock($lockKey, $lockTimeout);
}
else {
return ["code" => 423, "message" => "Please hold off for a bit before retrying. Thank you for your patience!"];
}
$dailyBalance = $this->dailyWalletSpent($payload["CustID"]);
//check kyc status
$kyc = $this->checkIfcustomerKYCIsComplete($payload['CustID'],MIDDLEWARE_DB_NAME)[0]["IsKYC"];
if(strtoupper($kyc) == "TRUE")
{
//check wallet balance
$balance = container('mutualFundModel')->getWalletBalance($payload);
if($balance['actualBalance'] < $payload['amount'] )
{
return [
"message" => "You have insufficent cash balance for this transaction",
"code" => 400,
"data" => ["Your current balance is: N" . number_format($balance['balance'], 2, '.', ',') ] ?? []
];
}
//post wallet transaction for debit
$payload['transactionType'] = "DEBIT";
$payload['transactionAmount'] = $payload['amount'];
$payload['cash_account_id'] = CSWALLET_DEBIT_ACCOUNT_MMF;
$payload['productType'] = "MMF";
$payload["client_id"] = $payload["CAMID"];
$payload["reference"] = "CWD". container('mutualFundModel')->generateWalletTransactionId();
$payload["narration"] = "Being debit from ". $payload["fullName"]."'s wallet to credit Money Market Fund"; //for wallet withdrawal to customer's bank
$post = container('PaystackGatewayModel')->createTransactionOnInfowareForEquityWalletWithdrawal($payload);
if($post["code"] == 200)
{
$payload['valueDate'] = $post["date_"] ;
$payload["transactionRef"] = $payload["reference"];
$payload["fundCode"] = CSWALLET_INVOLVEMENT;
//create wallet spent
$this->createDailyWalletSpent($payload);
//post credit to infoware
$payload['invType'] = 'MMF';
$payload['businessInvolvement'] = CAM_DB_NAME;
$payload['BIZID'] = $payload["CAMID"];
$payload['BranchCode'] = '000';
$payload['CRAccountMaster'] = 'MMF-8000';
$payload['CRAccountSub'] = $payload['BIZID'];
$payload['DRAccountSub'] = '10002';
$payload['DRAccountMaster'] = 'MMF-8000';
$payload['Amount'] = $payload['amount'];
$payload['Narration'] = "Being credit to MMF cash account from CS Wallet for {$payload['fullName']} with Business ID: {$payload['BIZID']} and Branch Code: {$payload['BranchCode']}";
$payload['EffectiveDate'] = date('Y-m-d');
$payload['CallerTransactionID'] = $payload['reference'];
$payload['involvementType'] = "MMF";
if($payload['type'] != "topup")
{
container('IWSRequest')->createInvolvementMMF($payload);
}
$fundAccount = container('IWSRequest')->fundAccountMMF($payload);
if($fundAccount->StatusID == 0)
{
$data_res = ["code"=>200, "tranxRef" => $payload["reference"], "message"=>"Payment posted successfully", "data"=> $fundAccount ?? []];
$payload["comment"] = "processed by client";
$payload["isPaid"] = 1;
$payload["isPaidDate"] = Carbon::now()->format('Y-m-d H:i:s');
}else{
//Notify RICA of transaction failure
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Partial Failed Wallet Transaction - Paystack: " .$payload["message"])
->usingView('failed_wallet_transaction_notification', $record)
->send();
// $data_res = ["code"=>200, "message"=>"Transfer To Bank in Progress", "data"=> "Transfer in progress"];
$data_res = ["code"=>200, "message"=>"Transfer to bank in progress", "data"=> []];
$payload["comment"] = "to be processed by FINCON";
}
}else{ //Notify RICA of transaction failure
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Failed Wallet Transaction - Posting issue on Infoware")
->usingView('failed_wallet_transaction_notification', $record)
->send();
// return ["code"=>200, "message"=>"Transfer To Bank in Progress", "data"=> []];
return ["code"=>400, "message"=>"Your withdrawal request failed. Please contact us", "data"=> []];
}
//Post debit to client's wallet in local table
$wallet = container('mutualFundModel')->debitWallet($payload);
if($wallet["code"] == 200)
{
//notify FINCON for bank to bank posting
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Successful Wallet Transaction")
->usingView('wallet_transaction_notification', $record)
->send();
return $data_res;
}else //Notify RICA of transaction failure
{
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"],
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->bcc(\getenv("IT-UNIT-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Partial Failed Wallet Transaction - Unable to update wallet report database")
->usingView('failed_wallet_transaction_notification', $record)
->send();
return ["code"=>200, "message"=>"Transfer To Bank in Progress", "data"=> []];
}
}else{
return ["code"=>400, "message"=>"Unable to Process Transfer Request Due to Incomplete KYC. Please Complete your KYC", "data"=> []];
}
}catch(\Exception $e){
return ["code"=>400, "message"=>"Unable to Process Transfer Request. Please contact support", "data"=> []];
}
}
public function getPinRecord($payload)
{
$pinRecord = $this->transferPinTable()
->where("CustID", "=", $payload["CustID"])->first();
if($pinRecord)
{
return (["code" => 200, "data" => $pinRecord]);
}
else{
return (["code" => 400, "data" => null]);
}
}
public function investmentNotificationTable()
{
return $this->container
->capsule
->table('investment_notification');
}
public function marginApplicationTable()
{
return $this->container
->capsule
->table('margin_application');
}
public function marginInterestRateTable()
{
return $this->container
->capsule
->table('margin_interest_rate');
}
public function savingsAccountTable()
{
return $this->container
->capsule
->table('savings_current_accounts');
}
public function marginTransactionTable()
{
return $this->container
->capsule
->table('margin_transaction');
}
public function marginCollateralTable()
{
return $this->container
->capsule
->table('margin_collateral');
}
public function marginLienTable()
{
return $this->container
->capsule
->table('margin_lien');
}
public function marginClientTable()
{
return $this->container
->capsule
->table('margin_client');
}
public function marginConversionRateTable()
{
return $this->container
->capsule
->table('margin_conversion_rate');
}
public function marginInterestTable()
{
return $this->container
->capsule
->table('margin_interest_log');
}
public function marginInterestAccruedTable()
{
return $this->container
->capsule
->table('margin_interest_accrued');
}
public function KYCImage()
{
return $this->container
->capsule
->table('kyc_image');
}
public function withdrawRequestTable()
{
return $this->container
->capsule
->table('withdraw_request');
}
public function paymentRequestTable()
{
return $this->container
->capsule
->table('payment_request');
}
public function withdrawRoleLimitTable()
{
return $this->container
->capsule
->table('withdraw_role_limit');
}
//modified by Tayo 8th of June 2021
private function activityTable()
{
return $this->container
->capsule
->table('activity_log');
}
//created by Tayo 17th of June 2021
private function iStateTable()
{
return $this->container
->capsule
->table('stateCode');
}
public function customerTable()
{
return $this->container
->capsule
->table('new_customers_account');
}
//create Feedback submission by Tayo
public function feedbackTable()
{
return $this->container
->capsule
->table('feedback');
}
public function withdrawalRequestOTPTable()
{
return $this->container
->capsule
->table('withdrawal_otp');
}
public function nubanTable()
{
return $this->container
->capsule
->table('nuban_account');
}
public function nubanProduct()
{
return $this->container
->capsule
->table('nuban_product');
}
public function cashAccountTable()
{
return $this->container
->capsule
->table('cashAccount');
}
public function bankCodeTable()
{
return $this->container
->capsule
->table('bankCode');
}
//modified by Tayo 13th of June 2021
//retrieve icode (for ixtrac), bankcode, and sortcode
public function bankCode($bankName){
return $this->bankCodeTable()
->where([["bankName", "=", $bankName]])
->orWhere([["bankName1", "=", $bankName]])
->orWhere([["bankName2", "=", $bankName]])
->orWhere([["bankCode", "=", $bankName]])
->first();
}
public function us_holidayTable()
{
return $this->container
->capsule
->table('us_holiday');
}
public function businessInvolvement()
{
return $this->container
->capsule
->table('business_involvement');
}
public function productInvolvement()
{
return $this->container
->capsule
->table('product_involvement');
}
public function getAllSavingsAccounts()
{
$accounts = $this->savingsAccountTable()
->get();
return $accounts;
}
public function activity_log($CustID, $fullName, $RegisterID, $StatusMessage,$system)
{
if ($StatusMessage == "Status Message is " || is_null($StatusMessage)){
$StatusMessage = "Status Message is NA";
}
$this->id = $this->activityTable()
->insertGetId([
'CustID' => $CustID,
'fullName' => str_replace(",","",$fullName),
'RegisterID' => $RegisterID,
'StatusMessage' => $StatusMessage,
'System' => $system
]);
return;
}
public function email_verification($payload)
{
$this->id = $this->emailVerificationsTable()
->insertGetId([
'emailAddress' => $payload['emailAddress'],
'CustID' => $payload['CustID'],
'username' => $payload['newUsername'],
'otp' => $payload['otp'],
'BIZID' => $payload['BIZID']
]);
return;
}
public function updateEmailVerificationTable($CustID)
{
$this->emailVerificationsTable()
->where([["CustID","=", $CustID]])
->update([
'isProfileCompleted' => true,
]);
return;
// return ['code' => 200, 'message' => 'Transfer pin updated'];
}
public function getUsernames($username)
{
$usernames = $this->emailVerificationsTable() //check if user has unused OTP
->where([
["username", "=", $username ]
])->get();
return $usernames;
}
public function createPin($CustID, $hashedPin)
{
$this->id = $this->transferPinTable()
->insertGetId([
'CustID' => $CustID,
'transferPin' => $hashedPin
]);
return;
}
public function deviceDetailsMobile($payload)
{
$this->id = $this->deviceDetailsTable()
->insertGetId([
'deviceName' => $payload['deviceName'],
'CustID' => $payload['CustID'],
'emailAddress' => $payload['email'],
'fullName' => $payload['fullName'],
'deviceIP' => $payload['deviceIP'],
'deviceToken' => $payload['deviceToken'],
'lastLocation' => $payload['lastLocation'],
'deviceModel' => $payload['deviceModel'],
'lastLogIn' => date('Y-m-d H:i:s'),
'createdAt' => date('Y-m-d H:i:s')// Add the current timestamp
]);
return;
}
public function infoware_log($payload)
{
$this->id = $this->infowareLogTable()
->insertGetId([
'business' => $payload['Business'],
'url' => $payload['URL'],
'status' => $payload['Status'],
'reason' => $payload['Reason'],
'response_time' => $payload['ResponseTime'],
'ip_address' => $payload['IPAddress'],
]);
return;
}
//create Feedback submission by Tayo 6th of June
public function submitFeedbackRequest($customerId,$email,$phone,$rating,$fullName,$feedback)
{
$responseData = "There was an error submitting feedback, kindly try again later.";
$this->id = $this->feedbackTable()
->insertGetId([
'CustID' => $customerId,
'emailAddress' => $email,
'phoneNumber' => $phone,
'rating' => $rating,
'fullName' => str_replace(",","",$fullName),
'feedback' => $feedback
]);
if($this->id > 0){
$responseData = "Feedback successfully submitted";
$status = "success";
$code = 200;
}else{
$responseData = "Feedback submission failed";
$status = "error";
$code = 400;
}
return [
"message" => $responseData,
"status" => $status,
"code" => $code
];
}
//end of feedback submission by Tayo
//created by Tayo 13th of June to compute SEC rolling average
public function rollingAvg($payload){
//$payload['rollDate'] = $payload['refDate'];
//$rollAvg = [];
$totalPort = $data = $res = [];
$mom = $momC = 0;
//Begin compute rolling Avegerage
for($i = 6 ; $i >= 0 ; $i--)
{
//Get previous months starting from earliest to current date
$dt = strtotime($payload['refDate']);
$payload['rollDate'] = date("Y-m-d", strtotime("-". $i ." month", $dt));
//fetch data for current month from infoware
$rollAvg = formatIWRes(container('IWSRequest')->rollingAvg($payload, $payload['rollDate']));
//$decoded_data = json_decode(json_encode($rollAvg));
//Number of records fetch
$count = count($rollAvg['data']);
if($count > 0)
{
// var_dump($count);
// var_dump($rollAvg['data']);
//sum Market value for records fetch
for ($j=0 ; $j <= $count ; $j++)
{
$totalPort[$i] = $totalPort[$i] + $rollAvg['data'][$j]['MarketValue']*1;
}
// var_dump($totalPort[$i]);
if ($i < 6)
{
$totalPortNext = $totalPort[$i+1] ?? 0;
// var_dump($totalPort[$i]);
// var_dump($totalPortNext);
$mom = (!is_null($totalPort[$i] - $totalPortNext) && !is_nan($totalPort[$i] - $totalPortNext)) ? ($totalPort[$i] - $totalPortNext) : 0;
$momC = (!is_null(($totalPort[$i]-$totalPortNext)/$totalPortNext) && ($totalPortNext != 0)) ? (($totalPort[$i]-$totalPortNext)/$totalPortNext) : 0;
//check if result is NaN
$momC = !is_nan($momC)? $momC: 0;
}
// $dates = $payload['rollDate'];
$data[$i] = ["MONTH" => $payload['rollDate'], "TOTAL VALUE" => $totalPort[$i], "MOM NGN CHANGE" => $mom ?? 0, "MOM % CHANGE" => $momC ?? 0];
// $data[$i]["MONTH"] = $payload['rollDate'];
// $data[$i]["TOTAL VALUE (₦)"] = $totalPort[$i];
// $data[$i]["MOM NGN CHANGE"] = $mom ?? 0;
// $data[$i]["MOM % CHANGE"] = $momC ?? 0;
}
}
//fetch application 7 months
//log Infoware response - Commneted by Tayo 30th of June for taking too much log space
//$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['fullName'], "7 months rolling average fetched for Portfolio " . $payload['portfolioID'] . ", with reference date " . $payload['refDate'], "Business ID is: " . $payload['BIZID'] . " on ". $payload['businessInvolvement'], "Rolling average fetched");
// return ["MONTH" => $dates, "TOTAL VALUE (₦)" => $totalPort, "MOM NGN CHANGE" => $mom ?? 0, "MOM % CHANGE" => $momC] ?? [];
$res = array_merge($res, $data);
return $res ?? [];
}
//created by Tayo 13th of June to compute SEC rolling average
public function totalRollingAvg($payload){
$cscs = $this->getCSCSNumber($payload)['data'];
// var_dump($cscs);
// die();
//$payload['rollDate'] = $payload['refDate'];
//$rollAvg = [];
$totalPort = $data = $res = [];
$mom = $momC = 0;
//Begin compute rolling Avegerage
for($i = 6 ; $i >= 0 ; $i--)
{
//Get previous months starting from earliest to current date
$dt = strtotime($payload['refDate']);
$payload['rollDate'] = date("Y-m-d", strtotime("-". $i ." month", $dt));
foreach($cscs as $cscsNo)
{
$payload['CSCSNumber'] = $cscsNo['CsCsAcct#'];
//fetch data for current month from infoware
$rollAvg = formatIWRes(container('IWSRequest')->rollingAvg($payload, $payload['rollDate']));
//$decoded_data = json_decode(json_encode($rollAvg));
//Number of records fetch
$count = count($rollAvg['data']);
if($count > 0)
{
//sum Market value for records fetch
for ($j=0 ; $j <= $count ; $j++)
{
$totalPort[$i] = $totalPort[$i] + $rollAvg['data'][$j]['MarketValue']*1;
}
}
}
if ($i < 6)
{
$totalPortNext = $totalPort[$i+1] ?? 0;
$mom = !is_null($totalPort[$i] - $totalPortNext) ? ($totalPort[$i] - $totalPortNext) : 0;
$momC = (!is_null(($totalPort[$i]-$totalPortNext)/$totalPortNext) && ($totalPortNext != 0)) ? (($totalPort[$i]-$totalPortNext)/$totalPortNext) : 0;
//check if result is NaN
$momC = !is_nan($momC)? $momC: 0;
}
// $dates = $payload['rollDate'];
$data[$i] = ["MONTH" => $payload['rollDate'], "TOTAL VALUE" => $totalPort[$i], "MOM NGN CHANGE" => $mom ?? 0, "MOM % CHANGE" => $momC ?? 0];
// $data[$i]["MONTH"] = $payload['rollDate'];
// $data[$i]["TOTAL VALUE (₦)"] = $totalPort[$i];
// $data[$i]["MOM NGN CHANGE"] = $mom ?? 0;
// $data[$i]["MOM % CHANGE"] = $momC ?? 0;
}
//fetch application 7 months
//log Infoware response - Commneted by Tayo 30th of June for taking too much log space
//$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['fullName'], "7 months rolling average fetched for Portfolio " . $payload['portfolioID'] . ", with reference date " . $payload['refDate'], "Business ID is: " . $payload['BIZID'] . " on ". $payload['businessInvolvement'], "Rolling average fetched");
// return ["MONTH" => $dates, "TOTAL VALUE (₦)" => $totalPort, "MOM NGN CHANGE" => $mom ?? 0, "MOM % CHANGE" => $momC] ?? [];
$res = array_merge($res, $data);
return $res ?? [];
}
public function CAMRollingAvg($payload) //create new fund
{
$totalPort = $data = $rez = [];
$mom = $momC = 0;
// var_dump($payload);
//Begin compute rolling Avegerage
for($i = 6 ; $i >= 0 ; $i--)
{
//Get previous months starting from earliest to current date
$dt = strtotime($payload['refDate']);
$payload['date'] = date("Y-m-d", strtotime("-". $i ." month", $dt));
//fetch data for current month from infoware
$result = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
$count = count($result);
if($count > 0)
{
/* foreach($result as $res)
{
$totalPort[$i] = $totalPort[$i] + $res['CURRENTVALUE'];
} */
$totalPort[$i] = array_sum(array_column($result, 'CURRENTVALUE')) ?? 0;
if ($i < 6)
{
$totalPortNext = $totalPort[$i+1] ?? 0;
$mom = !is_null($totalPort[$i] - $totalPortNext) ? ($totalPort[$i] - $totalPortNext) : 0;
$momC = (!is_null(($totalPort[$i]-$totalPortNext)/$totalPortNext) && ($totalPortNext != 0))? (($totalPort[$i]-$totalPortNext)/$totalPortNext) : 0;
//check if result is NaN
$momC = !is_nan($momC)? $momC: 0;
}
$data[$i] = ["MONTH" => $payload['date'], "TOTAL VALUE" => $totalPort[$i], "MOM NGN CHANGE" => $mom ?? 0, "MOM % CHANGE" => $momC ?? 0];
// $data[$i]["MONTH"] = $payload['date'];
// $data[$i]["TOTAL VALUE (₦)"] = $totalPort[$i];
// $data[$i]["MOM NGN CHANGE"] = $mom ?? 0;
// $data[$i]["MOM % CHANGE"] = $momC ?? 0;
}
}
//fetch application 7 months
//log Infoware response - Commneted by Tayo 30th of June for taking too much log space
//$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['fullName'], "7 months rolling average fetched for Portfolio " . $payload['portfolioID'] . ", with reference date " . $payload['refDate'], "Business ID is: " . $payload['BIZID'] . " on ". $payload['businessInvolvement'], "Rolling average fetched");
$rez = array_merge($rez, $data);
return $rez ?? [];
}
/**
* //send OTP modified by Tayo
*/
public function createOTPRequest($fullName, $customerId,$email,$otp, $phoneNumber, $bizFrom, $payload)
{
$responseData = "There was an error sending the OTP, kindly try again later.";
$isOTPValid = $this->withdrawalRequestOTPTable() //check if user has unused OTP
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->get();
if( count($isOTPValid) > 0){
$this->withdrawalRequestOTPTable()
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["used", "=", 0 ] ,
["expired", "=", 0 ]
])->update([
"used" => 1,
"expired" => 1,
'ipaddress' => $this->get_client_ip(),
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}
//create new OTP
$this->id = $this->withdrawalRequestOTPTable()
->insertGetId([
'CustID' => $customerId,
'emailAddress' => $email,
'fullName' => $fullName,
'phoneNumber' => $phoneNumber,
'bizFrom' => $bizFrom,
'ipaddress' => $this->get_client_ip(),
'otp' => $otp
]);
if($this->id > 0){
//send OTP via email
$result = [
"otp" => $otp,
"fullName" => str_replace(",","",$fullName),
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
// "accountNumber" => $payload['accountNumber'],
// "fundCode" => $payload['fundCode'],
// "redemptionDate" => $payload['redemptionDate'],
// "redemptionAmount" => $payload['redemptionAmount']
];
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->bcc("[email protected]")
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('general_otp', $result)
->send();
}else{
(new Mailer())
->to($email)
->bcc("[email protected]")
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('general_otp', $result)
->send();
}
$responseData = "OTP successfully sent to user's email";
}
return [
"message" => $responseData,
"data" => ["email" => $email]
];
}
public function createAdminOTPRequest($fullName, $customerId,$email,$otp, $phoneNumber, $bizFrom, $payload)
{
$responseData = "There was an error sending the OTP, kindly try again later.";
$isOTPValid = $this->withdrawalRequestOTPTable() //check if user has unused OTP
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->get();
if( count($isOTPValid) > 0){
$this->withdrawalRequestOTPTable()
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["used", "=", 0 ] ,
["expired", "=", 0 ]
])->update([
"used" => 1,
"expired" => 1,
'ipaddress' => $this->get_client_ip(),
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}
//create new OTP
$this->id = $this->withdrawalRequestOTPTable()
->insertGetId([
'CustID' => $customerId,
'emailAddress' => $email,
'fullName' => "ADMIN - " . str_replace(",","",$fullName),
'phoneNumber' => $phoneNumber,
'bizFrom' => $bizFrom,
'ipaddress' => $this->get_client_ip(),
'otp' => $otp
]);
if($this->id > 0){
//send OTP via email
if($payload['transactionType'] == "redemption")
{
$result = [
"otp" => $otp,
"fullName" => str_replace(",","",$fullName),
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"accountNumber" => $payload['accountNumber'],
"fundCode" => $payload['fundCode'],
"redemptionDate" => $payload['redemptionDate'],
"redemptionAmount" => $payload['redemptionAmount']
];
(new Mailer())
->to(\getenv("AMO-ADMIN-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('admin_red_general_otp', $result)
->send();
$responseData = "Redemption OTP successfully sent to user's email";
}elseif($payload['transactionType'] == "subscription")
{
$result = [
"otp" => $otp,
"fullName" => str_replace(",","",$fullName),
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"fundCode" => $payload['fundCode'],
"subscriptionAmount" => $payload['subscriptionAmount']
];
(new Mailer())
->to(\getenv("AMO-ADMIN-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('admin_sub_general_otp', $result)
->send();
$responseData = "Subscription OTP successfully sent to user's email";
}elseif(strtoupper($payload['transactionType']) == "ADMIN")
{
$result = [
"otp" => $otp,
"fullName" => str_replace(",","",$fullName),
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
// "fundCode" => $payload['fundCode'],
// "subscriptionAmount" => $payload['subscriptionAmount']
];
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('admin_otp', $result)
->send();
}else{
(new Mailer())
->to($payload['emailAddress'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('admin_otp', $result)
->send();
}
$responseData = "Subscription OTP successfully sent to admin's email";
}
}
return [
"message" => $responseData,
"data" => ["email" => $email]
];
}
public function KYCReport($status)
{
$query = $this->KYCTable();
if ($status === 'pending') {
$query->where(function ($query) {
$query->whereNull('approval')
->orWhere('approval', 'under review');
});
} elseif ($status === 'approved') {
$query->where('approval', 'approved');
} elseif ($status === 'rejected') {
$query->where('approval', 'rejected');
}
return $query->get();
}
//Created by Tayo 31st August to fetch pending KYC images from local db
public function KYCImages($payload)
{
return $this->KYCImage()
->where([
["requestID", "=", $payload['requestID']],
])
->get();
}
public function IWKYCImage($payload)
{
$result = formatIWRes(container('IWSRequest')->PGetData2('cp_0015', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'] ?? [];
return $result;
}
//Created by Tayo 31st August to fetch pending KYC requests from Infoware
public function IWKYCReport()
{
$record = formatIWRes(container('IWSRequest')->getAllKYC())['data'];
// $record += formatIWRes(container('IWSRequest')->PGetData2('cp_0015', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
// $result = formatIWRes(container('IWSRequest')->PGetData2('cp_0015', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
return $record;
}
//Created by Tayo 31st August to submit abridged KYC update to local table
public function KYCSubmit($payload)
{
$kycRequest = $this->KYCTable()
->where(
[["emailAddress","=", $payload['emailAddress']], ["approval", "=", 'under review'], ["CustID", "=", $payload["CustID"]]])
->first();
if(count($kycRequest) != 0)
{
return ["code" => 400,"message" => "You already submitted a KYC request which is under review"];
}
//post data to local KYCTable
if(strtoupper($payload['accountType']) == "IND"){
$this->id = $this->KYCTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'ASSETID' => $payload['ASSETID'],
'SECID' => $payload['SECID'],
'firstName' => $payload['firstName'],
'lastName' => $payload['lastName'],
'otherNames' => $payload['otherNames'],
'BVNFirstName' => $payload['BVNFirstName'],
'BVNLastName' => $payload['BVNLastName'],
'BVNMiddleName' => $payload['BVNMiddleName'],
'emailAddress' => $payload['emailAddress'],
'phoneNumber' => $payload['phoneNumber'],
'country' => $payload['country'],
'state' => $payload['state'],
'city' => $payload['city'],
'lga' => $payload['lga'],
'address' => $payload['address'],
'bankAcctName' => $payload['bankAcctName'],
'bankAcctNumber' => $payload['bankAcctNumber'],
'bankName' => $payload['bankName'],
'bankName' => $payload['bankName'],
'bankCode' => $payload['bankCode'],
'BVNNumber' => $payload['BVNNumber'],
'sortCode' => $payload['sortCode'],
'motherMaidenName' => $payload['motherMaidenName'],
'NOKName' => $payload['NOKName'],
// "address2" => $payload['address2'],
// "issueDate" => $payload['issueDate'],
// "proofOfAddress" => $payload['proofOfAddress'],
'identityType' => $payload['identityType'],
'identityExpiryDate' => $payload['identityExpiryDate'],
'identityNumber' => $payload['identityNumber'],
'accountType' => $payload['accountType'],
'bizFrom' => $payload['bizFrom'],
"approval" => "under review"
// 'RCNo' => $payload['RCNo'],
]);
} elseif(strtoupper($payload['accountType']) == "CORP"){
$this->id = $this->KYCTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'ASSETID' => $payload['ASSETID'],
'SECID' => $payload['SECID'],
'compName' => $payload['compName'],
'BVNFirstName' => $payload['BVNFirstName'],
'BVNLastName' => $payload['BVNLastName'],
'BVNMiddleName' => $payload['BVNMiddleName'],
'emailAddress' => $payload['emailAddress'],
'phoneNumber' => $payload['phoneNumber'],
'country' => $payload['country'],
'state' => $payload['state'],
'city' => $payload['city'],
'lga' => $payload['lga'],
'address' => $payload['address'],
// "address2" => $payload['address2'],
// "issueDate" => $payload['issueDate'],
// "proofOfAddress" => $payload['proofOfAddress'],
'bankAcctName' => $payload['bankAcctName'],
'bankAcctNumber' => $payload['bankAcctNumber'],
'bankName' => $payload['bankName'],
'bankCode' => $payload['bankCode'],
'BVNNumber' => $payload['BVNNumber'],
'sortCode' => $payload['sortCode'],
'identityType' => $payload['identityType'],
'identityExpiryDate' => $payload['identityExpiryDate'],
'identityNumber' => $payload['identityNumber'],
'RCNo' => $payload['RCNo'],
'accountType' => $payload['accountType'],
'bizFrom' => $payload['bizFrom'],
"approval" => "under review"
]);
}
if($this->id > 0){
$requestID = $this->id;
$data = [
"message" => "KYC Update request submitted",
"status" => "success",
"code" => 200
];
$filename= "";
$directory = dirname(__DIR__, 2) . "/public_view/files/kyc/";
foreach($payload['files'] as $file)
{
$uploadedFile = $file;
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile($directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
//insert image
$this->id = $this->KYCImage()
->insertGetId([
'CustID' => $payload['CustID'],
'requestID' => $requestID,
'imageID' => "img-".mt_rand(100000, 999999),
'name' => $filename,
'url' => env('IMAGE_URL')."kyc/",
'extension' => $extension,
]);
}
}else{
$data = [
"message" => "KYC Update request submission failed",
"status" => "failed",
"code" => 400
];
}
//send email notification
$payload['fullName'] = (strtoupper($payload["accountType"]) == "IND") ? $payload['lastName'] ." " . $payload['firstName'] : $payload['compName'];
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
];
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Update Request")
->usingView('kyc_submit_notification', $mail)
->send();
}else{
(new Mailer())
->to($payload['emailAddress'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Update Request")
->usingView('kyc_submit_notification', $mail)
->send();
}
return $data;
}
//Created by Tayo 31st August to approve KYC requests on local db and push to infoware
public function KYCApprove($payload)
{
//select all data for Infoware push
$approve = $this->KYCTable()
->where(function ($query) use ($payload) {
$query->where('ID', $payload['ID'])
->where(function ($query) {
$query->whereNull('approval')
->orWhere('approval', 'under review');
});
})
->first();
if(count($approve) > 0)
{
$decodedApprove = json_decode(json_encode($approve),true);
if(!empty($decodedApprove ) && !is_null($decodedApprove) && $decodedApprove != [] && $decodedApprove != "")
{
//push data to infoware
$kycupdate = formatIWRes(container('IWSRequest')->updateIWKYC($decodedApprove))['StatusID'];
// var_dump("kyc push to infoware status ID is ". $kycupdate);
if($kycupdate == 0)
{
//select all client images for upload to infoware
$docload = $this->KYCImage()
->where([
["CustID", "=", $decodedApprove['CustID']],
["requestID", "=", $decodedApprove['ID']],
])
->get();
$decodedDocload = json_decode(json_encode($docload),true);
//upload documents to infoware
$imageUpload = $this->kycFileUpload($decodedDocload, $decodedApprove['CustID'], MIDDLEWARE_DB_NAME);
if($imageUpload > 0)
{
//update kyc status on Infoware
$kycStatus = formatIWRes(container('IWSRequest')->updateIWKYCStatus($decodedApprove['CustID']))['StatusID'];
// var_dump("kycStatus is " . $kycStatus);
if($kycStatus == 0)
{
//send KYC rejection status notificaiton to client
$mail = [
"fullName" => str_replace(",","",$decodedApprove['lastName']. " " .$decodedApprove['firstName']),
"CustID" => $decodedApprove['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $decodedApprove['phoneNumber'],
"emailAddress" => $decodedApprove['emailAddress'],
];
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Approved Notification")
->usingView('kyc_approve_notify', $mail)
->send();
}else{
(new Mailer())
->to($decodedApprove['emailAddress'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Approved Notification")
->usingView('kyc_approve_notify', $mail)
->send();
}
//update approval field to approved
$update = $this->KYCTable()
->where(function ($query) use ($payload) {
$query->where('ID', $payload['ID'])
->where(function ($query) {
$query->whereNull('approval')
->orWhere('approval', 'under review');
});
})
->update([
"approval" => "approved",
"comment" => "Approved by ". $payload['admin'] ,
"approvalDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
//create wallet for user. First check if user has wallet involvment
$decodedApprove["fullName"] = str_replace(",","",$decodedApprove['lastName']. " " .$decodedApprove['firstName']);
$decodedApprove["fundCode"] = "CSWALLET";
$decodedApprove["company"] = "GROUP";
$decodedApprove["description"] = "CARDINALSTONE WALLET";
$decodedApprove["product"] = "CSWALLET";
$result = $this->nubanTable()
->where([
["product", "=", $decodedApprove['product'] ],
["fundCode", "=", $decodedApprove['fundCode'] ],
["CustID", "=", $decodedApprove['CustID'] ],
])->get();
if(empty($result) || count($result) == 0 || is_null($result[0]->accountName) || is_null($result[0]->accountNumber))
{
$this->createNubanCustomer($decodedApprove);
}
$data = [
"message" => "KYC Approved, data submitted to Infoware, and client is notified",
"status" => "success",
"code" => 200
];
}else{
$data = [
"message" => "KYC status update on Infoware failed",
"status" => "error",
"code" => 400
];
}
}else{
$data = [
"message" => "Image upload to Infoware failed",
"status" => "error",
"code" => 400
];
}
}else{
$data = [
"message" => "KYC data push to Infoware failed",
"status" => "error",
"code" => 400
];
}
}else{
$data = [
"message" => "record not found",
"status" => "error",
"code" => 400
];
}
return $data;
}else{
$data = [
"message" => "No pending KYC request for this client",
"status" => "success",
"code" => 200
];
}
return $data;
}
public static function getCustomerData()
{
$result = [];
if (!$result = container('cache')->fetch('customerData')) {
$data = formatIWRes(container('IWSRequest')->getCustomerData());
$result = $data;
container('cache')->save('customerData', $result, 60 * 60 * 60);
}
return $result;
}
public static function getTradesData($payload)
{
$data = formatIWRes(container('IWSRequest')->getTradesData($payload['startDate'], $payload['endDate']));
return $data;
}
public static function getBirthdayData()
{
$result = [];
if (!$result = container('cache')->fetch('birthdayData')) {
$data = formatIWRes(container('IWSRequest')->retrieveBirthdays());
$result = $data;
container('cache')->save('birthdayData', $result, 60 * 60 * 24);
}
return $result;
}
public static function getCAMData_1()
{
// Assuming $data is a JSON string from container('IWSRequest')->getCAMData_1();
$data = formatIWRes(container('IWSRequest')->getCAMData_1());
// Recursive function to sanitize data
$sanitizeData = function (&$item) use (&$sanitizeData) {
if (is_array($item)) {
foreach ($item as $key => $value) {
if (is_string($value) && stripos($value, "<SCRIPT>") !== false) {
unset($item[$key]);
} elseif (is_array($value)) {
$sanitizeData($item[$key]);
}
}
}
};
// Apply sanitization
$sanitizeData($data);
return $data;
}
public static function getCAMData_2()
{
$data = formatIWRes(container('IWSRequest')->getCAMData_2());
return $data;
}
public static function getCAMData_3()
{
$data = formatIWRes(container('IWSRequest')->getCAMData_3());
return $data;
}
public static function getCAMData_4()
{
$data = formatIWRes(container('IWSRequest')->getCAMData_4());
return $data;
}
public static function getCAMData_5()
{
$data = formatIWRes(container('IWSRequest')->getCAMData_5());
return $data;
}
public function KYCReject($payload)
{
$comment = [];
$i=0;
foreach ($payload['comment'] as $key => $value) //write rejection reasons into an array
{
$comment[$i] = $value;
$reason = $reason . "" .$value . ", ";
$i += 1;
}
$update = $this->KYCTable()
->where(function ($query) use ($payload) {
$query->where('ID', $payload['ID'])
->where(function ($query) {
$query->whereNull('approval')
->orWhere('approval', 'under review');
});
})
->update([
"approval" => "rejected",
"comment" => "Rejected by ". $payload['admin'] . " due to " . $reason,
"approvalDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
// var_dump($update);
if($update > 0)
{
$approve = $this->KYCTable()
->where([
["ID", "=", $payload['ID']],
])
->first();
$decodedApprove = json_decode(json_encode($approve),true);
//send KYC rejection status notificaiton to client
$mail = [
"fullName" => str_replace(",","",$decodedApprove['lastName']. " " .$decodedApprove['firstName']),
"CustID" => $decodedApprove['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $decodedApprove['phoneNumber'],
"emailAddress" => $decodedApprove['emailAddress'],
"comment" => $comment,
];
// var_dump($mail);
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Rejected Notification")
->usingView('kyc_reject_notify', $mail)
->send();
}else{
(new Mailer())
->to($decodedApprove['emailAddress'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Rejected Notification")
->usingView('kyc_reject_notify', $mail)
->send();
}
$data = [
"message" => "KYC rejected and client notified",
"status" => "success",
"code" => 200
];
return $data;
}
$data = [
"message" => "No pending KYC request for this client",
"status" => "success",
"code" => 200
];
return $data;
}
//Created by Tayo 31st August to approve KYC requests on infoware
/* public function IWKYCApprove($payload)
{
//update kyc status
// $kycStatus = formatIWRes(container('IWSRequest')->updateIWKYCStatus($payload['CustID']))['data'][0];
$kycStatus = formatIWRes(container('IWSRequest')->updateIWKYCStatus($payload['CustID']))['StatusID'];
// var_dump("kycStatus is " . $kycStatus);
if($kycStatus == 0)
{
//send KYC rejection status notificaiton to client
$data = [
"message" => "KYC Approved and updated Infoware",
"status" => "success",
"code" => 200
];
return $data;
}
return;
} */
public function IWKYCApprove($payload)
{
//update kyc status
$kycStatus = formatIWRes(container('IWSRequest')->updateIWKYCStatus($payload['CustID']))['StatusID'];
if($kycStatus == 0)
{
//send KYC status notificaiton to client
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
];
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Approved Notification")
->usingView('kyc_approve_notify', $mail)
->send();
}else{
(new Mailer())
->to($decodedApprove['emailAddress'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Approved Notification")
->usingView('kyc_approve_notify', $mail)
->send();
}
$data = [
"message" => "KYC Approved, updated Infoware, and client notified",
"status" => "success",
"code" => 200
];
return $data;
}
return;
}
/* public function IWKYCReject($payload)
{
//send KYC rejection status notificaiton to client
$data = [
"message" => "KYC status notificaiton sent",
"status" => "success",
"code" => 200
];
return $data;
} */
public function IWKYCReject($payload)
{
$comment = [];
$i=0;
foreach ($payload['comment'] as $key => $value) //write rejection reasons into an array
{
$comment[$i] = $value;
$i += 1;
}
//send KYC rejection status notificaiton to client
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"comment" => $comment,
];
// var_dump($mail);
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Rejected Notification")
->usingView('kyc_reject_notify', $mail)
->send();
}else{
(new Mailer())
->to($decodedApprove['emailAddress'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Rejected Notification")
->usingView('kyc_reject_notify', $mail)
->send();
}
$data = [
"message" => "KYC rejection notificaiton sent",
"status" => "success",
"code" => 200
];
return $data;
/* $data = [
"message" => "KYC status notificaiton sent",
"status" => "success",
"code" => 200
];
return $data; */
}
public function resendOTPRequest($fullName, $customerId,$email,$otp, $phoneNumber, $bizFrom, $payload)
{
//$responseData = "There was an error sending the OTP, kindly try again later.";
$isOTPValid = $this->withdrawalRequestOTPTable()//check if user has unused OTP
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->get();
if( count($isOTPValid) > 0){
$this->withdrawalRequestOTPTable()
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["used", "=", 0 ] ,
["expired", "=", 0 ]
])->update([
"used" => 1,
"expired" => 1,
'ipaddress' => $this->get_client_ip(),
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}
//create new OTP
$this->id = $this->withdrawalRequestOTPTable()
->insertGetId([
'CustID' => $customerId,
'emailAddress' => $email,
'fullName' => str_replace(",","",$fullName),
'phoneNumber' => $phoneNumber,
'bizFrom' => $bizFrom,
'ipaddress' => $this->get_client_ip(),
'otp' => $otp
]);
if($this->id > 0){
//send OTP via email
$result = [
"otp" => $otp,
"fullName" => str_replace(",","",$fullName),
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
// "accountNumber" => $payload['accountNumber'],
// "fundCode" => $payload['fundCode'],
// "redemptionDate" => $payload['redemptionDate'],
// "redemptionAmount" => $payload['redemptionAmount']
];
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('general_otp', $result)
->send();
}else{
(new Mailer())
->to($email)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('general_otp', $result)
->send();
}
$responseData = "OTP successfully sent to user's email";
}
return [
"message" => $responseData,
"data" => ["email" => $email]
];
}
public function resendAdminOTPRequest($fullName, $customerId,$email,$otp, $phoneNumber, $bizFrom, $admin)
{
//$responseData = "There was an error sending the OTP, kindly try again later.";
$isOTPValid = $this->withdrawalRequestOTPTable()//check if user has unused OTP
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->get();
if( count($isOTPValid) > 0){
$this->withdrawalRequestOTPTable()
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["used", "=", 0 ] ,
["expired", "=", 0 ]
])->update([
"used" => 1,
"expired" => 1,
'ipaddress' => $this->get_client_ip(),
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}
//create new OTP
$this->id = $this->withdrawalRequestOTPTable()
->insertGetId([
'CustID' => $customerId,
'emailAddress' => $email,
'fullName' => str_replace(",","",$fullName),
'phoneNumber' => $phoneNumber,
'bizFrom' => $bizFrom,
'ipaddress' => $this->get_client_ip(),
'otp' => $otp
]);
if($this->id > 0){
//send OTP via email
$result = [
"otp" => $otp,
"fullName" => str_replace(",","",$fullName),
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"accountNumber" => $payload['accountNumber'],
"fundCode" => $payload['fundCode'],
"redemptionDate" => $payload['redemptionDate'],
"redemptionAmount" => $payload['redemptionAmount']
];
(new Mailer())
->to(\getenv("AMO-ADMIN-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("OTP Notification")
->usingView('admin_red_general_otp', $result)
->send();
$responseData = "OTP successfully sent to user's email";
}
return [
"message" => $responseData,
"data" => ["email" => $email]
];
}
/**
* create a fundcode record on our DB
*/
public function verifyOTPRequest($customerId,$email,$otp)
{
//$responseData = "There was an error verifying the OTP, kindly try again later.";
// var_dump($customerId);
// var_dump($email);
// var_dump($otp);
$isOTPValid = $this->withdrawalRequestOTPTable()
->where([
["CustID", "=", $customerId ],
["otp", "=", $otp ],
["emailAddress", "=", $email ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->get();
if( count($isOTPValid) == 0){
$data = [
"message" => "Invalid OTP. Please try again.",
"status" => "error",
"code" => 400
];
}elseif(count($isOTPValid) > 0){
//check if OTP has expired after 10 minutes of being created.
//error_log("isOTPValid: ". $isOTPValid[0]->createdDate);
$now = Carbon::now()->format('Y-m-d H:i:s');
$otpCreated = Carbon::parse($isOTPValid[0]->createdDate);
if($otpCreated->diffInMinutes($now) > 10){
//set used to true, insert usedDate, and set expired to true
$this->withdrawalRequestOTPTable()
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["otp", "=", $otp ],
["used", "=", 0 ] ,
["expired", "=", 0 ]
])->update([
"used" => 1,
"expired" => 1,
'ipaddress' => $this->get_client_ip(),
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
$data = [
"message" => "OTP Expired. Please generate another OTP",
"status" => "error",
"code" => 400
];
}else{
//set used to true and insert usedDate
$this->withdrawalRequestOTPTable()
->where([
["CustID", "=", $customerId ],
["emailAddress", "=", $email ],
["otp", "=", $otp ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->update([
"used" => 1,
'ipaddress' => $this->get_client_ip(),
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
$data = [
"message" => "OTP Verified",
"status" => "success",
"code" => 200
];
}
}
return $data;
}
public function requestAccountDeletion($customerId, $emailAddress, $clientName)
{
$record = [
'clientName' => $clientName,
'emailAddress' => $emailAddress,
'customerId' => $customerId,
'requestDate' => Carbon::now()->format('Y-m-d H:i:s')
];
(new Mailer())
->to($emailAddress)
->bcc(\getenv('IT-UNIT-EMAIL'), 'IT Unit')
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Account Deletion Request")
->usingView('account_deletion_request', $record)
->send();
(new Mailer())
->to(\getenv("AMO-ADMIN-EMAIL"), 'CardinalStone')
->bcc(\getenv('IT-UNIT-EMAIL'), 'IT Unit')
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Account Deletion Request Notification")
->usingView('account_deletion_request_notification', $record)
->send();
return ["code" => 200, "message" => "Your account deletion process is underway and will be finalized within 48 hours.."];
}
//end of send OTP modified by Tayo
/**
* This Method returns the customer's internet banking data
*
* @param type $id
* @return type Array
* @author ewomazino.ukah <[email protected]>
*/
public function fetchCustomerData($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$stockBrokingCustomerId = $payload['stockbrokingID'] = $customerz[0]['SECID'];
$assetMgmtCustomerId = $payload['assetMgmtID'] = $customerz[0]['ASSETID'];
$CAMCustomerId = $payload['CAMID'] = $customerz[0]['CAMID'];
return [
'stockBrokingCustomerId' => $payload['stockbrokingID'],
'assetMgmtCustomerId' => $payload['assetMgmtID'],
'CAMCustomerId' => $payload['CAMID'],
'SMA-CAM' => container('SMA_CAMModel')->findAccounts($CAMCustomerId),
'FI-CAM' => container('termInstrument_CAMModel')->findCustomerTermInstruments($CAMCustomerId),
'MF-CAM' => container('mutualFund_CAMModel')->findAccounts($CAMCustomerId),
'STB' => container('stockbrokingModel')->findCSCSAccounts($stockBrokingCustomerId),
'CA' => container('cashAccountModel')->findCustomerCashAccts($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId),
'SMA' => container('SMAModel')->findAccounts($assetMgmtCustomerId),
'FI' => container('termInstrumentModel')->findCustomerTermInstruments($assetMgmtCustomerId),
'MF' => container('mutualFundModel')->findAccounts($assetMgmtCustomerId),
'TROVE' => container('foreignEquityModel')->findAccounts($stockBrokingCustomerId),
];
}
/**
*
* This Method returns the customer's internet banking data on the middleware
*
* @param type $middlewareId
* @return type Array
* @author ewomazino.ukah <[email protected]>
*/
public function getCustomerDetails($middlewareId)
{
$customerDetails = formatIWRes(
container('IWSRequest')->PGetData2('CP_0004', $middlewareId, MIDDLEWARE_DB_NAME)
)['data'][0];
$customerDetails["Gender"] = ($customerDetails["Gender"] == "1") ? "Male" : "Female";
$customerBankDetails = $this->getCustomerBankDetails($middlewareId)[0] ?? [];
return array_merge($customerDetails, $customerBankDetails);
}
/**
*
* This Method returns the customer's internet banking data on the middleware
*
* @param type $middlewareId
* @author ewomazino.ukah <[email protected]>
*/
public function getCustomerBankDetails($middlewareId)
{
// $bankDetails = formatIWRes(container('IWSRequest')->PGetData2('CP_0002', $middlewareId, MIDDLEWARE_DB_NAME))['data'] ?? [];
$bankDetails = formatIWRes(container('IWSRequest')->PGetData2('CP_0002', $middlewareId, MIDDLEWARE_DB_NAME))['data'] ?? [];
$i=0;
foreach($bankDetails as $bank)
{
$icode = $this->bankCode($bank['BankName']);
$bankDetails[$i]['SortCode'] = $icode->iCode;
$i=$i+1;
}
return $bankDetails;
}
/**
*
* This Method returns the all matched customers using the provided query on the middleware
*
* @param type $query
* @return type Array
* @author ewomazino.ukah <[email protected]>
*/
public function birthdayReport()
{
$customers = formatIWRes(
container('IWSRequest')->PGetData('CP_0008', MIDDLEWARE_DB_NAME)
)['data'];
return $customers;
}
/* public function searchForCustomers($query)
{
if($query == null){
//var_dump("No Query");
//var_dump("Results----");
$customers = formatIWRes(container('IWSRequest')->PGetData('CP_0008', MIDDLEWARE_DB_NAME))['data'];
// $customers = formatIWRes(container('IWSRequest')->PGetData('CP_0016', MIDDLEWARE_DB_NAME))['data'];
//var_dump($customers);
$customers = array_map(function ($customer) {
return array_merge($customer, [
'customerId' => $customer['CustAID'],
'assetMgmtID' => $customer['CSPCustAID'],
'stockbrokingID' => $customer['CSSCustAID'],
'CAMCustomerId' => $customer['CAMCustAID '] ?? null,
]);
}, $customers);
$customers = array_values($customers);
}else{
//var_dump("There is Query");
$cacheKey = "search.$query";
if (!$customers = container('cache')->fetch($cacheKey)) {
$customers = formatIWRes(
container('IWSRequest')->PGetData('CP_0008', MIDDLEWARE_DB_NAME)
)['data'];
$customers = array_filter($customers, function ($customer) use ($query) {
return strpos(strtolower($customer['Name']), strtolower($query)) !== false;
});
$customers = array_map(function ($customer) {
return array_merge($customer, [
'customerId' => $customer['CustAID'],
'assetMgmtID' => $customer['CSPCustAID'],
'stockbrokingID' => $customer['CSSCustAID'],
'CAMCustomerId' => $customer['CAMCustAID']
]);
}, $customers);
$customers = array_values($customers);
container('cache')->save($cacheKey, $customers, 60 * 3);
}
}
return $customers;
} */
public function searchForCustomers($query)
{
if($query == null){
$customers = [];
if(!$customers = container('cache')->fetch('customerInfo')){
//var_dump($customers);
$customers = formatIWRes(container('IWSRequest')->PGetData('CP_0016', MIDDLEWARE_DB_NAME))['data'];
container('cache')->save('customerInfo', $customers, 60 * 60 * 6);
$customers = array_map(function ($customer) {
return array_merge($customer, [
'customerId' => $customer['CustAID'],
'assetMgmtID' => $customer['CSPCustAID'] ?? null,
'stockbrokingID' => $customer['CSSCustAID'] ?? null,
'CAMCustomerId' => $customer['CAMCustAID '] ?? null,
'CRMID' => $customer['CRMID'] ?? null
]);
}, $customers);
$customers = array_values($customers);
}
else{
$customers = array_map(function ($customer) {
return array_merge($customer, [
'customerId' => $customer['CustAID'],
'assetMgmtID' => $customer['CSPCustAID'] ?? null,
'stockbrokingID' => $customer['CSSCustAID'] ?? null,
'CAMCustomerId' => $customer['CAMCustAID '] ?? null,
'CRMID' => $customer['CRMID'] ?? null
]);
}, $customers);
$customers = array_values($customers);
}
}
else{
$cacheKey = "search.$query";
if (!$customers = container('cache')->fetch($cacheKey)) {
// $customers = formatIWRes(container('IWSRequest')->PGetData('CP_0008', MIDDLEWARE_DB_NAME))['data'];
$customers = formatIWRes(container('IWSRequest')->PGetData('CP_0016', MIDDLEWARE_DB_NAME))['data'];
$customers = array_filter($customers, function ($customer) use ($query) {
return strpos(strtolower($customer['Name']), strtolower($query)) !== false;
});
$customers = array_map(function ($customer) {
return array_merge($customer, [
'customerId' => $customer['CustAID'],
'assetMgmtID' => $customer['CSPCustAID'],
'stockbrokingID' => $customer['CSSCustAID'],
'CAMCustomerId' => $customer['CAMCustAID']
]);
}, $customers);
$customers = array_values($customers);
container('cache')->save($cacheKey, $customers, 60 * 3);
}
}
return $customers;
}
public function mutualFundLogin($customerId, $password)
{
//fetch username
$username = formatIWRes(container('IWSRequest')->PGetData2('css_0018', $customerId, MIDDLEWARE_DB_NAME))['data'];
// if($username[0]['userName'] == $customerId)
if(!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != "")
{
$customerId = $username[0]['CustID'];
}
return $this->detectApplicationLockdown()
->loginToMiddleware($customerId, $password)
->retrieveCustomersInvolvement()
->mutualFundRespond();
}
public function mutualFundLoginDetails($payload)
{
$this->customerData['UserID'] = $payload['CustID'];
$customerId = $payload['CustID'];
//fetch additional information
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $customerId, MIDDLEWARE_DB_NAME))['data'];
$this->customerData['Fullname'] = str_replace(","," ",$customers[0]['Name']);
$this->customerData['companyName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['fullName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['firstName'] = str_replace(","," ",trim($customers[0]['FirstName']));
$this->customerData['lastName'] = str_replace(","," ",trim($customers[0]['LastName']));
$this->customerData['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
$this->customerData['BVNFirstName'] = str_replace(",","",$customers[0]['BVNFirstName']);
$this->customerData['BVNLastName'] = str_replace(","," ",trim($customers[0]['BVNLastName']));
$this->customerData['BVNMiddleName'] = str_replace(","," ",trim($customers[0]['BVNMiddleName']));
$this->customerData['userName'] = trim($customers[0]['userName']);
$this->customerData['gender'] = $customers[0]['Gender'];
$this->customerData['SECID'] = $customers[0]['SECID'];
$this->customerData['CustID'] = $customers[0]['CustID'];
$this->customerData['ASSETID'] = $customers[0]['ASSETID'];
$this->customerData['CAMID'] = $customers[0]['CAMID'];
$this->customerData['CAM'] = $customers[0]['CAM'];
$this->customerData['CSS'] = $customers[0]['CSS'];
$this->customerData['CSP'] = $customers[0]['CSP'];
$this->customerData['CSA'] = $customers[0]['CSA'];
$this->customerData['CST'] = $customers[0]['CST'];
$this->customerData['CSRL'] = $customers[0]['CSRL'];
$this->customerData['TROVE'] = $customers[0]['TROVE'];
$this->customerData['MF'] = $customers[0]['MF'];
$this->customerData['SMA'] = $customers[0]['SMA'];
$this->customerData['MGIN'] = $customers[0]['MGIN'];
$this->customerData['IBD'] = $customers[0]['IBD'];
$this->customerData['SOF'] = $customers[0]['SOF'];
$this->customerData['isCSCSNumber'] = $this->isCSCSNumber($customers[0]['SECID']);
$this->customerData['emailAddress'] = $customers[0]['Email1'];
$this->customerData['phoneNumber'] = $customers[0]['Phone1'];
$this->customerData['accountType'] = $customers[0]['ClientType'];
$this->customerData['Address'] = $customers[0]['Address1'].", ".$customers[0]['State'].", ".$customers[0]['City'].", ".$customers[0]['Country'];
// $accountOfficer = explode(" ",$customers[0]['AccountOfficer']);
$this->customerData['AccountOfficer'] = (is_null($customers[0]['AccountOfficer']) || $customers[0]['AccountOfficer'] == "") ? "Investment Advisor" : $customers[0]['AccountOfficer'];
$this->customerData['accountOfficerEmail'] = (!is_null($customers[0]['accountOfficerEmail']) && !empty($customers[0]['accountOfficerEmail']) && $customers[0]['accountOfficerEmail'] != "") ? $customers[0]['accountOfficerEmail'] : "[email protected]";
$this->customerData['accountOfficerPhoneNo'] = (is_null($customers[0]['accountOfficerPhoneNo']) || $customers[0]['accountOfficerPhoneNo'] == "") ? "+2347100433" : $customers[0]['accountOfficerPhoneNo'];
return $this->retrieveCustomersInvolvement()
->mutualFundRespond();
}
//created by Tayo for Mutual Funds Admin login 24th of June
public function mutualFundAdminLogin($customerId, $admin)
{
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $customerId, MIDDLEWARE_DB_NAME))['data'];
$this->customerData = $customers;
$this->customerData['UserID'] = $customerId;
$this->customerData['CustID'] = $customerId;
$this->customerData['Fullname'] = str_replace(","," ",$customers[0]['Name']);
$this->customerData['companyName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['fullName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['firstName'] = str_replace(","," ",trim($customers[0]['FirstName']));
$this->customerData['lastName'] = str_replace(","," ",trim($customers[0]['LastName']));
$this->customerData['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
$this->customerData['BVNFirstName'] = str_replace(",","",$customers[0]['BVNFirstName']);
$this->customerData['BVNLastName'] = str_replace(","," ",trim($customers[0]['BVNLastName']));
$this->customerData['BVNMiddleName'] = str_replace(","," ",trim($customers[0]['BVNMiddleName']));
$this->customerData['Email'] = $customers[0]['Email1'];
$this->customerData['emailAddress'] = $customers[0]['Email1'];
$this->customerData['Phone'] = $customers[0]['Phone1'];
$this->customerData['phoneNumber'] = $customers[0]['Phone1'];
$this->customerData['admin'] = $admin;
return $this->detectApplicationLockdown()
->retrieveCustomersInvolvementAdmin($customerId)
->mutualFundAdminRespond();
/*
$customers = array_filter($customers, function ($customer) use ($query) {
return strpos(strtolower($customer['Name']), strtolower($query)) !== false;
});
$customers = array_map(function ($customer) {
return array_merge($customer, [
'customerId' => $customer['CustAID'],
'assetMgmtID' => $customer['CSPCustAID'],
'stockbrokingID' => $customer['CSSCustAID'],
'CAMCustomerId' => $customer['CAMCustAID']
]);
}, $customers);
$customers = array_values($customers); */
//return $customers;
}
//created by Tayo to retreive customer involvement when logged in as Admin 24th of June
private function retrieveCustomersInvolvementAdmin($customerId)
{
$response = formatIWRes(
container('IWSRequest')->PGetData2('P_00090', $customerId, MIDDLEWARE_DB_NAME)
);
if ($response['StatusID'] !== NOERROR) {
throw new \Exception($response['StatusMessage'], 422);
}
// we return an empty array here to ensure every new user without
// stockbroking and asset management account can login,
$this->customerData['involvements'] = $response['data'] ?? [];
return $this;
}
/**
* Login the customer and return the customer data
* @todo change userId to username
* @param string $name
* @param string $password
* @return array
* @author ewomazino.ukah <[email protected]>
*/
public function login($customerId, $password)
{
//fetch username
$username = formatIWRes(container('IWSRequest')->PGetData2('css_0018', $customerId, MIDDLEWARE_DB_NAME))['data'];
// if($username[0]['userName'] == $customerId)
if(!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != "" )
{
$customerId = $username[0]['CustID'];
}
return $this->detectApplicationLockdown()
->loginToMiddleware($customerId, $password)
->retrieveCustomersInvolvement()
// ->retrieveCustomersInvolvement()
->respond();
// ->respond();
}
public function login_1($customerId, $password)
{
//fetch username
$username = formatIWRes(container('IWSRequest')->PGetData2('css_0018', $customerId, MIDDLEWARE_DB_NAME))['data'];
// if($username[0]['userName'] == $customerId)
if(!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != "" )
{
$customerId = $username[0]['CustID'];
}
return $this->detectApplicationLockdown()
->loginToMiddleware_1($customerId, $password);
}
public function findCustomerByNameDetails($payload)
{
$this->customerData['UserID'] = $payload['CustID'];
$this->customerData['hasTransferPin'] = false;
$this->customerData['isProfileCompleted'] = false;
$customerId = $payload['CustID'];
if(ENVIRONMENT === 'testing'){
$verify = $this->getPinRecord($payload);
if($verify['code'] === 200)
{
$this->customerData['hasTransferPin'] = true;
}
}
//fetch additional information
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $customerId, MIDDLEWARE_DB_NAME))['data'];
if (
$customers[0]['BVN'] != '' &&
$customers[0]['BVNFirstName'] != '' &&
$customers[0]['BVNLastName'] != ''
){
$this->customerData['isProfileCompleted'] = true;
}
$this->customerData['Fullname'] = str_replace(","," ",$customers[0]['Name']);
$this->customerData['companyName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['fullName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['firstName'] = str_replace(","," ",trim($customers[0]['FirstName']));
$this->customerData['lastName'] = str_replace(","," ",trim($customers[0]['LastName']));
$this->customerData['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
$this->customerData['BVNFirstName'] = str_replace(",","",$customers[0]['BVNFirstName']);
$this->customerData['BVNLastName'] = str_replace(","," ",trim($customers[0]['BVNLastName']));
$this->customerData['BVNMiddleName'] = str_replace(","," ",trim($customers[0]['BVNMiddleName']));
$this->customerData['userName'] = trim($customers[0]['userName']);
$this->customerData['gender'] = $customers[0]['Gender'];
$this->customerData['SECID'] = $customers[0]['SECID'];
$this->customerData['CustID'] = $customers[0]['CustID'];
$this->customerData['ASSETID'] = $customers[0]['ASSETID'];
$this->customerData['CAMID'] = $customers[0]['CAMID'];
$this->customerData['CAM'] = $customers[0]['CAM'];
$this->customerData['CSS'] = $customers[0]['CSS'];
$this->customerData['CSP'] = $customers[0]['CSP'];
$this->customerData['CSA'] = $customers[0]['CSA'];
$this->customerData['CST'] = $customers[0]['CST'];
$this->customerData['CSRL'] = $customers[0]['CSRL'];
$this->customerData['TROVE'] = $customers[0]['TROVE'];
$this->customerData['MF'] = $customers[0]['MF'];
$this->customerData['SMA'] = $customers[0]['SMA'];
$this->customerData['MGIN'] = $customers[0]['MGIN'];
$this->customerData['IBD'] = $customers[0]['IBD'];
$this->customerData['SOF'] = $customers[0]['SOF'];
$this->customerData['isCSCSNumber'] = $this->isCSCSNumber($customers[0]['SECID']);
$this->customerData['emailAddress'] = $customers[0]['Email1'];
$this->customerData['phoneNumber'] = $customers[0]['Phone1'];
$this->customerData['accountType'] = $customers[0]['ClientType'];
$this->customerData['Address'] = $customers[0]['Address1'].", ".$customers[0]['State'].", ".$customers[0]['City'].", ".$customers[0]['Country'];
$this->customerData['isStaff'] = (strtoupper($customers[0]['Category']) == "EMPLOYEE") ? true :false;
$isStaff = $this->customerData['isStaff'];
// $accountOfficer = explode(" ",$customers[0]['AccountOfficer']);
$this->customerData['AccountOfficer'] = (is_null($customers[0]['AccountOfficer']) || $customers[0]['AccountOfficer'] == "") ? "Investment Advisor" : $customers[0]['AccountOfficer'];
$this->customerData['accountOfficerEmail'] = (!is_null($customers[0]['accountOfficerEmail']) && !empty($customers[0]['accountOfficerEmail']) && $customers[0]['accountOfficerEmail'] != "") ? $customers[0]['accountOfficerEmail'] : "[email protected]";
$this->customerData['accountOfficerPhoneNo'] = (is_null($customers[0]['accountOfficerPhoneNo']) || $customers[0]['accountOfficerPhoneNo'] == "") ? "+2347100433" : $customers[0]['accountOfficerPhoneNo'];
return $this->retrieveCustomersInvolvement()
->respond();
}
public function findCustomerByNameDetails_($payload)
{
$this->customerData['UserID'] = $payload['CustID'];
$this->customerData['hasTransferPin'] = false;
$this->customerData['isProfileCompleted'] = false;
$customerId = $payload['CustID'];
//fetch additional information
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $customerId, MIDDLEWARE_DB_NAME))['data'];
if (
$customers[0]['BVN'] != '' &&
$customers[0]['BVNFirstName'] != '' &&
$customers[0]['BVNLastName'] != ''
){
$this->customerData['isProfileCompleted'] = true;
}
$this->customerData['Fullname'] = str_replace(","," ",$customers[0]['Name']);
$this->customerData['companyName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['fullName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['firstName'] = str_replace(","," ",trim($customers[0]['FirstName']));
$this->customerData['lastName'] = str_replace(","," ",trim($customers[0]['LastName']));
$this->customerData['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
$this->customerData['BVNFirstName'] = str_replace(",","",$customers[0]['BVNFirstName']);
$this->customerData['BVNLastName'] = str_replace(","," ",trim($customers[0]['BVNLastName']));
$this->customerData['BVNMiddleName'] = str_replace(","," ",trim($customers[0]['BVNMiddleName']));
$this->customerData['userName'] = trim($customers[0]['userName']);
$this->customerData['gender'] = $customers[0]['Gender'];
$this->customerData['SECID'] = $customers[0]['SECID'];
$this->customerData['CustID'] = $customers[0]['CustID'];
$this->customerData['ASSETID'] = $customers[0]['ASSETID'];
$this->customerData['CAMID'] = $customers[0]['CAMID'];
$this->customerData['CAM'] = $customers[0]['CAM'];
$this->customerData['CSS'] = $customers[0]['CSS'];
$this->customerData['CSP'] = $customers[0]['CSP'];
$this->customerData['CSA'] = $customers[0]['CSA'];
$this->customerData['CST'] = $customers[0]['CST'];
$this->customerData['CSRL'] = $customers[0]['CSRL'];
$this->customerData['TROVE'] = $customers[0]['TROVE'];
$this->customerData['MF'] = $customers[0]['MF'];
$this->customerData['SMA'] = $customers[0]['SMA'];
$this->customerData['MGIN'] = $customers[0]['MGIN'];
$this->customerData['IBD'] = $customers[0]['IBD'];
$this->customerData['SOF'] = $customers[0]['SOF'];
$this->customerData['isCSCSNumber'] = $this->isCSCSNumber($customers[0]['SECID']);
$this->customerData['emailAddress'] = $customers[0]['Email1'];
$this->customerData['phoneNumber'] = $customers[0]['Phone1'];
$this->customerData['accountType'] = $customers[0]['ClientType'];
$this->customerData['Address'] = $customers[0]['Address1'].", ".$customers[0]['State'].", ".$customers[0]['City'].", ".$customers[0]['Country'];
$this->customerData['isStaff'] = (strtoupper($customers[0]['Category']) == "EMPLOYEE") ? true :false;
$isStaff = $this->customerData['isStaff'];
// $accountOfficer = explode(" ",$customers[0]['AccountOfficer']);
$this->customerData['AccountOfficer'] = (is_null($customers[0]['AccountOfficer']) || $customers[0]['AccountOfficer'] == "") ? "Investment Advisor" : $customers[0]['AccountOfficer'];
$this->customerData['accountOfficerEmail'] = (!is_null($customers[0]['accountOfficerEmail']) && !empty($customers[0]['accountOfficerEmail']) && $customers[0]['accountOfficerEmail'] != "") ? $customers[0]['accountOfficerEmail'] : "[email protected]";
$this->customerData['accountOfficerPhoneNo'] = (is_null($customers[0]['accountOfficerPhoneNo']) || $customers[0]['accountOfficerPhoneNo'] == "") ? "+2347100433" : $customers[0]['accountOfficerPhoneNo'];
return $this->retrieveCustomersInvolvement()
->respond_1();
}
/* public function updateUsername($customerId, $CustID)
{
//fetch username
$username = formatIWRes(container('IWSRequest')->PGetData2('css_0018', $customerId, MIDDLEWARE_DB_NAME))['data'];
$username_1 = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $CustID, MIDDLEWARE_DB_NAME))['data'];
if(!is_null($username_1[0]['userName']) && !empty($username_1[0]['userName']) && $username_1[0]['userName'] != ""){
return['code' => 400, 'message' => "You already have a friendly username set as " . $username_1[0]['userName']];
}elseif((!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != "") && strtoupper($username[0]['userName']) == strtoupper($username_1[0]['userName'])){
return['code' => 400, 'message' => "Username already taken by you, please choose another username"];
}elseif(!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != ""){
return['code' => 400, 'message' => "Username already taken, please choose another username"];
}elseif(is_null($username[0]['userName']))
{
$res = formatIWRes(container('IWSRequest')->PGetData2('css_0017', "{$CustID}|{$customerId}", MIDDLEWARE_DB_NAME))['data'];
return['code' => 200, 'message' => "Username successfully created"];
}
} */
public function createUsername($customerId, $CustID)
{
//fetch username
$username = formatIWRes(container('IWSRequest')->PGetData2('css_0018', $customerId, MIDDLEWARE_DB_NAME))['data'];
$username_1 = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $CustID, MIDDLEWARE_DB_NAME))['data'];
if(!is_null($username_1[0]['userName']) && !empty($username_1[0]['userName']) && $username_1[0]['userName'] != ""){
return['code' => 400, 'message' => "You already have a friendly username set as " . $username_1[0]['userName']];
}elseif((!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != "") && strtoupper($username[0]['userName']) == strtoupper($username_1[0]['userName'])){
return['code' => 400, 'message' => "Username already taken by you, please choose another username"];
}elseif(!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != ""){
return['code' => 400, 'message' => "Username already taken, please choose another username"];
}elseif(is_null($username) || is_null($username[0]['userName']) || empty($username[0]['userName']) || $username[0]['userName'] == "")
{
$res = formatIWRes(container('IWSRequest')->PGetData2('css_0017', "{$CustID}|{$customerId}", MIDDLEWARE_DB_NAME))['data'];
if($res["StatusID"] == 0)
{
return['code' => 200, 'message' => "Username successfully created"];
}else{
return['code' => 400, 'message' => "Username creation failed. Try again later"];
}
}
}
public function updateUsername($customerId, $CustID)
{
//fetch username
$username = formatIWRes(container('IWSRequest')->PGetData2('css_0018', $customerId, MIDDLEWARE_DB_NAME))['data'];
$username_1 = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $CustID, MIDDLEWARE_DB_NAME))['data'];
// var_dump($username);
/* if(!is_null($username_1[0]['userName']) && !empty($username_1[0]['userName']) && $username_1[0]['userName'] != ""){
return['code' => 400, 'message' => "You already have a friendly username set as " . $username_1[0]['userName']];
}elseif(!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != ""){ */
if((!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != "") && strtoupper($username[0]['userName']) == strtoupper($username_1[0]['userName']))
{
return['code' => 400, 'message' => "Username already taken by you, please choose another username"];
}elseif(!is_null($username[0]['userName']) && !empty($username[0]['userName']) && $username[0]['userName'] != ""){
return['code' => 400, 'message' => "Username already taken, please choose another username"];
}elseif(is_null($username) || is_null($username[0]['userName']) || empty($username[0]['userName']) || $username[0]['userName'] == "")
{
// var_dump($username);
$res = formatIWRes(container('IWSRequest')->PGetData2('css_0017', "{$CustID}|{$customerId}", MIDDLEWARE_DB_NAME))['data'];
// var_dump($res);
if($res["StatusID"] == 0)
{
return['code' => 200, 'message' => "Username successfully updated"];
}else{
return['code' => 400, 'message' => "Username update failed. Try again later"];
}
}
}
private function detectApplicationLockdown()
{
// if (container("adModel")->fixedBannerExists() && (env('ENVIRONMENT') !== 'testing'))
// {
// throw new \Exception(
// LOCKDOWN_MESSAGE,
// 423
// );
// }
return $this;
}
private function loginToMiddleware($customerId, $password)
{
// login to middleware
// if successful update the customerdata
$response = formatIWRes(
container('IWSRequest')->loginToMiddleware($customerId, $password)
) ?? [];
if (!$this->customerData = $response['data'][0] ?? null) {
$log = container('mutualFundModel')->authLog($customerId, null, null, null,null, null, null, null, $this->get_client_ip(), "Infoware Authentication Failed");
// throw new \Exception("Invalid user ID or password", 422);
throw new \Exception($response["StatusMessage"], 422);
}
//fetch additional information
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $customerId, MIDDLEWARE_DB_NAME))['data'];
$this->customerData['Fullname'] = str_replace(","," ",$customers[0]['Name']);
$this->customerData['companyName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['fullName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['firstName'] = str_replace(","," ",trim($customers[0]['FirstName']));
$this->customerData['lastName'] = str_replace(","," ",trim($customers[0]['LastName']));
$this->customerData['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
$this->customerData['BVNFirstName'] = str_replace(",","",$customers[0]['BVNFirstName']);
$this->customerData['BVNLastName'] = str_replace(","," ",trim($customers[0]['BVNLastName']));
$this->customerData['BVNMiddleName'] = str_replace(","," ",trim($customers[0]['BVNMiddleName']));
$this->customerData['userName'] = trim($customers[0]['userName']);
$this->customerData['gender'] = $customers[0]['Gender'];
$this->customerData['SECID'] = $customers[0]['SECID'];
$this->customerData['CustID'] = $CustID = $customers[0]['CustID'];
$this->customerData['ASSETID'] = $ASSETID = $customers[0]['ASSETID'];
$this->customerData['CAMID'] = $CAMID = $customers[0]['CAMID'];
$this->customerData['CAM'] = $customers[0]['CAM'];
$this->customerData['CSS'] = $customers[0]['CSS'];
$this->customerData['CSP'] = $customers[0]['CSP'];
$this->customerData['CSA'] = $customers[0]['CSA'];
$this->customerData['CST'] = $customers[0]['CST'];
$this->customerData['CSRL'] = $customers[0]['CSRL'];
$this->customerData['TROVE'] = $customers[0]['TROVE'];
$this->customerData['MF'] = $customers[0]['MF'];
$this->customerData['SMA'] = $customers[0]['SMA'];
$this->customerData['MGIN'] = $customers[0]['MGIN'];
$this->customerData['IBD'] = $customers[0]['IBD'];
$this->customerData['SOF'] = $customers[0]['SOF'];
$this->customerData['isCSCSNumber'] = $this->isCSCSNumber($customers[0]['SECID']);
$this->customerData['emailAddress'] = $customers[0]['Email1'];
$this->customerData['phoneNumber'] = $customers[0]['Phone1'];
$this->customerData['accountType'] = $customers[0]['ClientType'];
$this->customerData['Address'] = $customers[0]['Address1'].", ".$customers[0]['State'].", ".$customers[0]['City'].", ".$customers[0]['Country'];
$SECID = $this->customerData['SECID'];
$CAMID = $this->customerData['CAMID'];
$ASSETID = $this->customerData['ASSETID'];
//var_dump($customers);
$ID = $id = $this->customerData['UserID'];
$name = str_replace(",","",$this->customerData['Fullname']);
$email = $this->customerData['emailAddress'];
$phone = $this->customerData['phoneNumber'];
$this->customerData['isStaff'] = (strtoupper($customers[0]['Category']) == "EMPLOYEE") ? true :false;
$isStaff = $this->customerData['isStaff'];
$phoneNumber = $this->customerData['phoneNumber'];
$emailAddress = $this->customerData['emailAddress'];
$fullName = str_replace(",","",$this->customerData['Fullname']);
// $accountOfficer = explode(" ",$customers[0]['AccountOfficer']);
$this->customerData['AccountOfficer'] = (is_null($customers[0]['AccountOfficer']) || $customers[0]['AccountOfficer'] == "") ? "Investment Advisor" : $customers[0]['AccountOfficer'];
$this->customerData['accountOfficerEmail'] = (!is_null($customers[0]['accountOfficerEmail']) && !empty($customers[0]['accountOfficerEmail']) && $customers[0]['accountOfficerEmail'] != "") ? $customers[0]['accountOfficerEmail'] : "[email protected]";
$this->customerData['accountOfficerPhoneNo'] = (is_null($customers[0]['accountOfficerPhoneNo']) || $customers[0]['accountOfficerPhoneNo'] == "") ? "+2347100433" : $customers[0]['accountOfficerPhoneNo'];
$this->customerData['accessToken'] = JWTToken::generate(compact('id','ID', 'assetMgmtCustomerId','ASSETID', 'name', 'fullName', 'stockBrokingCustomerId','SECID', 'CAMCustomerId','CAMID','email','emailAddress', 'phone','phoneNumber', 'isStaff'));
// return ['customer' => $this->customerData];
return $this;
}
private function loginToMiddleware_1($customerId, $password)
{
// login to middleware
// if successful update the customerdata
$response = formatIWRes(
container('IWSRequest')->loginToMiddleware($customerId, $password)
) ?? [];
if (!$this->customerData = $response['data'][0] ?? null) {
$log = container('mutualFundModel')->authLog($customerId, null, null, null,null, null, null, null, $this->get_client_ip(), "Infoware Authentication Failed");
// throw new \Exception("Invalid user ID or password", 422);
throw new \Exception($response["StatusMessage"], 422);
}
//fetch additional information
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $customerId, MIDDLEWARE_DB_NAME))['data'];
//var_dump($customers);
$this->customerData['Fullname'] = str_replace(","," ",$customers[0]['Name']);
$this->customerData['companyName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['fullName'] = str_replace(",","",$customers[0]['Name']);
$this->customerData['firstName'] = str_replace(","," ",trim($customers[0]['FirstName']));
$this->customerData['lastName'] = str_replace(","," ",trim($customers[0]['LastName']));
$this->customerData['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
$this->customerData['BVNFirstName'] = str_replace(",","",$customers[0]['BVNFirstName']);
$this->customerData['BVNLastName'] = str_replace(","," ",trim($customers[0]['BVNLastName']));
$this->customerData['BVNMiddleName'] = str_replace(","," ",trim($customers[0]['BVNMiddleName']));
$this->customerData['userName'] = trim($customers[0]['userName']);
$this->customerData['gender'] = $customers[0]['Gender'];
$this->customerData['SECID'] = $customers[0]['SECID'];
$this->customerData['CustID'] = $customers[0]['CustID'];
$this->customerData['ASSETID'] = $customers[0]['ASSETID'];
$this->customerData['CAMID'] = $customers[0]['CAMID'];
$this->customerData['CAM'] = $customers[0]['CAM'];
$this->customerData['CSS'] = $customers[0]['CSS'];
$this->customerData['CSP'] = $customers[0]['CSP'];
$this->customerData['CSA'] = $customers[0]['CSA'];
$this->customerData['CST'] = $customers[0]['CST'];
$this->customerData['CSRL'] = $customers[0]['CSRL'];
$this->customerData['TROVE'] = $customers[0]['TROVE'];
$this->customerData['MF'] = $customers[0]['MF'];
$this->customerData['SMA'] = $customers[0]['SMA'];
$this->customerData['MGIN'] = $customers[0]['MGIN'];
$this->customerData['IBD'] = $customers[0]['IBD'];
$this->customerData['SOF'] = $customers[0]['SOF'];
$this->customerData['isCSCSNumber'] = $this->isCSCSNumber($customers[0]['SECID']);
$this->customerData['emailAddress'] = $customers[0]['Email1'];
$this->customerData['phoneNumber'] = $customers[0]['Phone1'];
$this->customerData['accountType'] = $customers[0]['ClientType'];
$this->customerData['Address'] = $customers[0]['Address1'].", ".$customers[0]['State'].", ".$customers[0]['City'].", ".$customers[0]['Country'];
$SECID = $this->customerData['SECID'];
$CAMID = $this->customerData['CAMID'];
$ASSETID = $this->customerData['ASSETID'];
$ID = $id = $this->customerData['UserID'];
$name = str_replace(",","",$this->customerData['Fullname']);
$email = $this->customerData['emailAddress'];
$phone = $this->customerData['phoneNumber'];
$this->customerData['isStaff'] = (strtoupper($customers[0]['Category']) == "EMPLOYEE") ? true :false;
$isStaff = $this->customerData['isStaff'];
$phoneNumber = $this->customerData['phoneNumber'];
$emailAddress = $this->customerData['emailAddress'];
$fullName = str_replace(",","",$this->customerData['Fullname']);
// $accountOfficer = explode(" ",$customers[0]['AccountOfficer']);
$this->customerData['AccountOfficer'] = (is_null($customers[0]['AccountOfficer']) || $customers[0]['AccountOfficer'] == "") ? "Investment Advisor" : $customers[0]['AccountOfficer'];
$this->customerData['accountOfficerEmail'] = (!is_null($customers[0]['accountOfficerEmail']) && !empty($customers[0]['accountOfficerEmail']) && $customers[0]['accountOfficerEmail'] != "") ? $customers[0]['accountOfficerEmail'] : "[email protected]";
$this->customerData['accountOfficerPhoneNo'] = (is_null($customers[0]['accountOfficerPhoneNo']) || $customers[0]['accountOfficerPhoneNo'] == "") ? "+2347100433" : $customers[0]['accountOfficerPhoneNo'];
$this->customerData['accessToken'] = JWTToken::generate(compact('id','ID', 'assetMgmtCustomerId','ASSETID', 'name', 'fullName', 'stockBrokingCustomerId','SECID', 'CAMCustomerId','CAMID','email','emailAddress', 'phone','phoneNumber', 'isStaff'));
return ['customer' => $this->customerData];
// return $this;
}
private function retrieveCustomersInvolvement()
{
$response = formatIWRes(
container('IWSRequest')->PGetData2('P_00090', $this->customerData['UserID'], MIDDLEWARE_DB_NAME)
);
if ($response['StatusID'] !== NOERROR) {
throw new \Exception($response['StatusMessage'], 422);
}
// we return an empty array here to ensure every new user without
// stockbroking and asset management account can login,
// var_dump("Involvement is ".$response['data']);
// die();
$this->customerData['involvements'] = $response['data'] ?? [];
return $this;
}
private function respond()
{
$ID = $id = $this->customerData['UserID'];
$name = str_replace(",","",$this->customerData['Fullname']);
$email = $this->customerData['emailAddress'];
$phone = $this->customerData['phoneNumber'];
$isStaff = $this->customerData['isStaff'];
$phoneNumber = $this->customerData['phoneNumber'];
$emailAddress = $this->customerData['emailAddress'];
$fullName = str_replace(",","",$this->customerData['Fullname']);
$SECID = $this->customerData['SECID'];
$CAMID = $this->customerData['CAMID'];
$ASSETID = $this->customerData['ASSETID'];
// extract the customers involvements (i.e stockbroking, asset managment or cam) to this scope
extract(parse_involvements($this->customerData['involvements']));
$this->customerData['MFAEnabled'] = container('MFAModel')->userHasMFAEnabled($id);
//log authentication
$log = container('mutualFundModel')->authLog($id, $name, $email, $phone,null, null, null, null, $this->get_client_ip(), "CSS/CAM Authentication Successful");
// var_dump("CAMID is " . $CAMCustomerId);
// var_dump("SECID is " . $stockBrokingCustomerId);
// var_dump("ASSETID is " . $assetMgmtCustomerId);
//var_dump($this->customerData);
// $this->customerData['userIsARestrictedStaff'] = container('IWSRequest')->userIsOnRestrictedList($stockBrokingCustomerId);
return [
'SMA-CAM' => container('SMA_CAMModel')->findAccounts($CAMCustomerId),
'FI-CAM' => container('termInstrument_CAMModel')->findCustomerTermInstruments($CAMCustomerId),
'MF-CAM' => container('mutualFund_CAMModel')->findAccounts($CAMCustomerId),
'STB' => container('stockbrokingModel')->findCSCSAccounts($stockBrokingCustomerId),
'MF' => container('mutualFundModel')->findAccounts($assetMgmtCustomerId),
'bankDetails' => $this->getCustomerBankDetails($id),
'KYCStatus' => $this->checkIfcustomerKYCIsComplete($id,MIDDLEWARE_DB_NAME),
'customer' => $this->customerData,
/* 'T-Bills' => container('TBillModel')->all(), */
'message' => 'Successfully fetched results!',
/* 'Bonds' => formatIWRes(container('IWSRequest')->PGetData('P_00082'))['data'] ?? [], */
'SMA' => container('SMAModel')->findAccounts($assetMgmtCustomerId),
'FI' => container('termInstrumentModel')->findCustomerTermInstruments($assetMgmtCustomerId),
'CA' => container('cashAccountModel')->findCustomerCashAccts($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId),
'TROVE' => container('foreignEquityModel')->findAccounts($stockBrokingCustomerId),
'foreign-equity' => container('foreignEquityModel')->getUserForeignEquityDetails($id),
'MF-CAM' => container('mutualFund_CAMModel')->findAccounts($CAMCustomerId),
'CA' => container('cashAccountModel')->findCustomerCashAccts($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId),
'LIMIT' => container('config')["cashAccount.FI10"],
'accessToken' => JWTToken::generate(compact('id','ID', 'assetMgmtCustomerId','ASSETID', 'name', 'fullName', 'stockBrokingCustomerId','SECID', 'CAMCustomerId','CAMID','email','emailAddress', 'phone','phoneNumber', 'isStaff')),
];
}
private function respond_1()
{
$ID = $id = $this->customerData['UserID'];
$name = str_replace(",","",$this->customerData['Fullname']);
$email = $this->customerData['emailAddress'];
$phone = $this->customerData['phoneNumber'];
$isStaff = $this->customerData['isStaff'];
$phoneNumber = $this->customerData['phoneNumber'];
$emailAddress = $this->customerData['emailAddress'];
$fullName = str_replace(",","",$this->customerData['Fullname']);
$SECID = $this->customerData['SECID'];
$CAMID = $this->customerData['CAMID'];
$ASSETID = $this->customerData['ASSETID'];
// extract the customers involvements (i.e stockbroking, asset managment or cam) to this scope
extract(parse_involvements($this->customerData['involvements']));
$this->customerData['MFAEnabled'] = container('MFAModel')->userHasMFAEnabled($id);
//log authentication
$log = container('mutualFundModel')->authLog($id, $name, $email, $phone,null, null, null, null, $this->get_client_ip(), "CSS/CAM Authentication Successful");
return [
// 'SMA-CAM' => container('SMA_CAMModel')->findAccounts($CAMCustomerId),
// 'FI-CAM' => container('termInstrument_CAMModel')->findCustomerTermInstruments($CAMCustomerId),
'MF-CAM' => container('mutualFund_CAMModel')->findAccounts($CAMCustomerId),
'STB' => container('stockbrokingModel')->findCSCSAccounts($stockBrokingCustomerId),
// 'MF' => container('mutualFundModel')->findAccounts($assetMgmtCustomerId),
'bankDetails' => $this->getCustomerBankDetails($id),
// 'KYCStatus' => $this->checkIfcustomerKYCIsComplete($id,MIDDLEWARE_DB_NAME),
'customer' => $this->customerData,
/* 'T-Bills' => container('TBillModel')->all(), */
'message' => 'Successfully fetched results!',
/* 'Bonds' => formatIWRes(container('IWSRequest')->PGetData('P_00082'))['data'] ?? [], */
// 'SMA' => container('SMAModel')->findAccounts($assetMgmtCustomerId),
// 'FI' => container('termInstrumentModel')->findCustomerTermInstruments($assetMgmtCustomerId),
// 'CA' => container('cashAccountModel')->findCustomerCashAccts($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId),
// 'TROVE' => container('foreignEquityModel')->findAccounts($stockBrokingCustomerId),
// 'foreign-equity' => container('foreignEquityModel')->getUserForeignEquityDetails($id),
'MF-CAM' => container('mutualFund_CAMModel')->findAccounts($CAMCustomerId),
// 'CA' => container('cashAccountModel')->findCustomerCashAccts($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId),
'LIMIT' => container('config')["cashAccount.FI10"],
'accessToken' => JWTToken::generate(compact('id','ID', 'assetMgmtCustomerId','ASSETID', 'name', 'fullName', 'stockBrokingCustomerId','SECID', 'CAMCustomerId','CAMID','email','emailAddress', 'phone','phoneNumber', 'isStaff')),
];
}
//created on the 21st of June by Tayo to return mfInvolvements after creating involvement
public function mfInvolvement($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId)
{
// var_dump ("ASSET ID is ".$assetMgmtCustomerId .", and SEC ID is " . $stockBrokingCustomerId.", and CAM ID is " . $CAMCustomerId);
return ['CA' => container('cashAccountModel')->findCustomerCashAccts($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId)];
}
private function mutualFundRespond()
{
$ID = $id = $this->customerData['UserID'];
$name = str_replace(",","",$this->customerData['Fullname']);
$email = $this->customerData['emailAddress'];
$phone = $this->customerData['phoneNumber'];
$isStaff = $this->customerData['isStaff'];
$phoneNumber = $this->customerData['phoneNumber'];
$emailAddress = $this->customerData['emailAddress'];
$fullName = str_replace(",","",$this->customerData['Fullname']);
$SECID = $this->customerData['SECID'];
$CAMID = $this->customerData['CAMID'];
$ASSETID = $this->customerData['ASSETID'];
// extract the customers involvements (i.e stockbroking, asset managment or cam) to this scope
extract(parse_involvements($this->customerData['involvements']));
//error_log("CAM: " . $CAMCustomerId);
//log authentication
$log = container('mutualFundModel')->authLog($id, $name, $email, $phone,$this->getCustomerBankDetails($id)[0]['BankName'], $this->getCustomerBankDetails($id)[0]['AcctNumber'], $this->getCustomerBankDetails($id)[0]['AccountName'], $this->getCustomerBankDetails($id)[0]['BVN'], $this->get_client_ip(), "MF Authentication Successful");
$this->customerData['MFAEnabled'] = container('MFAModel')->userHasMFAEnabled($id);
return [
'MF-CAM' => container('mutualFund_CAMModel')->findAccounts($CAMCustomerId),
'CA' => container('cashAccountModel')->findCustomerCashAccts($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId),
'LIMIT' => container('config')["cashAccount.FI10"],
'customer' => $this->customerData,
'bankDetails' => $this->getCustomerBankDetails($id),
'KYCStatus' => $this->checkIfcustomerKYCIsComplete($id,MIDDLEWARE_DB_NAME),
'accessToken' => JWTToken::generate(compact('id','ID', 'assetMgmtCustomerId','ASSETID', 'name', 'fullName', 'stockBrokingCustomerId','SECID', 'CAMCustomerId','CAMID','email','emailAddress', 'phone','phoneNumber', 'isStaff')),
'message' => 'Successfully fetched results!'
];
}
public function mfInfo($payload)
{
$CAMCustomerId = $payload["CAMID"];
return ["code" =>200,
'MF-CAM' => container('mutualFund_CAMModel')->findAccounts($CAMCustomerId),
// 'LIMIT' => container('config')["cashAccount.FI10"],
'message' => 'Successfully fetched results!'
];
}
private function mutualFundAdminRespond()
{
$ID = $id = $this->customerData['UserID'];
$name = str_replace(",","",$this->customerData['Fullname']);
$email = $this->customerData['emailAddress'];
$phone = $this->customerData['phoneNumber'];
$isStaff = $this->customerData['isStaff'];
$isAdmin = true;
$phoneNumber = $this->customerData['phoneNumber'];
$emailAddress = $this->customerData['emailAddress'];
$fullName = str_replace(",","",$this->customerData['Fullname']);
$SECID = $this->customerData['SECID'];
$CAMID = $this->customerData['CAMID'];
$ASSETID = $this->customerData['ASSETID'];
// extract the customers involvements (i.e stockbroking, asset managment or cam) to this scope
extract(parse_involvements($this->customerData['involvements']));
//error_log("CAM: " . $CAMCustomerId);
//log authentication
// $log = container('mutualFundModel')->authLog($id, $name, $email, $phone,$this->getCustomerBankDetails($id)[0]['BankName'], $this->getCustomerBankDetails($id)[0]['AcctNumber'], $this->getCustomerBankDetails($id)[0]['AccountName'], $this->getCustomerBankDetails($id)[0]['BVN'], $this->get_client_ip(), ($name != "") ? "MF Admin Authentication Successful" : "MF Admin - User does not exist");
$log = container('mutualFundModel')->authLog($id, $name, $email, $phone,$this->getCustomerBankDetails($id)[0]['BankName'], $this->getCustomerBankDetails($id)[0]['AcctNumber'], $this->getCustomerBankDetails($id)[0]['AccountName'], $this->getCustomerBankDetails($id)[0]['BVN'], $this->get_client_ip(), ($name != "") ? "MF Admin Authentication Successful ({$this->customerData['admin']})" : "MF Admin - User does not exist ({$this->customerData['admin']})");
$this->customerData['MFAEnabled'] = container('MFAModel')->userHasMFAEnabled($id);
return [
'MF-CAM' => container('mutualFund_CAMModel')->findAccounts($CAMCustomerId),
'CA' => container('cashAccountModel')->findCustomerCashAccts($assetMgmtCustomerId, $stockBrokingCustomerId, $CAMCustomerId),
'LIMIT' => container('config')["cashAccount.FI10"],
'customer' => $this->customerData,
'bankDetails' => $this->getCustomerBankDetails($id),
'KYCStatus' => $this->checkIfcustomerKYCIsComplete($id,MIDDLEWARE_DB_NAME),
'accessToken' => JWTToken::generate(compact('id','ID', 'assetMgmtCustomerId','ASSETID', 'name', 'fullName', 'stockBrokingCustomerId','SECID', 'CAMCustomerId','CAMID','email','emailAddress', 'phone','phoneNumber', 'isStaff', 'isAdmin')),
'message' => 'Successfully fetched results!'
];
}
public function getRespectiveBusinessID($userId, $business)
{
$resp ="";
$response = formatIWRes(
container('IWSRequest')->PGetData2('P_00090', $userId, MIDDLEWARE_DB_NAME)
);
if ($response['StatusID'] !== NOERROR) {
throw new \Exception($response['StatusMessage'], 422);
}
// return $response['data'];
$result = json_decode(json_encode($response['data']));
foreach($result as $each){
if($each->Stockbroking == $business){
$resp = $each->Value;
}
}
return $resp;
}
/**
* Reset the customer password
* @param int $id
* @param string $oldPassword
* @param string $newPassword
* @return array
* @author ewomazino.ukah <[email protected]>
*/
public function resetPassword($customerId, $oldPassword, $newPassword)
{
$status = $data = null;
$res = $this
->container
->IWSRequest
->loginToMiddleware($customerId, $oldPassword);
$formattedRes = formatIWRes($res);
if (is_null($formattedRes['data'])) {
throw new \Exception("Incorrect Password! - {$formattedRes['StatusMessage']}", 422);
} else {
//$newPassword = urlencode($newPassword);
//container('IWSRequest')->EBizPWDChg("CustAID={$customerId}&CurrentPWD={$oldPassword}&NewPWD={$newPassword}&PWDChangeRequired=false"); //GET request for old endpoint
container('IWSRequest')->EBizPWDChg($customerId,$oldPassword,$newPassword);
$status = 'Password Changed Successfuly';
$data = formatIWRes($res) ?? [] ;
}
return compact('status', 'data');
}
/* public function forgotPassword($payload)
{
//initiate password reset
$this->chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$this->length = 20;
$resetHash = "";
$charArray = str_split($this->chars);
for ($i = 0; $i < $this->length; $i++) {
$index = array_rand($charArray);
$resetHash .= $charArray[$index];
}
//fetch username
$customer = formatIWRes(container('IWSRequest')->PGetData2('css_0018', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
if(!is_null($customer[0]['userName']) && !empty($customer[0]['userName']) && $customer[0]['userName'] != "" )
{
$payload['CustID'] = $customer[0]['CustID'];
$fullName = str_replace(",","",$customer[0]['Name']);
$emailAddress = $customer[0]['Email1'];
$payload['username'] = $customer[0]['userName'];
$url = getenv('FORGOT_PASSWORD_URL').$resetHash."&CustID=".$payload['CustID'];
}else{
//option is userid
$customer = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
if(!is_null($customer[0]['CustID']) && !empty($customer[0]['CustID']) && $customer[0]['CustID'] != "")
{
$fullName = str_replace(",","",$customer[0]['Name']);
$emailAddress = $customer[0]['Email1'];
$payload['username'] = $customer[0]['userName'];
$url = getenv('FORGOT_PASSWORD_URL').$resetHash."&CustID=".$payload['CustID'];
}else{
return ["code" => 400, "message" => "User not found"];
}
}
//check for existing password reset link
$isLinkValid = $this->forgotPasswordTable()
->where([
["CustID", "=", $payload['CustID'] ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->get();
if( count($isLinkValid) > 0){
$this->forgotPasswordTable()
->where([
["CustID", "=", $payload['CustID'] ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->update([
"used" => 1,
"expired" => 1,
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}
$initiate = $this->forgotPasswordTable()
->insertGetId([
'CustID' => $payload['CustID'],
'companyName' => $payload['companyName'],
'username' => $payload['username'],
'emailAddress' => $emailAddress,
'fullName' => $fullName,
'resetHash' => $resetHash,
]);
//send email
$record = [
"fullName" => $fullName,
"emailAddress" => $emailAddress,
"url" => $url,
"company" => $payload['companyName'],
];
(new Mailer())
->to($emailAddress)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Password Reset")
->usingView('forgot_password', $record)
->send();
return ["code" => 200, "message" => "Password reset successfully initiated and a reset link has been sent to your registered email address."];
} */
public function forgotPassword($payload)
{
//fetch username
$customer = formatIWRes(container('IWSRequest')->PGetData2('css_0018', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
if(!is_null($customer[0]['userName']) && !empty($customer[0]['userName']) && $customer[0]['userName'] != "" )
{
$payload['CustID'] = $customer[0]['CustID'];
$fullName = str_replace(",","",$customer[0]['Name']);
$email = $emailAddress = $customer[0]['Email1'];
$phone = $phoneNumber = $customer[0]['Phone1'];
$payload['username'] = $customer[0]['userName'];
// $url = getenv('FORGOT_PASSWORD_URL').$resetHash."&CustID=".$payload['CustID'];
}else{
//option is CustID
$customer = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
if(!is_null($customer[0]['CustID']) && !empty($customer[0]['CustID']) && $customer[0]['CustID'] != "")
{
$fullName = str_replace(",","",$customer[0]['Name']);
$email = $emailAddress = $customer[0]['Email1'];
$phone = $phoneNumber = $customer[0]['Phone1'];
$payload['username'] = $customer[0]['userName'];
// $url = getenv('FORGOT_PASSWORD_URL').$resetHash."&CustID=".$payload['CustID'];
}else{
return ["code" => 400, "message" => "User not found"];
}
}
//send OTP
$otp = mt_rand(100000, 999999);
$data["username"] = $username = $payload["username"];
$data["CustID"] = $ID = $id = $CustID = $payload["CustID"];
$data["emailAddress"] = $payload["emailAddress"] = $email = $emailAddress;
$data["fullName"] = $name = $payload["fullName"] = $fullName;
$data["phoneNumber"] = $payload["phoneNumber"] = $phone = $phoneNumber;
$biz = "CSP";
$createOTP = $this->createOTPRequest($fullName, $CustID,$emailAddress,$otp,$phoneNumber, $biz, $payload);
// var_dump($CustID);
// var_dump($ID);
// $data["accessToken"] = JWTToken::generate(compact('name', 'fullName', 'username','CustID','id', 'ID', 'email', 'emailAddress', 'phone', 'phoneNumber'));
$data = [];
return ["code" => 200, "message" => $createOTP["message"], "data" => $data];
}
public function forgotPasswordVerify($payload)
{
//validate password reset link
$isLinkValid = $this->forgotPasswordTable()
->where([
["CustID", "=", $payload['CustID'] ],
["resetHash", "=", $payload['resetHash'] ],
["used", "=", 0 ],
["expired", "=", 0 ]
])
->get();
if( count($isLinkValid) == 0){
$data = [
"message" => "Invalid/expired password reset link. Please reinitiate password reset",
"status" => "error",
"code" => 400
];
}elseif(count($isLinkValid) > 0){
$now = Carbon::now()->format('Y-m-d H:i:s');
$linkCreated = Carbon::parse($isLinkValid[0]->createdDate);
if($linkCreated->diffInMinutes($now) > 15){
//set used to true, insert usedDate, and set expired to true
$this->forgotPasswordTable()
->where([
["CustID", "=", $payload['CustID'] ],
["resetHash", "=", $payload['resetHash'] ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->update([
"used" => 1,
"expired" => 1,
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
$data = [
"message" => "Password reset link expired. Please reinitiate password reset",
"status" => "error",
"code" => 400
];
}else{
//set used to true and insert usedDate
/* $this->forgotPasswordTable()
->where([
["CustID", "=", $payload['CustID'] ],
["resetHash", "=", $payload['resetHash'] ],
["used", "=", 0 ],
["expired", "=", 0 ]
])->update([
"used" => 1,
"usedDate" => Carbon::now()->format('Y-m-d H:i:s')
]); */
$data = [
"message" => "Password reset link verified",
"status" => "success",
"code" => 200,
"url" => getenv('CHANGE_PASSWORD_URL').$payload['resetHash']."&CustID=".$payload['CustID'],
];
}
}
return $data;
}
/* public function forgotPasswordChange($payload)
{
//validate resetHash
// $verify = $this->forgotPasswordTable()
// ->where([["CustID", "=", $payload["CustID"]],
// ["resetHash", "=", $payload["resetHash"]],
// ["used", "=", 0 ],
// ["expired", "=", 0 ]
// ])
// ->first();
$verify = $this->forgotPasswordVerify($payload);
if($verify["code"] == 200)
{
// container('IWSRequest')->EBizPWDChg($payload["CustID"],$payload["password"]);
// container('IWSRequest')->EBizResetPWD("CustAID={$payload['CustID']}&NewPWD={$payload["password"]}&PWDChangeRequired=false");
// EBizResetPWD3($customerId,$oldPassword="",$newPassword, $PWDChangeRequired, $DisablePWDChangeAlert)
container('IWSRequest')->EBizResetPWD3($payload['CustID'],"",$payload["password"], false, true);
$update = $this->forgotPasswordTable()
->where([["CustID", "=", $payload["CustID"]],
["resetHash", "=", $payload["resetHash"]],
])
->update([
"used" => 1,
"expired" => 1,
]);
return ["code" => 200, "message" => "Password Successfuly Changed"];
}else{
return ["code" => 400, "message" => "Invalid/expired password reset link. Please reinitiate password reset"];
}
}
*/
public function forgotPasswordChange($payload)
{
$verify = $this->withdrawalRequestOTPTable()
->where([["CustID", "=", $payload["CustID"]],
["otp", "=", $payload["otp"]],
["createdDate", 'like', Carbon::now()->format('Y-m-d') . '%']
])
->first();
$verify = json_decode(json_encode($verify), true);
if(count($verify) > 0)
{
// container('IWSRequest')->EBizPWDChg($payload["CustID"],$payload["password"]);
// container('IWSRequest')->EBizResetPWD("CustAID={$payload['CustID']}&NewPWD={$payload["password"]}&PWDChangeRequired=false");
// EBizResetPWD3($customerId,$oldPassword="",$newPassword, $PWDChangeRequired, $DisablePWDChangeAlert)
container('IWSRequest')->EBizResetPWD3($payload['CustID'],"",$payload["password"], false, true);
return ["code" => 200, "message" => "Password Successfuly Changed"];
}else{
return ["code" => 400, "message" => "Password reset OTP is invalid. Please reinitiate password reset"];
}
}
private function processQuery($payload, $BusinessType)
{
$query = '';
foreach ($this->newAccountFields as $key => $value) {
$postFix = $key + 1 !== count($this->newAccountFields) ? '|' : null;
if ($value === "businessInvolvement") {
$val = $BusinessType;
} else if ($value === "involvementType" && strpos($query, "Asset") === -1) {
$val = '';
} else {
$val = (string) isset($payload[$value]) ? $payload[$value] : ' ';
}
$query .= "{$val}$postFix";
}
return $query;
}
private function handleFileUpload($payload, $parentId, $businessInvolvement)
{
// $fileUploadStatus;
$uploadedFileCount = 0;
if (
isset($payload['files']) &&
is_array($payload['files'])
) {
foreach ($payload['files'] as $key => $uploadedFile) {
error_log("inside the foreach for upload");
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$params = [
"parentID" => $parentId,
"fileName" => "{$this->filesType[$key]}: {$uploadedFile->getClientFilename()}",
"fileType" => $extension,
"file" => $uploadedFile->getStream(),
];
try {
$response = container('IWSRequest')->uploadFile($params, $businessInvolvement);
$uploadedFileCount += 1;
// $fileUploadStatus = formatIWRes($response);
} catch (\Exception $e) {
//var_dump($e->getMessage());
}
}
}
return $uploadedFileCount;
}
private function kycFileUpload($payload, $CustID, $businessInvolvement)
{
//read all image files into an array
$i = 0;
foreach($payload as $image){
//$url = $image['url'].$image['name'];
// $ff = 0;
$directory = dirname(__DIR__, 2) . "/public_view/files/kyc/";
// $contents = file_get_contents($url);
$name = $payload[$i]['CustID']."-".$payload[$i]['imageID'].".".$payload[$i]['extension'];
// $contents = file_get_contents($url);
$file = $directory . $payload[$i]['name'];
// file_put_contents($file, $contents);
// $uploaded_file = new UploadedFile($file, $payload[$i]['name']);
$uploaded_file = new UploadedFile($file, $name);
$payload[$i] += ['file' => $uploaded_file];
$i += 1;
}
// $fileUploadStatus;
$uploadedFileCount = 0;
if (isset($payload) && is_array($payload)) {
foreach ($payload as $uploadedFile) {
error_log("inside the foreach for upload");
$extension = pathinfo($uploadedFile['file']->getClientFilename(), PATHINFO_EXTENSION);
$params = [
"parentID" => $CustID,
"fileName" => pathinfo($uploadedFile['file']->getClientFilename(), PATHINFO_BASENAME ),
"fileType" => $extension,
"file" => $uploadedFile['file']->getStream(),
];
try {
$response = container('IWSRequest')->uploadFile($params, $businessInvolvement);
$uploadedFileCount += 1;
}
catch (\Exception $e) {
// var_dump($e->getMessage());
}
}
}
return $uploadedFileCount;
}
private function kycFileUploaddd($payload, $CustID, $businessInvolvement)
{
//read all image files into an array
$i = 0;
foreach($payload as $image){
$url = $image['url'].$image['name'];
$directory = dirname(__DIR__, 2) . "/public_view/files/kyc/";
$contents = file_get_contents($url);
$name = $payload[$i]['CustID']."-".$payload[$i]['imageID'].".".$payload[$i]['extension'];
$contents = file_get_contents($url);
$file = $directory . $name;
file_put_contents($file, $contents);
$uploaded_file = new UploadedFile($file, $name);
$payload[$i] += ['file' => $uploaded_file];
$i += 1;
}
// $fileUploadStatus;
$uploadedFileCount = 0;
if (isset($payload) && is_array($payload)) {
foreach ($payload as $uploadedFile) {
error_log("inside the foreach for upload");
$extension = pathinfo($uploadedFile['file']->getClientFilename(), PATHINFO_EXTENSION);
// var_dump("extension is " . $extension);
$params = [
"parentID" => $CustID,
"fileName" => pathinfo($uploadedFile['file']->getClientFilename(), PATHINFO_BASENAME ),
"fileType" => $extension,
"file" => $uploadedFile['file']->getStream(),
];
try {
$response = container('IWSRequest')->uploadFile($params, $businessInvolvement);
$uploadedFileCount += 1;
} catch (\GuzzleHttp\Exception\RequestException $e) {
/**
* Here we actually catch the instance of GuzzleHttp\Psr7\Response
* (find it in ./vendor/guzzlehttp/psr7/src/Response.php) with all
* its own and its 'Message' trait's methods. See more explanations below.
*
* So you can have: HTTP status code, message, headers and body.
* Just check the exception object has the response before.
*/
if ($e->hasResponse()) {
$response = $e->getResponse();
// var_dump($response->getStatusCode()); // HTTP status code;
// var_dump($response->getReasonPhrase()); // Response message;
// var_dump((string) $response->getBody()); // Body, normally it is JSON;
// var_dump(json_decode((string) $response->getBody())); // Body as the decoded JSON;
// var_dump($response->getHeaders()); // Headers array;
// var_dump($response->hasHeader('Content-Type')); // Is the header presented?
// var_dump($response->getHeader('Content-Type')[0]); // Concrete header value;
$message1 = $response->getStatusCode();
$message2 = $response->getReasonPhrase();
$message3 = $CustID;
$message4 = (string) $response->getBody();
$message5 = "Upload KYC Image to Infoware";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
}
}
}
}
return $uploadedFileCount;
}
private function handleAccountCreation($businessInvolvement, $query, $payload)
{
$result = [];
if(in_array($businessInvolvement, array_keys($this->businessInvolvement))) {
$response = formatIWRes(
container('IWSRequest')->PGetData2ForCAM("P_00100", $query, $businessInvolvement)
//container('IWSRequest')->PGetData2ForCAM("P_00100", $query, CAM_DB_NAME)
);
$result[$businessInvolvement]['AccountCreationStatus'] = $response;
$parentId = $response["data"][0]['Column1'];
if ($response["StatusID"] === NOERROR) {
$result[$businessInvolvement]["uploadedFileCount"] = $this->handleFileUpload($payload, $parentId, $businessInvolvement);
}
}
return $result ?? [];
}
public function createNewAccount($payload)
{
$response = [];
foreach ($payload['businessInvolvement'] as $businessInvolvement) {
$query = $this->processQuery($payload, $this->businessInvolvement[trim($businessInvolvement)]);
try {
$result = $this->handleAccountCreation($businessInvolvement, $query, $payload);
$response = array_merge($response, $result);
} catch (\Exception $e) {
$result[$businessInvolvement] = [
'error_message' => $e->getMessage(),
];
}
}
try {
$this->newSignupNotification($payload);
} catch (\Exception $e) {
container('logger')->info(($e->getMessage()));
}
return $response;
}
/**
* This method generates birthday report for clients
*
* @param array $payload
* @return void
* @author Dev Team <[email protected]>
*/
public function generateBirthdayReport($payload)
{
$customersHNIAbj = array_filter($payload['customers'], function ($customer) {
return $customer['Category'] === 'HNI Abuja';
});
$customersMassAffAbj = array_filter($payload['customers'], function ($customer) {
return $customer['Category'] === 'Mass Affluent Abuja';
});
$customersMassAfluent = array_filter($payload['customers'], function ($customer) {
return $customer['Category'] === 'Mass Affluent';
});
$customersHNI = array_filter($payload['customers'], function ($customer) {
return $customer['Category'] === 'HNI';
});
//var_dump($customersHNIAbj);
$payload['customers'] = array_values($customersMassAfluent);
(new Mailer())
->to(\getenv('MAIA-EMAIL'))
// ->cc(\getenv('MUTUAL_FUND_MANAGER_MAIL'))
->bcc(\getenv('IT-UNIT-EMAIL'), 'IT Unit')
->bcc(\getenv('DOCC-EMAIL'), 'Deal, Original And Client Coverage')
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Client Birthdays for the week starting ({$payload['startDate']}) to ({$payload['endDate']})")
->usingView('clientBirthday', $payload)
->send();
$payload['customers'] = array_values($customersHNI);
(new Mailer())
->to(\getenv('VC-EMAIL'))
// ->cc(\getenv('MUTUAL_FUND_MANAGER_MAIL'))
->bcc(\getenv('IT-UNIT-EMAIL'), 'IT Unit')
->bcc(\getenv('DOCC-EMAIL'), 'Deal, Original And Client Coverage')
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Client Birthdays for the week starting ({$payload['startDate']}) to ({$payload['endDate']})")
->usingView('clientBirthday', $payload)
->send();
$payload['customers'] = array_values($customersHNIAbj);
(new Mailer())
->to(\getenv('ABUJAIA-EMAIL'))
// ->cc(\getenv('MUTUAL_FUND_MANAGER_MAIL'))
->bcc(\getenv('IT-UNIT-EMAIL'), 'IT Unit')
->bcc(\getenv('DOCC-EMAIL'), 'Deal, Original And Client Coverage')
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Client Birthdays for the week starting ({$payload['startDate']}) to ({$payload['endDate']})")
->usingView('clientBirthday', $payload)
->send();
$payload['customers'] = array_values($customersMassAffAbj);
(new Mailer())
->to(\getenv('ABUJAIA-EMAIL'))
// ->cc(\getenv('MUTUAL_FUND_MANAGER_MAIL'))
->bcc(\getenv('IT-UNIT-EMAIL'), 'IT Unit')
->bcc(\getenv('DOCC-EMAIL'), 'Deal, Original And Client Coverage')
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Client Birthdays for the week starting ({$payload['startDate']}) to ({$payload['endDate']})")
->usingView('clientBirthday', $payload)
->send();
return;
}
/**
* This method initiates a transfer request
*
* @param array $payload
* @return void
* @author Dev Team <[email protected]>
*/
public function transferRequest($payload)
{
$this->newTransferRequestNotification($payload);
if(ENVIRONMENT === 'testing'){
return (new Mailer())
->to(DEFAULT_EMAIL, $payload['fullName'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Transaction Alert: InterCompany Transfer of ₦{$payload['amount']}")
->usingView('transferEmailTemplate', $payload)
->send();
}else{
return (new Mailer())
->to($payload['emailAddress'], $payload['fullName'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Transaction Alert: InterCompany Transfer of ₦{$payload['amount']}")
->usingView('transferEmailTemplate', $payload)
->send();
}
}
/**
* This method initiates a withdraw request
*
* @param array $payload
* @return void
* @author Dev Team <[email protected]>
*/
public function withdrawRequest($payload)
{
$this->newFundsWithdrawRequestNotification($payload);
if(ENVIRONMENT === 'testing'){
return (new Mailer())
->to(DEFAULT_EMAIL, $payload['fullName'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Cash Withdrawal Notification of ₦{$payload['amount']}")
->usingView('withdrawEmailTemplate', $payload)
->send();
}else{
return (new Mailer())
->to($payload['emailAddress'], $payload['fullName'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Cash Withdrawal Notification of ₦{$payload['amount']}")
->usingView('withdrawEmailTemplate', $payload)
->send();
}
}
private function newFundsWithdrawRequestNotification($payload)
{
$message = "Dear Team, <br><br>" .
"Please note that there has been a new funds withdraw request on the client portal. Find below a summary of the client details:<br><br>" .
"Client Name: {$payload['fullName']} <br>" .
"Client ID: {$payload['CustID']} <br>" .
"Cash Account: {$payload['cashAccount']} <br>" .
"Amount: ₦{$payload['amount']}<br>" .
"Bank Name: {$payload['bankName']} <br>" .
"Bank Account Name: {$payload['bankAccountName']} <br>" .
"Bank Account Number: {$payload['bankAccountNumber']} <br>" .
"Phone number: {$payload['phoneNumber']}<br>" .
"Email: {$payload['emailAddress']}<br>" .
"Kindly process the client's request using the bank account information on the system. <br><br>" .
"Warm regards,<br>";
$params = [
"subject" => "Cash Withdrawal Notification of ₦{$payload['amount']}",
"message" => $message,
"email" => getenv("FUND_REQUEST_GROUP"),
];
return formatIWRes(container('IWSRequest')->SendMail($params))['data'];
}
private function newTransferRequestNotification($payload)
{
$message = "Dear Team, <br><br>" .
"Please note that there has been a new inter-company transfer request on the client portal. Find below a summary of the client details:<br><br>" .
"Client Name: {$payload['fullName']} <br>" .
"Client ID: {$payload['CustID']} <br>" .
"Source Cash Account: {$payload['cashAccountSrc']} <br>" .
"Destination Cash Account: {$payload['cashAccountDest']} <br>" .
"Amount: ₦{$payload['amount']}<br>" .
"Note: {$payload['note']}<br>" .
"Phone number: {$payload['phoneNumber']}<br>" .
"Email: {$payload['emailAddress']}<br>" .
"Kindly process the client's request. <br><br>" .
"Warm regards,<br>";
$params = [
"subject" => "Transaction Alert: InterCompany Transfer of ₦{$payload['amount']}",
"message" => $message,
"email" => getenv("FUND_REQUEST_GROUP"),
];
return formatIWRes(container('IWSRequest')->SendMail($params))['data'];
}
private function newSignupNotification($payload)
{
$involvements = '';
foreach ($payload['businessInvolvement'] as $key => $invol) {
$prefix = $key === 1 ? ', ' : '';
$involvements .= $prefix . $this->businessInvolvement[trim($invol)];
}
/* $message = "Dear Team, <br><br>" .
"Please note that there has been a new sign up on the client portal. Find below a summary of the client details:<br><br>" .
"First Name: {$payload['Firstname']} <br>" .
"Last Name: {$payload['Surname']}<br>" .
"Phone number: {$payload['Phone']}<br>" .
"Email: {$payload['EmailAddress']}<br>" .
"Product(s): {$involvements}<br><br>" .
"Kindly verify the client details on Infoware and regularize. <br><br>" .
"Warm regards,<br>";
*/
$message = "Dear Team, <br><br>" .
"Please note that there has been a new sign up for the CSP Fixed Income Fund. Find below a summary of the client details:<br><br>" .
"First Name: {$payload['Firstname']} <br>" .
"Last Name: {$payload['Surname']}<br>" .
"Phone number: {$payload['phoneNumber']}<br>" .
"Email: {$payload['EmailAddress']}<br>" .
"Kindly verify the client details on Infoware CAM and regularize. <br><br>" .
"Warm regards,<br>";
$params = [
"subject" => "New Sign Up Notification",
"message" => $message,
];
return formatIWRes(container('IWSRequest')->SendMail($params))['data'];
}
/*
* @return object
* @author [email protected]
*/
/* public function createNubanAccount($data)
{
$res = container('PaystackRequest')->createNubanAccount($data);
return $res;
}*/
// New Signup flow
/*
* @return object
* @author [email protected]
*/
/* public function validateBVN($phone, $bvn)
{
$res = container('PaystackRequest')->validateBVN($phone,$bvn);
return $res;
} */
/**
* create a new customer DB-middleware
*/
public function createNewCustomerRecord($payload)
{
$result = formatIWRes(container('IWSRequest')->startCreateCustomerAccount($payload, MIDDLEWARE_DB_NAME));
$decoded_data = json_decode(json_encode($result));
if($decoded_data->OutValue == null || $decoded_data->OutValue=="" || $decoded_data->StatusID > 0) {
return [
// 'message' => "Individual account opening cannot be completed at the moment",
'message' => $decoded_data->StatusMessage,
'code' => 400
];
}
$payload['CustAID'] = $decoded_data->OutValue;
$payload['CustID'] = $decoded_data->OutValue;
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $decoded_data->OutValue, $payload['firstName']. " " . $payload['lastName']. " " . $payload['companyName'], "Status ID: " . $decoded_data->StatusID . ", Out Value: " . $decoded_data->OutValue, "Account created on Middleware with ID " .$decoded_data->OutValue . " and Status Message is " .$decoded_data->StatusMessage, "New Individual Account Creation in Middleware");
if($payload["check-dc"] === false)
{
$updateResult = formatIWRes(container('IWSRequest')->completeCreateCustomerAccount($payload, MIDDLEWARE_DB_NAME, $payload['CustAID']));
$decoded_data = json_decode(json_encode($updateResult));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "Status ID: " . $decoded_data->StatusID . ", Out Value: " . $decoded_data->OutValue, "Custom Attributes updated for CustAID " .$payload['CustAID'] . " and Status Message is " .$decoded_data->StatusMessage, "Individual Custom Attributes Update in Middleware");
$this->handleFileUpload($payload, $payload['CustID'], MIDDLEWARE_DB_NAME);
}
// var_dump("Business Involvement is: " .$payload["businessInvolvement"]);
if(strtoupper($payload["businessInvolvement"]) == strtoupper(STOCKBROKING_DB_NAME) ||strtoupper($payload["businessInvolvement"]) == strtoupper(CAM_DB_NAME) ||strtoupper($payload["businessInvolvement"]) == strtoupper(ASSETMGMT_DB_NAME))
{
$bizCode = $this->createAccountOnVariousBusinesssUnits( $payload['CustID'], $payload );
}
//update buziness code to middleware
$CSS = (isset($bizCode['SECID']) && $bizCode['SECID'] != 0)? 1 : 0;
$CAM = (isset($bizCode['CAMID']) && $bizCode['CAMID'] != 0)? 1 : 0;
$CSP = (isset($bizCode['ASSETID']) && $bizCode['ASSETID'] != 0)? 1 : 0;
$CST = (isset($payload['CST']) && $payload['CST'] == 1)? 1 : 0;
$CSA = (isset($payload['CSA']) && $payload['CSA'] == 1)? 1 : 0;
$CSRL = (isset($payload['CSRL']) && $payload['CSRL'] == 1)? 1 : 0;
$TROVE = (isset($payload['TROVE']) && $payload['TROVE'] == 1)? 1 : 0;
$MF = (isset($payload['MF']) && $payload['MF'] == 1)? 1 : 0;
$SMA = (isset($payload['SMA']) && $payload['SMA'] == 1)? 1 : 0;
$SOF = (isset($payload['SOF']) && $payload['SOF'] == 1)? 1 : 0;
$updateBizCode = formatIWRes(container('IWSRequest')->updateBusinessCodeToMiddleware($payload['CustID'], $CSS, $CAM, $CSP, $CST, $CSA, $CSRL, $TROVE, $MF, $SMA, $SOF));
//since CSS_0019 is acting up
if(strtoupper($payload['accountOpeningProduct']) == "CST" )
{
$payload['BIZ'] = "CST";
}elseif(strtoupper($payload['accountOpeningProduct']) == "STK" )
{
$payload['BIZ'] = "CSS";
}elseif(strtoupper($payload['accountOpeningProduct']) == "TROVE" )
{
$payload['BIZ'] = "TROVE";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CAM" )
{
$payload['BIZ'] = "CAM1";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CSA" )
{
$payload['BIZ'] = "CSA";
}elseif(strtoupper($payload['accountOpeningProduct']) == "MF" )
{
$payload['BIZ'] = "MF";
}elseif(strtoupper($payload['accountOpeningProduct']) == "SMA" )
{
$payload['BIZ'] = "SMA";
}elseif(strtoupper($payload['accountOpeningProduct']) == "REGISTRAR" )
{
$payload['BIZ'] = "CSRL";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CSP" )
{
$payload['BIZ'] = "CSP";
}
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], $payload['BIZ']));
if(strtoupper($payload['BIZ']) == "TROVE")
{
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], "CSS"));
}
//create fullName
$payload["fullName"] = trim(trim($payload["lastName"]) . " ". trim($payload["firstName"]) . " ". trim($payload["otherNames"]));
//create initial password
if($payload['check-dc'] === false)
{
$this->chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$this->length = 6;
$password = "";
$charArray = str_split($this->chars);
for ($i = 0; $i < $this->length; $i++) {
$index = array_rand($charArray);
$password .= $charArray[$index];
}
}else{
$password = generateSecureOTP();
}
//store initial password for user
// container('IWSRequest')->EBizResetPWD("CustAID={$payload['CustID']}&NewPWD={$password}&PWDChangeRequired=true");
// EBizResetPWD3($customerId,$oldPassword="",$newPassword, $PWDChangeRequired, $DisablePWDChangeAlert)
container('IWSRequest')->EBizResetPWD3($payload['CustID'],"",$password, true, true);
//send welcome email notificaiton
if(strtoupper($payload['accountOpeningProduct']) == "REGISTRAR" )
{
$template = "csrl_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "STK" ){
$template = "css_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CAM" && $payload["check-dc"] === false){
$template = "cam_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "SMA" ){
$template = "cam_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "MF" ){
$template = "mf_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "TROVE" ){
$template = "trove_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CST" ){
$template = "cst_welcome_email_template";
}else
{
$template = "cam_checkdc_welcome_email_template";
}
if($payload["product"] === "CARDINALSTONE FIXED INCOME ALPHA FUND" || $payload["product"] === "CARDINALSTONE FIXED INCOME BETA FUND"){
$payload["product"] = "MUTUAL FUND";
}
if($template === 'cam_checkdc_welcome_email_template')
{
$record = [
"fullName" => $payload["fullName"],
"product" => $payload["product"],
"username" => $payload["username"],
"password" => $password,
];
}else{
$record = [
"fullName" => $payload["fullName"],
"product" => $payload["product"],
"CustID" => $payload["CustID"],
"password" => $password,
];
}
if($payload['partner'] === 1){
return [
"message" => "Individual account created successfully",
"CustID" => $payload['CustID'],
"BIZID" => $bizCode['BIZID'],
"password" => $password,
"code" => 200
];
}
(new Mailer())
->to($payload["emailAddress"])
// ->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Welcome to CardinalStone")
->usingView($template, $record)
->send();
return [
"message" => "Individual account created successfully",
"CustID" => $payload['CustID'],
"BIZID" => $bizCode['BIZID'],
"password" => $record['password'],
"code" => 200
];
}
/**
* create a new corporate DB-middleware
*/
public function createNewCorporateRecord($payload)
{
$result = formatIWRes($this->container->IWSRequest->startCreateCustomerAccount($payload, MIDDLEWARE_DB_NAME));
$decoded_data = json_decode(json_encode($result));
if($decoded_data->OutValue == null || $decoded_data->OutValue == "" || $decoded_data->StatusID > 0) { //$decoded_data->StatusID > 0
return [
// 'message' => "Coporate account opening cannot be completed this time",
'message' => $decoded_data->StatusMessage,
'code' => 400,
];
}
$payload['CustID'] = $decoded_data->OutValue;
$payload['CustAID'] = $decoded_data->OutValue;
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $decoded_data->OutValue, $payload['firstName']. " " . $payload['lastName']. " " . $payload['companyName'], "Status ID: " .$decoded_data->StatusID . ", Out Value: " . $decoded_data->OutValue, "Account created on Middleware with ID " . $decoded_data->OutValue . ", and Status Message is " . $decoded_data->StatusMessage, "New Corporate Account Creation in Middleware");
$updateResult = formatIWRes($this->container->IWSRequest->completeCreateCustomerAccount($payload, MIDDLEWARE_DB_NAME, $payload['CustAID']));
$decoded_data = json_decode(json_encode($updateResult));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustAID'], $payload['firstName']. " " . $payload['lastName']. " " . $payload['companyName'], "Status ID: " .$decoded_data->StatusID . ", Out Value: " . $decoded_data->OutValue, "Custom Attributes updated for CustAID " .$payload['CustAID'] . " and Status Message is " .$decoded_data->StatusMessage, "Corporate Custom Attributes Update in Middleware");
// $uploadData = [
// "identityDocument"=> $payload['identityDocument'],
// "certificateOfIncoporation"=> $payload['certificateOfIncoporation'],
// "passport"=> $payload['passport'],
// "CACDocuments"=> $payload['CACDocuments'],
// "memorandomAndArticleOfIncorporation"=> $payload['memorandomAndArticleOfIncorporation'],
// "signature"=> $payload['signature']
// ];
// $this->uploadVariousFiles( $uploadData, $payload['CustAID']);
$this->handleFileUpload($payload, $payload['CustAID'], MIDDLEWARE_DB_NAME);
// if(strtoupper($payload["businessInvolvement"]) == strtoupper(STOCKBROKING_DB_NAME) ||strtoupper($payload["businessInvolvement"]) == strtoupper(CAM_DB_NAME) ||strtoupper($payload["businessInvolvement"]) == strtoupper(ASSETMGMT_DB_NAME))
// {
// $bizCode = $this->createAccountOnVariousBusinesssUnits( $payload['CustAID'], $payload );
// }
if(strtoupper($payload["businessInvolvement"]) == strtoupper(STOCKBROKING_DB_NAME) ||strtoupper($payload["businessInvolvement"]) == strtoupper(CAM_DB_NAME) ||strtoupper($payload["businessInvolvement"]) == strtoupper(ASSETMGMT_DB_NAME))
{
$bizCode = $this->createAccountOnVariousBusinesssUnits( $payload['CustID'], $payload );
// $bizCode = $this->createAccountOnVariousBusinesssUnits( $payload['CustAID'], $payload );
}
//update buziness code to middleware
$CSS = (isset($bizCode['SECID']) && $bizCode['SECID'] != 0)? 1 : 0;
$CAM = (isset($bizCode['CAMID']) && $bizCode['CAMID'] != 0)? 1 : 0;
$CSP = (isset($bizCode['ASSETID']) && $bizCode['ASSETID'] != 0)? 1 : 0;
$CST = (isset($payload['CST']) && $payload['CST'] == 1)? 1 : 0;
$CSA = (isset($payload['CSA']) && $payload['CSA'] == 1)? 1 : 0;
$CSRL = (isset($payload['CSRL']) && $payload['CSRL'] == 1)? 1 : 0;
$TROVE = (isset($payload['TROVE']) && $payload['TROVE'] == 1)? 1 : 0;
$MF = (isset($payload['MF']) && $payload['MF'] == 1)? 1 : 0;
$SMA = (isset($payload['SMA']) && $payload['SMA'] == 1)? 1 : 0;
$SOF = (isset($payload['SOF']) && $payload['SOF'] == 1)? 1 : 0;
$updateBizCode = formatIWRes(container('IWSRequest')->updateBusinessCodeToMiddleware($payload['CustAID'], $CSS, $CAM, $CSP, $CST, $CSA, $CSRL, $TROVE, $MF, $SMA, $SOF));
//since CSS_0019 is acting up
if(strtoupper($payload['accountOpeningProduct']) == "CST" )
{
$payload['BIZ'] = "CST";
}elseif(strtoupper($payload['accountOpeningProduct']) == "STK" )
{
$payload['BIZ'] = "CSS";
}elseif(strtoupper($payload['accountOpeningProduct']) == "TROVE" )
{
$payload['BIZ'] = "TROVE";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CAM" )
{
$payload['BIZ'] = "CAM1";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CSA" )
{
$payload['BIZ'] = "CSA";
}elseif(strtoupper($payload['accountOpeningProduct']) == "MF" )
{
$payload['BIZ'] = "MF";
}elseif(strtoupper($payload['accountOpeningProduct']) == "SMA" )
{
$payload['BIZ'] = "SMA";
}elseif(strtoupper($payload['accountOpeningProduct']) == "REGISTRAR" )
{
$payload['BIZ'] = "CSRL";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CSP" )
{
$payload['BIZ'] = "CSP";
}
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], $payload['BIZ']));
if(strtoupper($payload['BIZ']) == "TROVE")
{
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], "CSS"));
}
//create fullName
$payload["fullName"] = trim($payload["companyName"]);
//create initial password
$this->chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$this->length = 6;
$password = "";
$charArray = str_split($this->chars);
for ($i = 0; $i < $this->length; $i++) {
$index = array_rand($charArray);
$password .= $charArray[$index];
}
//store initial password for user
// container('IWSRequest')->EBizResetPWD("CustAID={$payload['CustID']}&NewPWD={$password}&PWDChangeRequired=true");
// EBizResetPWD3($customerId,$oldPassword="",$newPassword, $PWDChangeRequired, $DisablePWDChangeAlert)
container('IWSRequest')->EBizResetPWD3($payload['CustID'],"",$password, true, true);
//send welcome email notificaiton
if(strtoupper($payload['accountOpeningProduct']) == "REGISTRAR" )
{
$template = "csrl_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "STK" ){
$template = "css_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CAM" ){
$template = "cam_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "SMA" ){
$template = "cam_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "MF" ){
$template = "mf_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "TROVE" ){
$template = "trove_welcome_email_template";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CST" ){
$template = "cst_welcome_email_template";
}else{
$template ="cst_welcome_email_template";
}
$record = [
"fullName" => $payload["fullName"],
"product" => $payload["product"],
"CustID" => $payload["CustID"],
"password" => $password,
];
if($payload['partner'] === 1){
return [
"message" => "Corporate account created successfully",
"CustID" => $payload['CustID'],
"BIZID" => $bizCode['BIZID'],
"password" => $password,
"code" => 200
];
}
(new Mailer())
->to($payload["emailAddress"])
// ->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Welcome to CardinalStone")
->usingView($template, $record)
->send();
return [
"message" => "Corporate account created successfully",
"CustID" => $payload['CustID'],
"password" => $record['password'],
"BIZID" => $bizCode['BIZID'],
"code" => 200
];
}
/**
* prepare update existing client records on middleware for additional business involvement
*/
public function createAddtionalAccount($payload)
{
$payload['CustAID'] = $payload['CustID'];
$middleware_data = formatIWRes(container('IWSRequest')->getUserDetailsFromMiddleware(MIDDLEWARE_DB_NAME, $payload['CustID']));
$payload["ASSETID"] = $middleware_data['data'][0]["ASSETID"];
$payload["SECID"] = $middleware_data['data'][0]["SECID"];
$payload["CAMID"] = $middleware_data['data'][0]["CAMID"];
$payload["CSS"] = $middleware_data['data'][0]["CSS"];
$payload["CAM"] = $middleware_data['data'][0]["CAM"];
$payload["CSP"] = $middleware_data['data'][0]["CSP"];
$payload["CSA"] = $middleware_data['data'][0]["CSA"];
$payload["CST"] = $middleware_data['data'][0]["CST"];
$payload["CSRL"] = $middleware_data['data'][0]["CSRL"];
$payload["TROVE"] = $middleware_data['data'][0]["TROVE"];
$payload["MF"] = $middleware_data['data'][0]["MF"];
$payload["SMA"] = $middleware_data['data'][0]["SMA"];
$payload["bankAcctName"] = $middleware_data['data'][0]["Bank_Acct_Name"];
$payload["bankAcctNumber"] = $middleware_data['data'][0]["Bank_Acct_No"];
$payload["bankName"] = $middleware_data['data'][0]["Bank_Name"];
$payload["bankCode"] = $middleware_data['data'][0]["bankCode"];
$payload["BVNNumber"] = $middleware_data['data'][0]['BVN'];
$payload['companyName'] = str_replace(",","",$middleware_data[0]['Name']);
$payload['fullName'] = str_replace(",","",$middleware_data[0]['Name']);
if(strtoupper($payload['businessInvolvement']) == strtoupper(ASSETMGMT_DB_NAME)){
$payload['BIZID'] = $payload['ASSETID'];
// $payload['CSP'] = 1;
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(STOCKBROKING_DB_NAME)){
$payload['BIZID'] = $payload['SECID'];
// $payload['CSS'] = 1;
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(CAM_DB_NAME)){
$payload['BIZID'] = $payload['CAMID'];
// $payload['CAM'] = 1;
}
//if user doesn't exist in the desired business, create user in desired business
if(is_null($payload['BIZID']) || empty($payload['BIZID']) || $payload['BIZID'] == "")
{
$bizCode = $this->createAccountOnAdditionalBusinesssUnits( $payload['CustAID'], $payload );
// var_dump($bizCode);
//update buziness code to middleware
if($bizCode["code"] == 200)
{
if(strtoupper($payload['businessInvolvement']) == strtoupper(STOCKBROKING_DB_NAME))
{
$payload["CSS"] = 1;
$payload["SECID"] = (!is_null($bizCode["SECID"])) ? $bizCode["SECID"] : $payload["SECID"];
$payload["BIZID"] = (!is_null($bizCode["SECID"])) ? $bizCode["SECID"] : $payload["SECID"];
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(CAM_DB_NAME))
{
$payload["CAM"] = 1;
$payload["CAMID"] = (!is_null($bizCode["CAMID"])) ? $bizCode["CAMID"] : $payload["CAMID"];
$payload["BIZID"] = (!is_null($bizCode["CAMID"])) ? $bizCode["CAMID"] : $payload["CAMID"];
}
if(strtoupper($payload['involvementType']) == "TROVE")
{
$payload["CSS"] = 1;
$payload["SECID"] = (!is_null($bizCode["SECID"])) ? $bizCode["SECID"] : $payload["SECID"];
$payload["BIZID"] = (!is_null($bizCode["SECID"])) ? $bizCode["SECID"] : $payload["SECID"];
$payload["TROVE"] = 1;
}
$updateBizCode = formatIWRes(container('IWSRequest')->updateBusinessCodeToMiddleware($payload['CustID'], $payload['CSS'], $payload['CAM'], $payload['CSP'], $payload['CST'], $payload['CSA'], $payload['CSRL'], $payload['TROVE'], $payload['MF'], $payload['SMA'], $payload['SOF']));
//since CSS_0019 is acting up
if(strtoupper($payload['accountOpeningProduct']) == "CST" )
{
$payload['BIZ'] = "CST";
}elseif(strtoupper($payload['accountOpeningProduct']) == "STK" )
{
$payload['BIZ'] = "CSS";
}elseif(strtoupper($payload['accountOpeningProduct']) == "TROVE" )
{
$payload['BIZ'] = "TROVE";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CAM" )
{
$payload['BIZ'] = "CAM1";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CSA" )
{
$payload['BIZ'] = "CSA";
}elseif(strtoupper($payload['accountOpeningProduct']) == "MF" )
{
$payload['BIZ'] = "MF";
}elseif(strtoupper($payload['accountOpeningProduct']) == "SMA" )
{
$payload['BIZ'] = "SMA";
}elseif(strtoupper($payload['accountOpeningProduct']) == "REGISTRAR" )
{
$payload['BIZ'] = "CSRL";
}elseif(strtoupper($payload['accountOpeningProduct']) == "CSP" )
{
$payload['BIZ'] = "CSP";
}
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], $payload['BIZ']));
if(strtoupper($payload['BIZ']) == "TROVE")
{
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], "CSS"));
}
$bizUpdate = " CSS = {$payload['CSS']}, CAM = {$payload['CAM']}, CSP = {$payload['CSP']}, CST = {$payload['CST']}, CSA = {$payload['CSA']}, CSRL = {$payload['CSRL']}, TROVE = {$payload['TROVE']}, MF = {$payload['MF']}, SMA = {$payload['SMA']}";
$updateResult = formatIWRes(container('IWSRequest')->completeCreateCustomerAccount($payload, MIDDLEWARE_DB_NAME, $payload['CustAID']));
$decoded_data = json_decode(json_encode($updateResult));
// $this->handleFileUpload($payload, $payload['CustAID'], MIDDLEWARE_DB_NAME);
// var_dump($updateResult);
if($updateResult['StatusID'] == 0)
{
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustAID'], $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "Status ID: " . $decoded_data->StatusID . ", Out Value: " . $decoded_data->OutValue . $bizUpdate, "Custom Attributes updated for CustAID " .$payload['CustAID'] . " and Status Message is " .$decoded_data->StatusMessage, "Middleware Update for Additional Business Involvement");
$this->handleFileUpload($payload, $payload['CustAID'], MIDDLEWARE_DB_NAME);
$createInvolvement = $this->createInvolvement($payload);
// var_dump($createInvolvement);
if($createInvolvement["code"] == 200)
{
return (["code" => 200, "message" => "New Additional Business and Product Involvements successfully created", "BIZID" => $payload['BIZID']]);
}else{
return (["code" => 400, "message" => "New Additional Business Involvement successfully Created, but Prouduct Involvement Failed"]);
}
}else{
return (["code" => 400, "message" => "New Additional Business Involvement Creation Failed"]);
}
}else{
return (["code" => 400, "message" => "New Additional Business Involvement Creation Failed"]);
}
}else{
$createInvolvement = $this->createInvolvement($payload);
// var_dump($createInvolvement);
if($createInvolvement["code"] == 200)
{
return (["code" => 200, "message" => "No Additional Business Involvement Required, but Product Involvement successfully created", "BIZID" => $payload['BIZID']]);
}else{
return (["code" => 400, "message" => "No Additional Business Involvement Required, but Product Involvement Creation Failed"]);
}
}
}
/**
* prepare record to create a new customer DB-middleware
*/
public function newAccount($payload)
{
if(strtoupper($payload['accountType']) == "IND"){
//individual signup
isset($payload["Title"]) ? $payload["Title"] : "";
isset($payload["product"]) ? $payload["product"] : "";
isset($payload["BIZ"]) ? $payload["BIZ"] : "";
isset($payload["firstName"]) ? $payload["firstName"] : "";
isset($payload["lastName"]) ? $payload["lastName"] : "";
isset($payload["otherNames"]) ? $payload["otherNames"] : "";
isset($payload["gender"]) ? $payload["gender"] : "1";
isset($payload["dateOfBirth"]) ? $payload["dateOfBirth"] : "";
isset($payload["maidenName"]) ? $payload["maidenName"] : "";
isset($payload["address"]) ? $payload["address"] : "";
isset($payload["swiftCode"]) ? $payload["swiftCode"] : "";
isset($payload["city"]) ? $payload["city"] : "";
isset($payload["country"]) ? $payload["country"] : "";
isset($payload["residency"]) ? $payload["residency"] : "";
isset($payload["state"]) ? $payload["state"] : "";
isset($payload["LGA"]) ? $payload["LGA"] : "";
isset($payload["emailAddress"]) ? $payload["emailAddress"] : "";
isset($payload["phoneNumber"]) ? $payload["phoneNumber"] : "";
isset($payload["politicallyExposed"]) ? $payload["politicallyExposed"] : "";
isset($payload["employmentType"]) ? $payload["employmentType"] : "";
isset($payload["occupation"]) ? $payload["occupation"] : "";
isset($payload["bankAcctName"]) ? $payload["bankAcctName"] : "";
isset($payload["bankAcctNumber"]) ? $payload["bankAcctNumber"] : "";
isset($payload["bankName"]) ? $payload["bankName"] : "";
isset($payload["bankCode"]) ? $payload["bankCode"] : "";
isset($payload["bankAcctName2"]) ? $payload["bankAcctName2"] : "";
isset($payload["bankName2"]) ? $payload["bankName2"] : "";
isset($payload["bankAcctName2"]) ? $payload["bankAcctName2"] : "";
isset($payload["bankAcctNumber2"]) ? $payload["bankAcctNumber2"] : "";
isset($payload["bankCode2"]) ? $payload["bankCode2"] : "";
isset($payload["referrer"]) ? $payload["referrer"] : "";
isset($payload["referralSource"]) ? $payload["referralSource"] : "";
isset($payload["BVNNumber"]) ? $payload["BVNNumber"] : "";
isset($payload["BVNFirstName"]) ? $payload["BVNFirstName"] : "";
isset($payload["BVNLastName"]) ? $payload["BVNLastName"] : "";
isset($payload["BVNMiddleName"]) ? $payload["BVNMiddleName"] : "";
isset($payload["beneficiaryAcctNo"]) ? $payload["beneficiaryAcctNo"] : "";
isset($payload["beneficiaryBankName"]) ? $payload["beneficiaryBankName"] : "";
isset($payload["beneficiaryBankAddress"]) ? $payload["beneficiaryBankAddress"] : "";
isset($payload["correspondentName"]) ? $payload["correspondentName"] : "";
isset($payload["correspondentAcctNo"]) ? $payload["correspondentAcctNo"] : "";
isset($payload["companyName"]) ? $payload["companyName"] : "";
isset($payload["nextOfKin"]) ? $payload["nextOfKin"] : "";
isset($payload["nextOfKinPhone"]) ? $payload["nextOfKinPhone"] : "";
isset($payload["nextOfKinEmail"]) ? $payload["nextOfKinEmail"] : "";
isset($payload["nextOfKinAddress"]) ? $payload["nextOfKinAddress"] : "";
isset($payload["nextOfKinGender"]) ? $payload["nextOfKinGender"] : "";
isset($payload["nextOfKinDOB"]) ? $payload["nextOfKinDOB"] : "";
isset($payload["nextOfKinRelationship"]) ? $payload["nextOfKinRelationship"] : "";
isset($payload["identityType"]) ? $payload["identityType"] : "";
isset($payload["identityExpiryDate"]) ? $payload["identityExpiryDate"] : "";
isset($payload["identityNumber"]) ? $payload["identityNumber"] : "";
isset($payload["employerName"]) ? $payload["employerName"] : "";
isset($payload["employerNo"]) ? $payload["employerNo"] : "";
isset($payload["employerAddress"]) ? $payload["employerAddress"] : "";
isset($payload["sortCode"]) ? $payload["sortCode"] : "";
isset($payload["previousCHN"]) ? $payload["previousCHN"] : "";
isset($payload["businessInvolvement"]) ? $payload["businessInvolvement"] : null;
isset($payload["involvementType"]) ? $payload["involvementType"] : null;
isset($payload["agreementCheck"]) ? $payload["agreementCheck"] : "true";
isset($payload["identityDocument"]) ? $payload["identityDocument"] : "true";
isset($payload["authorisedSignatureName"]) ? $payload["authorisedSignatureName"] : "";
//isset($payload["gender"]) ? $payload["gender"] : "1";
//$payload["state"] =$payload["stateOfOrigin"] ; //to be removed by Tayo after Jasmine account opening
$result = $this->createNewCustomerRecord($payload);
}elseif(strtoupper($payload['accountType']) == "CORP"){
//corporate signup
isset($payload["Title"]) ? $payload["Title"] : "";
isset($payload["product"]) ? $payload["product"] : "";
isset($payload["BIZ"]) ? $payload["BIZ"] : "";
isset($payload["firstName"]) ? $payload["firstName"] : "";
isset($payload["lastName"]) ? $payload["lastName"] : "";
isset($payload["otherNames"]) ? $payload["otherNames"] : "";
isset($payload["city"]) ? $payload["city"] : "";
isset($payload["country"]) ? $payload["country"] : "";
isset($payload["maidenName"]) ? $payload["maidenName"] : "";
isset($payload["dateOfBirth"]) ? $payload["dateOfBirth"] : "";
isset($payload["gender"]) ? $payload["gender"] : "1";
isset($payload["address"]) ? $payload["address"] : "";
isset($payload["state"]) ? $payload["state"] : "";
isset($payload["emailAddress"]) ? $payload["emailAddress"] : "";
isset($payload["phoneNumber"]) ? $payload["phoneNumber"] : "";
isset($payload["politicallyExposed"]) ? $payload["politicallyExposed"] : "";
isset($payload["companyName"]) ? $payload["companyName"] : "";
isset($payload["employmentType"]) ? $payload["employmentType"] : "";
isset($payload["occupation"]) ? $payload["occupation"] : "";
isset($payload["bankAcctName"]) ? $payload["bankAcctName"] : "";
isset($payload["bankAcctNumber"]) ? $payload["bankAcctNumber"] : "";
isset($payload["bankName"]) ? $payload["bankName"] : "";
isset($payload["bankCode"]) ? $payload["bankCode"] : "";
isset($payload["referrer"]) ? $payload["referrer"] : "";
isset($payload["referralSource"]) ? $payload["referralSource"] : "";
isset($payload["BVNNumber"]) ? $payload["BVNNumber"] : "";
isset($payload["BVNFirstName"]) ? $payload["BVNFirstName"] : "";
isset($payload["BVNLastName"]) ? $payload["BVNLastName"] : "";
isset($payload["BVNMiddleName"]) ? $payload["BVNMiddleName"] : "";
isset($payload["beneficiaryName"]) ? $payload["beneficiaryName"] : "";
isset($payload["beneficiaryAcctNo"]) ? $payload["beneficiaryAcctNo"] : "";
isset($payload["beneficiaryBankName"]) ? $payload["beneficiaryBankName"] : "";
isset($payload["beneficiaryBankAddress"]) ? $payload["beneficiaryBankAddress"] : "";
isset($payload["correspondentName"]) ? $payload["correspondentName"] : "";
isset($payload["correspondentAcctNo"]) ? $payload["correspondentAcctNo"] : "";
isset($payload["nextOfKin"]) ? $payload["nextOfKin"] : "";
isset($payload["nextOfKinPhone"]) ? $payload["nextOfKinPhone"] : "";
isset($payload["nextOfKinEmail"]) ? $payload["nextOfKinEmail"] : "";
isset($payload["nextOfKinAddress"]) ? $payload["nextOfKinAddress"] : "";
isset($payload["nextOfKinGender"]) ? $payload["nextOfKinGender"] : "";
isset($payload["nextOfKinDOB"]) ? $payload["nextOfKinDOB"] : "";
isset($payload["nextOfKinRelationship"]) ? $payload["nextOfKinRelationship"] : "";
isset($payload["identityType"]) ? $payload["identityType"] : "";
isset($payload["identityNumber"]) ? $payload["identityNumber"] : "";
isset($payload["identityExpiryDate"]) ? $payload["identityExpiryDate"] : "";
isset($payload["employerName"]) ? $payload["employerName"] : "";
isset($payload["employerNo"]) ? $payload["employerNo"] : "";
isset($payload["employerAddress"]) ? $payload["employerAddress"] : "";
isset($payload["sortCode"]) ? $payload["sortCode"] : "";
isset($payload["RCNo"]) ? $payload["RCNo"] : "";
isset($payload["incorporationDate"]) ? $payload["incorporationDate"] : "";
isset($payload["swiftCode"]) ? $payload["swiftCode"] : "";
isset($payload["taxID"]) ? $payload["taxID"] : "";
isset($payload["previousCHN"]) ? $payload["previousCHN"] : "";
isset($payload["businessInvolvement"]) ? $payload["businessInvolvement"] : null ;
isset($payload["correspondentBankNo"]) ? $payload["correspondentBankNo"] : "";
isset($payload["correspondentBankName"]) ? $payload["correspondentBankName"] : "";
isset($payload["involvementType"]) ? $payload["involvementType"] : null;
isset($payload["primaryContactName"]) ? $payload["primaryContactName"] : "";
isset($payload["primaryContactPhone"]) ? $payload["primaryContactPhone"] : "";
isset($payload["primaryContactEmail"]) ? $payload["primaryContactEmail"] : "";
isset($payload["primaryContactDesignation"]) ? $payload["primaryContactDesignation"] : "";
isset($payload["secondaryContactName"]) ? $payload["secondaryContactName"] : "";
isset($payload["secondaryContactPhone"]) ? $payload["secondaryContactPhone"] : "";
isset($payload["secondaryContactEmail"]) ? $payload["secondaryContactEmail"] : "";
isset($payload["secondaryContactDesignation"]) ? $payload["secondaryContactDesignation"] : "";
isset($payload["agreementCheck"]) ? $payload["agreementCheck"] : "";
isset($payload["authorisedSignatureName"]) ? $payload["agreementCheck"] : "";
//isset($payload["gender"]) ? $payload["gender"] : "1";
$payload["compName"] = $payload["companyName"];
$payload["gender"] = "1";
$result = $this->createNewCorporateRecord($payload);
}
if(!is_null($payload["involvementType"]) && !is_null($payload["businessInvolvement"]) && strtoupper($payload['businessInvolvement']) != "CSRL" && strtoupper($payload['businessInvolvement']) != "CSA")
{
$payload['BIZID'] = $result["BIZID"];
$createInvolvement = formatIWRes(container('IWSRequest')->createInvolvement($payload));
}
return $result ?? [];
}
//create account on various involvements
public function createAccountOnVariousBusinesssUnits($middlewareID, $payload)
{
$response = [];
$ASSETID = $SECID = $CAMID ="";
// foreach ($payload['businessInvolvement'] as $businessInvolvement)
// {
if(strtoupper($payload['businessInvolvement']) == strtoupper(ASSETMGMT_DB_NAME)){
$result = formatIWRes($this->container->IWSRequest->startCreateCustomerAccount($payload, $payload['businessInvolvement']));
$decoded_data = json_decode(json_encode($result));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Account Creation in Asset Management");
$ASSETID = $BIZID = $decoded_data->OutValue;
$updateResult = formatIWRes($this->container->IWSRequest->completeCreateCustomerAccount($payload, $payload['businessInvolvement'], $BIZID));
$decoded_data = json_decode(json_encode($updateResult));
$this->handleFileUpload($payload, $ASSETID, ASSETMGMT_DB_NAME);
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "ASSETID: " . $ASSETID, "Status Message is " .$decoded_data->StatusMessage, "Custom Attributes Update in Asset Management");
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(STOCKBROKING_DB_NAME)){
$result = formatIWRes($this->container->IWSRequest->startCreateCustomerAccount($payload, $payload['businessInvolvement']));
$decoded_data = json_decode(json_encode($result));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Account Creation in SEC");
$SECID = $BIZID = $decoded_data->OutValue;
$updateResult = formatIWRes($this->container->IWSRequest->completeCreateCustomerAccount($payload, $payload['businessInvolvement'], $BIZID));
$decoded_data = json_decode(json_encode($updateResult));
$this->handleFileUpload($payload, $SECID, STOCKBROKING_DB_NAME);
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "SECID: " . $SECID, "Status Message is " .$decoded_data->StatusMessage, "Custom Attributes Update in SEC");
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(CAM_DB_NAME))
{
$result = formatIWRes($this->container->IWSRequest->startCreateCustomerAccount($payload, $payload['businessInvolvement']));
$decoded_data = json_decode(json_encode($result));
$CAMID = $BIZID = $decoded_data->OutValue;
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Account Creation in CAM");
if($payload["check-dc"] === false){
$updateResult = formatIWRes($this->container->IWSRequest->completeCreateCustomerAccount($payload, $payload['businessInvolvement'], $BIZID));
$decoded_data = json_decode(json_encode($updateResult));
$this->handleFileUpload($payload, $CAMID, CAM_DB_NAME);
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Custom Attributes Update in CAM");
}
}
// }
$updateResult = formatIWRes($this->container->IWSRequest->MergeCustomerAccountIDToMiddleware($middlewareID, $ASSETID, $SECID, $CAMID));
$decoded_data = json_decode(json_encode($updateResult));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "ASSETID: " . $ASSETID .", SECID: " . $SECID . ", CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Middleware IDs Merged for new client");
return ["ASSETID" => $ASSETID ?? 0, "CAMID" => $CAMID ?? 0, "SECID" => $SECID ?? 0, "BIZID" => $BIZID ?? 0];
}
public function createAccountOnAdditionalBusinesssUnits($middlewareID, $payload)
{
$response = [];
$ASSETID = $payload['ASSETID'];
$SECID = $payload['SECID'];
$CAMID = $payload['CAMID'];
// var_dump("business involvement is " . $payload['businessInvolvement']);
// var_dump(STOCKBROKING_DB_NAME);
if(strtoupper($payload['businessInvolvement']) == strtoupper(ASSETMGMT_DB_NAME)){
$result = formatIWRes($this->container->IWSRequest->startCreateCustomerAccount($payload, $payload['businessInvolvement']));
$decoded_data = json_decode(json_encode($result));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Account Creation in Asset Management");
$ASSETID = $BIZID = $decoded_data->OutValue;
$updateResult = formatIWRes($this->container->IWSRequest->completeCreateCustomerAccount($payload, $payload['businessInvolvement'], $BIZID));
$decoded_data = json_decode(json_encode($updateResult));
$this->handleFileUpload($payload, $ASSETID, ASSETMGMT_DB_NAME);
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "ASSETID: " . $ASSETID, "Status Message is " .$decoded_data->StatusMessage, "Custom Attributes Update in Asset Management");
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(STOCKBROKING_DB_NAME)){
$result = formatIWRes($this->container->IWSRequest->startCreateCustomerAccount($payload, $payload['businessInvolvement']));
$decoded_data = json_decode(json_encode($result));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Account Creation in SEC");
$SECID = $BIZID = $decoded_data->OutValue;
$updateResult = formatIWRes($this->container->IWSRequest->completeCreateCustomerAccount($payload, $payload['businessInvolvement'], $BIZID));
$decoded_data = json_decode(json_encode($updateResult));
$this->handleFileUpload($payload, $SECID, STOCKBROKING_DB_NAME);
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "SECID: " . $SECID, "Status Message is " .$decoded_data->StatusMessage, "Custom Attributes Update in SEC");
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(CAM_DB_NAME))
{
$result = formatIWRes($this->container->IWSRequest->startCreateCustomerAccount($payload, $payload['businessInvolvement']));
$decoded_data = json_decode(json_encode($result));
$CAMID = $BIZID = $decoded_data->OutValue;
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Account Creation in CAM");
$updateResult = formatIWRes($this->container->IWSRequest->completeCreateCustomerAccount($payload, $payload['businessInvolvement'], $BIZID));
$decoded_data = json_decode(json_encode($updateResult));
$this->handleFileUpload($payload, $CAMID, CAM_DB_NAME);
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Custom Attributes Update in CAM");
}else{
}
$updateResult = formatIWRes($this->container->IWSRequest->MergeCustomerAccountIDToMiddleware($middlewareID, $ASSETID, $SECID, $CAMID));
$decoded_data = json_decode(json_encode($updateResult));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $middlewareID, $payload['firstName']. " " . $payload['lastName'] . " " . $payload['companyName'], "ASSETID: " . $ASSETID .", SECID: " . $SECID . ", CAMID: " . $CAMID, "Status Message is " .$decoded_data->StatusMessage, "Middleware IDs Merged for new client");
if($decoded_data->StatusID != 0)
{
return ["code" => 400,"ASSETID" => $ASSETID, "CAMID" => $CAMID, "SECID" => $SECID];
}elseif($decoded_data->StatusID == 0)
{
return ["code" => 200, "ASSETID" => $ASSETID, "CAMID" => $CAMID, "SECID" => $SECID];
}
}
//upload files
public function uploadVariousFiles($payload, $custID) //custID is the middleware id
{
// error_log(print_r($payload));
foreach ($payload as $eachUpload=>$value)
{
if($value == ""){
continue;
}
$tempVariable = explode(".", $value);
$fileName = $eachUpload;
$fileType = $tempVariable[3];
error_log($this->container->IWSRequest->uploadFile($custID,$fileName,$fileType,$value ));
formatIWRes($this->container->IWSRequest->uploadFile($custID,$fileName,$fileType,$value ));
}
}
/*
* @return object
* @author [email protected]
*/
public function approveCustomerRecords($payload)
{
if($payload['level'] == 1 ) {
//update for LineManager
$this->customerTable()
->where('id', $payload['id'])
->update([
"lm_approval_status" => "approved",
"line_manager_approval" => $payload['approved_by'],
"line_manager_approvalDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}else
if($payload['level'] == 2 ){
//update for DivisionalHead
//update for LineManager
$this->customerTable()
->where('id', $payload['id'])
->update([
"dh_approval_status" => "approved",
"divisional_manager_approval" => $payload['approved_by'],
"divisional_manager_approvalDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
//todo:
//post to ixtrac
}
else{
return "Invalid Approval Level";
}
}
/**
* get all customer record on our DB that
*/
public function getAllNewCustomerForApproval($level)
{
if($level == 1){
//return for approval level 1
return $this->customerTable()
->where([
["lm_approval_status", "=", null],
["line_manager_approval", "=", null]
])
->get();
}else{
//return for approval level 2
//means level 1 must have been approved
return $this->customerTable()
->where([
["lm_approval_status", "!=", null],
["line_manager_approval", "!=", null]
])
->get();
}
}
//created by Tayo on the 17th of June to fetch iXtrac type state e.g Lagos -> LA
public function iState($state)
{
$iState = $this->iStateTable() //check if user has unused OTP
->where([["name", "=", $state ]])
->orWhere([["name1", "=", $state ]])
->orWhere([["name2", "=", $state ]])
->first();
return $iState->code;
}
public function checkIfcustomerKYCIsComplete($BIZID, $BIZ=null)
{
$BIZ = MIDDLEWARE_DB_NAME;
$res = $this
->container
->IWSRequest->PGetData2ForAll('CSP_0017', $BIZID, $BIZ);
return formatIWRes($res)['data'];
}
public function stateAndLGA() {
$lgaList = [
"Abia" => [
"Aba North",
"Aba South",
"Arochukwu",
"Bende",
"Ikwuano",
"Isiala Ngwa North",
"Isiala Ngwa South",
"Isuikwuato",
"Obi Ngwa",
"Ohafia",
"Osisioma",
"Ugwunagbo",
"Ukwa East",
"Ukwa West",
"Umuahia North",
"muahia South",
"Umu Nneochi"
],
"Adamawa" => [
"Demsa",
"Fufure",
"Ganye",
"Gayuk",
"Gombi",
"Grie",
"Hong",
"Jada",
"Larmurde",
"Madagali",
"Maiha",
"Mayo Belwa",
"Michika",
"Mubi North",
"Mubi South",
"Numan",
"Shelleng",
"Song",
"Toungo",
"Yola North",
"Yola South"
],
"Akwa Ibom" => [
"Abak",
"Eastern Obolo",
"Eket",
"Esit Eket",
"Essien Udim",
"Etim Ekpo",
"Etinan",
"Ibeno",
"Ibesikpo Asutan",
"Ibiono-Ibom",
"Ika",
"Ikono",
"Ikot Abasi",
"Ikot Ekpene",
"Ini",
"Itu",
"Mbo",
"Mkpat-Enin",
"Nsit-Atai",
"Nsit-Ibom",
"Nsit-Ubium",
"Obot Akara",
"Okobo",
"Onna",
"Oron",
"Oruk Anam",
"Udung-Uko",
"Ukanafun",
"Uruan",
"Urue-Offong Oruko",
"Uyo"
],
"Anambra" => [
"Aguata",
"Anambra East",
"Anambra West",
"Anaocha",
"Awka North",
"Awka South",
"Ayamelum",
"Dunukofia",
"Ekwusigo",
"Idemili North",
"Idemili South",
"Ihiala",
"Njikoka",
"Nnewi North",
"Nnewi South",
"Ogbaru",
"Onitsha North",
"Onitsha South",
"Orumba North",
"Orumba South",
"Oyi"
],
"Anambra" => [
"Aguata",
"Anambra East",
"Anambra West",
"Anaocha",
"Awka North",
"Awka South",
"Ayamelum",
"Dunukofia",
"Ekwusigo",
"Idemili North",
"Idemili South",
"Ihiala",
"Njikoka",
"Nnewi North",
"Nnewi South",
"Ogbaru",
"Onitsha North",
"Onitsha South",
"Orumba North",
"Orumba South",
"Oyi"
],
"Bauchi" => [
"Alkaleri",
"Bauchi",
"Bogoro",
"Damban",
"Darazo",
"Dass",
"Gamawa",
"Ganjuwa",
"Giade",
"Itas-Gadau",
"Jama are",
"Katagum",
"Kirfi",
"Misau",
"Ningi",
"Shira",
"Tafawa Balewa",
" Toro",
" Warji",
" Zaki"
],
"Bayelsa" => [
"Brass",
"Ekeremor",
"Kolokuma Opokuma",
"Nembe",
"Ogbia",
"Sagbama",
"Southern Ijaw",
"Yenagoa"
],
"Benue" => [
"Agatu",
"Apa",
"Ado",
"Buruku",
"Gboko",
"Guma",
"Gwer East",
"Gwer West",
"Katsina-Ala",
"Konshisha",
"Kwande",
"Logo",
"Makurdi",
"Obi",
"Ogbadibo",
"Ohimini",
"Oju",
"Okpokwu",
"Oturkpo",
"Tarka",
"Ukum",
"Ushongo",
"Vandeikya"
],
"Borno" => [
"Abadam",
"Askira-Uba",
"Bama",
"Bayo",
"Biu",
"Chibok",
"Damboa",
"Dikwa",
"Gubio",
"Guzamala",
"Gwoza",
"Hawul",
"Jere",
"Kaga",
"Kala-Balge",
"Konduga",
"Kukawa",
"Kwaya Kusar",
"Mafa",
"Magumeri",
"Maiduguri",
"Marte",
"Mobbar",
"Monguno",
"Ngala",
"Nganzai",
"Shani"
],
"Cross River" => [
"Abi",
"Akamkpa",
"Akpabuyo",
"Bakassi",
"Bekwarra",
"Biase",
"Boki",
"Calabar Municipal",
"Calabar South",
"Etung",
"Ikom",
"Obanliku",
"Obubra",
"Obudu",
"Odukpani",
"Ogoja",
"Yakuur",
"Yala"
],
"Delta" => [
"Aniocha North",
"Aniocha South",
"Bomadi",
"Burutu",
"Ethiope East",
"Ethiope West",
"Ika North East",
"Ika South",
"Isoko North",
"Isoko South",
"Ndokwa East",
"Ndokwa West",
"Okpe",
"Oshimili North",
"Oshimili South",
"Patani",
"Sapele",
"Udu",
"Ughelli North",
"Ughelli South",
"Ukwuani",
"Uvwie",
"Warri North",
"Warri South",
"Warri South West"
],
"Ebonyi" => [
"Abakaliki",
"Afikpo North",
"Afikpo South",
"Ebonyi",
"Ezza North",
"Ezza South",
"Ikwo",
"Ishielu",
"Ivo",
"Izzi",
"Ohaozara",
"Ohaukwu",
"Onicha"
],
"Edo" => [
"Akoko-Edo",
"Egor",
"Esan Central",
"Esan North-East",
"Esan South-East",
"Esan West",
"Etsako Central",
"Etsako East",
"Etsako West",
"Igueben",
"Ikpoba Okha",
"Orhionmwon",
"Oredo",
"Ovia North-East",
"Ovia South-West",
"Owan East",
"Owan West",
"Uhunmwonde"
],
"Ekiti" => [
"Ado Ekiti",
"Efon",
"Ekiti East",
"Ekiti South-West",
"Ekiti West",
"Emure",
"Gbonyin",
"Ido Osi",
"Ijero",
"Ikere",
"Ikole",
"Ilejemeje",
"Irepodun-Ifelodun",
"Ise-Orun",
"Moba",
"Oye"
],
"Rivers" => [
"Port Harcourt",
"Obio-Akpor",
"Okrika",
"Ogu–Bolo",
"Eleme",
"Tai",
"Gokana",
"Khana",
"Oyigbo",
"Opobo–Nkoro",
"Andoni",
"Bonny",
"Degema",
"Asari-Toru",
"Akuku-Toru",
"Abua–Odual",
"Ahoada West",
"Ahoada East",
"Ogba–Egbema–Ndoni",
"Emohua",
"Ikwerre",
"Etche",
"Omuma"
],
"Enugu" => [
"Aninri",
"Awgu",
"Enugu East",
"Enugu North",
"Enugu South",
"Ezeagu",
"Igbo Etiti",
"Igbo Eze North",
"Igbo Eze South",
"Isi Uzo",
"Nkanu East",
"Nkanu West",
"Nsukka",
"Oji River",
"Udenu",
"Udi",
"Uzo Uwani"
],
"FCT" => [
"Abaji",
"Bwari",
"Gwagwalada",
"Kuje",
"Kwali",
"Municipal Area Council"
],
"Gombe" => [
"Akko",
"Balanga",
"Billiri",
"Dukku",
"Funakaye",
"Gombe",
"Kaltungo",
"Kwami",
"Nafada",
"Shongom",
"Yamaltu-Deba"
],
"Imo" => [
"Aboh Mbaise",
"Ahiazu Mbaise",
"Ehime Mbano",
"Ezinihitte",
"Ideato North",
"Ideato South",
"Ihitte-Uboma",
"Ikeduru",
"Isiala Mbano",
"Isu",
"Mbaitoli",
"Ngor Okpala",
"Njaba",
"Nkwerre",
"Nwangele",
"Obowo",
"Oguta",
"Ohaji-Egbema",
"Okigwe",
"Orlu",
"Orsu",
"Oru East",
"Oru West",
"Owerri Municipal",
"Owerri North",
"Owerri West",
"Unuimo"
],
"Jigawa" => [
"Auyo",
"Babura",
"Biriniwa",
"Birnin Kudu",
"Buji",
"Dutse",
"Gagarawa",
"Garki",
"Gumel",
"Guri",
"Gwaram",
"Gwiwa",
"Hadejia",
"Jahun",
"Kafin Hausa",
"Kazaure",
"Kiri Kasama",
"Kiyawa",
"Kaugama",
"Maigatari",
"Malam Madori",
"Miga",
"Ringim",
"Roni",
"Sule Tankarkar",
"Taura",
"Yankwashi"
],
"Kaduna" => [
"Birnin Gwari",
"Chikun",
"Giwa",
"Igabi",
"Ikara",
"Jaba",
"Jema a",
"Kachia",
"Kaduna North",
"Kaduna South",
"Kagarko",
"Kajuru",
"Kaura",
"Kauru",
"Kubau",
"Kudan",
"Lere",
"Makarfi",
"Sabon Gari",
"Sanga",
"Soba",
"Zangon Kataf",
"Zaria"
],
"Kano" => [
"Ajingi",
"Albasu",
"Bagwai",
"Bebeji",
"Bichi",
"Bunkure",
"Dala",
"Dambatta",
"Dawakin Kudu",
"Dawakin Tofa",
"Doguwa",
"Fagge",
"Gabasawa",
"Garko",
"Garun Mallam",
"Gaya",
"Gezawa",
"Gwale",
"Gwarzo",
"Kabo",
"Kano Municipal",
"Karaye",
"Kibiya",
"Kiru",
"Kumbotso",
"Kunchi",
"Kura",
"Madobi",
"Makoda",
"Minjibir",
"Nasarawa",
"Rano",
"Rimin Gado",
"Rogo",
"Shanono",
"Sumaila",
"Takai",
"Tarauni",
"Tofa",
"Tsanyawa",
"Tudun Wada",
"Ungogo",
"Warawa",
"Wudil"
],
"Katsina" => [
"Bakori",
"Batagarawa",
"Batsari",
"Baure",
"Bindawa",
"Charanchi",
"Dandume",
"Danja",
"Dan Musa",
"Daura",
"Dutsi",
"Dutsin Ma",
"Faskari",
"Funtua",
"Ingawa",
"Jibia",
"Kafur",
"Kaita",
"Kankara",
"Kankia",
"Katsina",
"Kurfi",
"Kusada",
"Mai Adua",
"Malumfashi",
"Mani",
"Mashi",
"Matazu",
"Musawa",
"Rimi",
"Sabuwa",
"Safana",
"Sandamu",
"Zango"
],
"Kebbi" => [
"Aleiro",
"Arewa Dandi",
"Argungu",
"Augie",
"Bagudo",
"Birnin Kebbi",
"Bunza",
"Dandi",
"Fakai",
"Gwandu",
"Jega",
"Kalgo",
"Koko Besse",
"Maiyama",
"Ngaski",
"Sakaba",
"Shanga",
"Suru",
"Wasagu Danko",
"Yauri",
"Zuru"
],
"Kogi" => [
"Adavi",
"Ajaokuta",
"Ankpa",
"Bassa",
"Dekina",
"Ibaji",
"Idah",
"Igalamela Odolu",
"Ijumu",
"Kabba Bunu",
"Kogi",
"Lokoja",
"Mopa Muro",
"Ofu",
"Ogori Magongo",
"Okehi",
"Okene",
"Olamaboro",
"Omala",
"Yagba East",
"Yagba West"
],
"Kwara" => [
"Asa",
"Baruten",
"Edu",
"Ekiti",
"Ifelodun",
"Ilorin East",
"Ilorin South",
"Ilorin West",
"Irepodun",
"Isin",
"Kaiama",
"Moro",
"Offa",
"Oke Ero",
"Oyun",
"Pategi"
],
"Lagos" => [
"Agege",
"Ajeromi-Ifelodun",
"Alimosho",
"Amuwo-Odofin",
"Apapa",
"Badagry",
"Epe",
"Eti Osa",
"Ibeju-Lekki",
"Ifako-Ijaiye",
"Ikeja",
"Ikorodu",
"Kosofe",
"Lagos Island",
"Lagos Mainland",
"Mushin",
"Ojo",
"Oshodi-Isolo",
"Shomolu",
"Surulere"
],
"Nasarawa" => [
"Akwanga",
"Awe",
"Doma",
"Karu",
"Keana",
"Keffi",
"Kokona",
"Lafia",
"Nasarawa",
"Nasarawa Egon",
"Obi",
"Toto",
"Wamba"
],
"Niger" => [
"Agaie",
"Agwara",
"Bida",
"Borgu",
"Bosso",
"Chanchaga",
"Edati",
"Gbako",
"Gurara",
"Katcha",
"Kontagora",
"Lapai",
"Lavun",
"Magama",
"Mariga",
"Mashegu",
"Mokwa",
"Moya",
"Paikoro",
"Rafi",
"Rijau",
"Shiroro",
"Suleja",
"Tafa",
"Wushishi"
],
"Ogun" => [
"Abeokuta North",
"Abeokuta South",
"Ado-Odo Ota",
"Egbado North",
"Egbado South",
"Ewekoro",
"Ifo",
"Ijebu East",
"Ijebu North",
"Ijebu North East",
"Ijebu Ode",
"Ikenne",
"Imeko Afon",
"Ipokia",
"Obafemi Owode",
"Odeda",
"Odogbolu",
"Ogun Waterside",
"Remo North",
"Shagamu"
],
"Ondo" => [
"Akoko North-East",
"Akoko North-West",
"Akoko South-West",
"Akoko South-East",
"Akure North",
"Akure South",
"Ese Odo",
"Idanre",
"Ifedore",
"Ilaje",
"Ile Oluji-Okeigbo",
"Irele",
"Odigbo",
"Okitipupa",
"Ondo East",
"Ondo West",
"Ose",
"Owo"
],
"Osun" => [
"Atakunmosa East",
"Atakunmosa West",
"Aiyedaade",
"Aiyedire",
"Boluwaduro",
"Boripe",
"Ede North",
"Ede South",
"Ife Central",
"Ife East",
"Ife North",
"Ife South",
"Egbedore",
"Ejigbo",
"Ifedayo",
"Ifelodun",
"Ila",
"Ilesa East",
"Ilesa West",
"Irepodun",
"Irewole",
"Isokan",
"Iwo",
"Obokun",
"Odo Otin",
"Ola Oluwa",
"Olorunda",
"Oriade",
"Orolu",
"Osogbo"
],
"Oyo" => [
"Afijio",
"Akinyele",
"Atiba",
"Atisbo",
"Egbeda",
"Ibadan North",
"Ibadan North-East",
"Ibadan North-West",
"Ibadan South-East",
"Ibadan South-West",
"Ibarapa Central",
"Ibarapa East",
"Ibarapa North",
"Ido",
"Irepo",
"Iseyin",
"Itesiwaju",
"Iwajowa",
"Kajola",
"Lagelu",
"Ogbomosho North",
"Ogbomosho South",
"Ogo Oluwa",
"Olorunsogo",
"Oluyole",
"Ona Ara",
"Orelope",
"Ori Ire",
"Oyo",
"Oyo East",
"Saki East",
"Saki West",
"Surulere"
],
"Plateau" => [
"Bokkos",
"Barkin Ladi",
"Bassa",
"Jos East",
"Jos North",
"Jos South",
"Kanam",
"Kanke",
"Langtang South",
"Langtang North",
"Mangu",
"Mikang",
"Pankshin",
"Qua an Pan",
"Riyom",
"Shendam",
"Wase"
],
"Sokoto" => [
"Binji",
"Bodinga",
"Dange Shuni",
"Gada",
"Goronyo",
"Gudu",
"Gwadabawa",
"Illela",
"Isa",
"Kebbe",
"Kware",
"Rabah",
"Sabon Birni",
"Shagari",
"Silame",
"Sokoto North",
"Sokoto South",
"Tambuwal",
"Tangaza",
"Tureta",
"Wamako",
"Wurno",
"Yabo"
],
"Taraba" => [
"Ardo Kola",
"Bali",
"Donga",
"Gashaka",
"Gassol",
"Ibi",
"Jalingo",
"Karim Lamido",
"Kumi",
"Lau",
"Sardauna",
"Takum",
"Ussa",
"Wukari",
"Yorro",
"Zing"
],
"Yobe" => [
"Bade",
"Bursari",
"Damaturu",
"Fika",
"Fune",
"Geidam",
"Gujba",
"Gulani",
"Jakusko",
"Karasuwa",
"Machina",
"Nangere",
"Nguru",
"Potiskum",
"Tarmuwa",
"Yunusari",
"Yusufari"
],
"Zamfara" => [
"Anka",
"Bakura",
"Birnin Magaji Kiyaw",
"Bukkuyum",
"Bungudu",
"Gummi",
"Gusau",
"Kaura Namoda",
"Maradun",
"Maru",
"Shinkafi",
"Talata Mafara",
"Chafe",
"Zurmi"
]
];
return $lgaList ?? [];
}
public function processEquityWebhook($payload) //create new fund
{
if($payload['webhookType'] == "nubanPayment")
{
//fetch CustID from NUBAN table
$nuban = $this->getNubanforWebhook($payload);
$decodedNuban = json_decode(json_encode($nuban), true);
$payload += $decodedNuban;
}
elseif($payload['webhookType'] == "transfer")
{
container('paystackGatewayModel')->postEquityVirtualTransaction($payload);
return $data = ["message" => "Successfully notified FINCON and RICA", "code" => 200];
}
elseif($payload['webhookType'] == "paystack")
{
container('paystackGatewayModel')->postEquityVirtualTransaction($payload);
return $data = ["message" => "Successfully notified FINCON and RICA", "code" => 200];
}
}
/**
* Process webhook event
*/
public function processWebhook($payload) //create new fund
{
if ($payload['webhookType'] != 'paystack_recovery')
{
// file_put_contents('/tmp/postdata_paystack.txt', var_export($payload, true), FILE_APPEND);
//check if record already exists
$check = $this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->first() ?? [];
$check = json_decode(json_encode($check), true);
if(count($check) > 0 && !is_null($payload["transactionRef"]))
{
$message1 = "Webhook Type - " . $payload['webhookType'];
$message2 = "Processing webhook";
$message3 = "Webhook Type Verified";
$message4 = json_encode($payload);
$message5 = "Duplicate Paystack Transaction";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
return ["code" => 400, "message" => "Duplicate Transaction"];
}else{
$message1 = "Webhook Type - " . $payload['webhookType'];
$message2 = "Processing webhook";
$message3 = "Webhook Type Verified";
$message4 = json_encode($payload);
$message5 = "Proceed to Process Paystack Transaction";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
}
}
/* $transactionDetails = container('PaystackGatewayModel')->retrieveTransactionDetails($payload['transactionRef']);
if($transactionDetails->amount != $payload['amount'] && !is_null($transactionDetails->amount)&& !is_null($payload['amount']))
{
$message1 = $payload['reference'];
$message2 = $payload['amount'];
$message3 = $payload['ipaddress'];
$message4 = $payload['email'];
$message5 = $payload['Fraudulent transaction'];
$this->activity_log($message1,$message2,$message3,$message4,$message5);
die("You are a THIEF!!!");
} */
if($payload['webhookType'] == "nubanPayment")
{
//insert payment details into paystack webhook log table
$this->paystackWebhookLogTable()
->insertGetId([
'transactionRef' => $payload["transactionRef"],
'reference' => $payload["reference"],
'fullName' => strtoupper($payload["fullName"]),
'accountNumber' => $payload["virtualAccountNumber"],
'paymentDetails' => $payload["cardDetails"],
'bankName' => $payload["bank"],
'channel' => $payload["channel"],
'phoneNumber' => $payload["phoneNumber"],
'emailAddress' => $payload["emailAddress"],
'event' => $payload["event"],
'status' => ( strtolower($payload["event"]) == "transfer.success") ? 'processed' : 'pending',
'customerCode' => $payload["customerCode"],
'actualAmount' => abs($payload['amount']),
'amount' => abs($payload['amount']),
'currency' => "NGN",
"ipAddress" => $payload["ipaddress"],
]);
//fetch CustID from NUBAN table
$nuban = $this->getNubanforWebhook($payload);
$decodedNuban = json_decode(json_encode($nuban), true);
$payload += $decodedNuban;
// file_put_contents('/tmp/nuban_webhook_paylaod1.txt', var_export($payload, true), FILE_APPEND);
$result = $this->mutualFundAdminLogin($payload['CustID'], $payload['admin']);
$payload['fullName'] = str_replace(",","",$result['customer'][0]["Name"]);
$payload['CAMID'] = $result['customer'][0]["CAMID"];
$payload['SECID'] = $result['customer'][0]["SECID"];
$payload['ASSETID'] = $result['customer'][0]["ASSETID"];
// file_put_contents('/tmp/nuban_webhook_paylaod2.txt', var_export($payload, true), FILE_APPEND);
//check if customer has product involvement
$load["CustID"] = $payload["CustID"];
$BIZID = $payload["CAMID"];
$load["businessInvolvement"] = $DB = CAM_DB_NAME;
//get Involvement Type and company
$nubanProduct = $this->getNubanProduct(strtoupper($payload["product"]));
$payload['company'] = $nubanProduct->company;
$load["involvementType"] = $INVOLVEMENT = $nubanProduct->involvementType;
// file_put_contents('/tmp/nuban_webhook_paylaod3.txt', var_export($payload, true), FILE_APPEND);
// file_put_contents('/tmp/nuban_webhook_laod1.txt', var_export($load, true), FILE_APPEND);
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) != "TRUE")
{
$create = $this->createInvolvement($load);
if(!isset($payload["CAMID"]) || empty($payload["CAMID"]) || is_null($payload["CAMID"]) || $payload["CAMID"] == "")
{
$payload["CAMID"] = $create["BIZID"];
}
}
if((is_null($payload['CAMID']) || empty($payload['CAMID']) || $payload['CAMID'] == "") ||(is_null($payload['fullName']) || empty($payload['fullName']) || $payload['fullName'] == ""))
{
$result = $this->mutualFundAdminLogin($payload['CustID'], $payload['admin']);
$payload['fullName'] = str_replace(",","",$result['customer'][0]["Name"]);
$payload['CAMID'] = $result['customer'][0]["CAMID"];
}
//check product subscribed
if(strtoupper($payload['product']) == "CSPFIFUND") //alpha fund subscription
{
//check for product description, registerID, ixtrac accountNumber, and set initiatedPrice
$res = container('mutualFundModel')->accountNumber($payload['fundCode'], $payload['CustID']);
$decodedRes = json_decode(json_encode($res), true);
$payload['registerID'] = $decodedRes[0]['REGISTER_ID'];
$payload['accountNumber'] = $decodedRes[0]['ACCOUNT_NUMBER'];
$payload['productDescription'] = $decodedRes[0]['DESCRIPTION'];
//fetch current fund price
$ress = container('mutualFundModel')->lastMutualFundtransactionPrice($payload['fundCode']);
$decodedRess = json_decode(json_encode($ress), true);
// $payload['initiatedPrice'] = $decodedRess['BidPrice'];
$payload['initiatedPrice'] = $decodedRess['BidPrice'];
$payload['merchantId'] = PAYSTACK_ID;
$payload['channel'] = "Virtual Account";
// $payload['admin'] = "Virtual Account";
$payload['clientId'] = $payload['CAMID'];
$payload['companyName'] = "CAM";
$payload['currency'] = "566";
$payload['productId'] = FI10;
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Merchant ID: " .$payload["merchantId"];
$message3 = "Product ID: " .$payload["productId"];
$message4 = "Record prepared for processing";
$message5 = "Proceed to attempt funding";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//Gl posting
$glPost = container('PaystackGatewayModel')->postMutualfundsVirtualTransaction($payload, $payload['reference'],$payload['merchantId']);
// var_dump("code is " . $glPost["code"]);
// var_dump($glPost);\
if($glPost["code"] == 200) {
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Complete";
$message5 = "Proceeding to book Subscription";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//process subscription
$payload['subscriptionAmount'] = $payload['amount'];
// $payload['channel'] = "bank_transfer";
$res = container('mutualFundModel')->newWebhookFundSubscription($payload);
if($res["code"] == 200){
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Subscription Status Code: " .$res["code"];
$message3 = "Subscription Status Message: " .$res["message"];
$message4 = "Subscription successful";
$message5 = "Proceed to notify RICA";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['subscriptionAmount'],
"transactionType" => "SUBSCRIPTION",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification")
->usingView('admin_rica_notify', $mail)
->send();
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "processed",
]);
return $data = ["message" => "Subscription Successful", "code" => 200];
}else{
//log event
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Subscription Status Code: " .$res["code"];
$message3 = "Subscription Status Message: " .$res["message"];
$message4 = "Subscription failed";
$message5 = "Proceed to notify RICA of Failure";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['subscriptionAmount'],
"transactionType" => "SUBSCRIPTION",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification Failed")
->usingView('admin_rica_notify', $mail)
->send();
return $data = ["message" => "Subscription Failed", "code" => 400];
}
}else{
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "failed",
]);
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Failed";
$message5 = "Cannot Proceed to book Subscription";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
return $data = ["message" => $glPost["message"], "code" => $glPost["code"]];
}
}elseif(strtoupper($payload['product']) == "CSWALLET") //alpha fund subscription
{
$payload['merchantId'] = PAYSTACK_ID; //Should be changed to CSWALLET merchantId
$payload['channel'] = "Virtual Account";
$payload['admin'] = "Virtual Account";
$payload['clientId'] = $payload['CAMID'];
$payload['companyName'] = "CAM";
$payload['currency'] = "566";
$payload['productId'] = CSWALLET_CASHACCOUNT;
$payload['productDescription'] = CSWALLET_DESCRIPTION;
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Merchant ID: " .$payload["merchantId"];
$message3 = "Product ID: " .$payload["productId"];
$message4 = "Record prepared for processing";
$message5 = "Proceed to attempt funding";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//Gl posting
$glPost = container('PaystackGatewayModel')->postWalletVirtualTransaction($payload, $payload['reference'],$payload['merchantId']);
// var_dump("code is " . $glPost["code"]);
// var_dump($glPost);\
// file_put_contents('/tmp/nuban_webhook_paylaod13.txt', var_export($glPost, true), FILE_APPEND);
if($glPost["code"] == 200) {
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Complete";
$message5 = "Proceeding to Credit Wallet";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//process subscription
$payload['transactionAmount'] = $payload['amount'];
$payload["productType"] = "Virtual Account";
$payload["transactionRef"] = $payload['reference'];
$payload["narration"] = "Being credit to ". $payload["fullName"]."'s wallet from ". $payload["productType"]; //for wallet
$res = container('mutualFundModel')->newWebhookCreditWallet($payload);
// file_put_contents('/tmp/nuban_webhook_paylaod14.txt', var_export($res, true), FILE_APPEND);
if($res["code"] == 200){
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Wallet Credit Status Code: " .$res["code"];
$message3 = "Wallet Credit Status Message: " .$res["message"];
$message4 = "Wallet Credit successful";
$message5 = "Proceed to notify RICA";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['transactionAmount'],
"transactionType" => "DEPOSIT",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification")
->usingView('admin_rica_notify', $mail)
->send();
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "processed",
]);
return $data = ["message" => "Wallet Credit Successful", "code" => 200];
}else{
//log event
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Wallet Credit Status Code: " .$res["code"];
$message3 = "Wallet Credit Status Message: " .$res["message"];
$message4 = "Wallet Credit failed";
$message5 = "Proceed to notify RICA of Failure";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['transactionAmount'],
"transactionType" => "DEPOSIT",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Failure Notification")
->usingView('admin_rica_notify', $mail)
->send();
return $data = ["message" => "Wallet Credit Failed", "code" => 400];
}
}else{
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "failed",
]);
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Failed";
$message5 = "Cannot Proceed to Credit Wallet";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
return $data = ["message" => $glPost["message"], "code" => $glPost["code"]];
}
}elseif(strtoupper($payload['product']) == "EQF")
{
//check for product description, registerID, ixtrac accountNumber, and set initiatedPrice
$res = container('mutualFundModel')->accountNumber($payload['fundCode'], $payload['CustID']);
$decodedRes = json_decode(json_encode($res), true);
$payload['registerID'] = $decodedRes[0]['REGISTER_ID'];
$payload['accountNumber'] = $decodedRes[0]['ACCOUNT_NUMBER'];
$payload['productDescription'] = $decodedRes[0]['DESCRIPTION'];
//fetch current fund price
$ress = container('mutualFundModel')->lastMutualFundtransactionPrice($payload['fundCode']);
$decodedRess = json_decode(json_encode($ress), true);
// $payload['initiatedPrice'] = $decodedRess['BidPrice'];
$payload['initiatedPrice'] = $decodedRess['BidPrice'];
$payload['merchantId'] = PAYSTACK_ID;
$payload['channel'] = "Virtual Account";
// $payload['admin'] = "Virtual Account";
$payload['clientId'] = $payload['CAMID'];
$payload['companyName'] = "CAM";
$payload['currency'] = "566";
$payload['productId'] = EQF_01;
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Merchant ID: " .$payload["merchantId"];
$message3 = "Product ID: " .$payload["productId"];
$message4 = "Record prepared for processing";
$message5 = "Proceed to attempt funding";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//Gl posting
$glPost = container('PaystackGatewayModel')->postMutualfundsVirtualTransaction($payload, $payload['reference'],$payload['merchantId']);
// var_dump("code is " . $glPost["code"]);
// var_dump($glPost);\
if($glPost["code"] == 200)
{
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Complete";
$message5 = "Proceeding to book Subscription";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//process subscription
$payload['subscriptionAmount'] = $payload['amount'];
// $payload['channel'] = "bank_transfer";
$res = container('mutualFundModel')->newWebhookFundSubscription($payload);
if($res["code"] == 200){
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Subscription Status Code: " .$res["code"];
$message3 = "Subscription Status Message: " .$res["message"];
$message4 = "Subscription successful";
$message5 = "Proceed to notify RICA";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['subscriptionAmount'],
"transactionType" => "SUBSCRIPTION",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification")
->usingView('admin_rica_notify', $mail)
->send();
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "processed",
]);
return $data = ["message" => "Subscription Successful", "code" => 200];
}else{
//log event
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Subscription Status Code: " .$res["code"];
$message3 = "Subscription Status Message: " .$res["message"];
$message4 = "Subscription failed";
$message5 = "Proceed to notify RICA of Failure";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['subscriptionAmount'],
"transactionType" => "SUBSCRIPTION",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification Failed")
->usingView('admin_rica_notify', $mail)
->send();
return $data = ["message" => "Subscription Failed", "code" => 400];
}
}else{
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "failed",
]);
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Failed";
$message5 = "Cannot Proceed to book Subscription";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
return $data = ["message" => $glPost["message"], "code" => $glPost["code"]];
}
}
}elseif($payload['webhookType'] == "nubanPayment2")
{
//insert payment details into paystack webhook log table
/* $this->paystackWebhookLogTable()
->insertGetId([
'transactionRef' => $payload["transactionRef"],
'reference' => $payload["reference"],
'fullName' => strtoupper($payload["fullName"]),
'accountNumber' => $payload["virtualAccountNumber"],
'paymentDetails' => $payload["cardDetails"],
'bankName' => $payload["bank"],
'channel' => $payload["channel"],
'phoneNumber' => $payload["phoneNumber"],
'emailAddress' => $payload["emailAddress"],
'event' => $payload["event"],
'status' => ( strtolower($payload["event"]) == "transfer.success") ? 'processed' : 'pending',
'customerCode' => $payload["customerCode"],
'actualAmount' => abs($payload['amount']),
'currency' => "NGN",
"ipAddress" => $payload["ipaddress"],
]); */
$payloads = $this->paystackWebhookLogTable()
->where([
["status", "=", "pending"],
["channel", "=", "dedicated_nuban"],
])
->get() ?? [];
$payloads = json_decode(json_encode($payloads), true);
file_put_contents('/tmp/nuban_reprocess.txt', var_export($payloads, true), FILE_APPEND);
foreach ($payloads as $payload)
{
$payload['virtualAccountNumber']= $payload['accountNumber'];
$payload['bank']= $payload['bankName'];
$payload['amount']= $payload['actualAmount'];
//fetch CustID from NUBAN table
$nuban = $this->getNubanforWebhook($payload);
$decodedNuban = json_decode(json_encode($nuban), true);
$payload += $decodedNuban;
// file_put_contents('/tmp/nuban_webhook_paylaod1.txt', var_export($payload, true), FILE_APPEND);
$result = $this->mutualFundAdminLogin($payload['CustID'], $payload['admin']);
$payload['fullName'] = str_replace(",","",$result['customer'][0]["Name"]);
$payload['CAMID'] = $result['customer'][0]["CAMID"];
$payload['SECID'] = $result['customer'][0]["SECID"];
$payload['ASSETID'] = $result['customer'][0]["ASSETID"];
// file_put_contents('/tmp/nuban_webhook_paylaod2.txt', var_export($payload, true), FILE_APPEND);
//check if customer has product involvement
$load["CustID"] = $payload["CustID"];
$BIZID = $payload["CAMID"];
$load["businessInvolvement"] = $DB = CAM_DB_NAME;
//get Involvement Type and company
$nubanProduct = $this->getNubanProduct(strtoupper($payload["product"]));
$payload['company'] = $nubanProduct->company;
$load["involvementType"] = $INVOLVEMENT = $nubanProduct->involvementType;
// file_put_contents('/tmp/nuban_webhook_paylaod3.txt', var_export($payload, true), FILE_APPEND);
// file_put_contents('/tmp/nuban_webhook_laod1.txt', var_export($load, true), FILE_APPEND);
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) != "TRUE")
{
$create = $this->createInvolvement($load);
if(!isset($payload["CAMID"]) || empty($payload["CAMID"]) || is_null($payload["CAMID"]) || $payload["CAMID"] == "")
{
$payload["CAMID"] = $create["BIZID"];
}
}
if((is_null($payload['CAMID']) || empty($payload['CAMID']) || $payload['CAMID'] == "") ||(is_null($payload['fullName']) || empty($payload['fullName']) || $payload['fullName'] == ""))
{
$result = $this->mutualFundAdminLogin($payload['CustID'], $payload['admin']);
$payload['fullName'] = str_replace(",","",$result['customer'][0]["Name"]);
$payload['CAMID'] = $result['customer'][0]["CAMID"];
}
//check product subscribed
if(strtoupper($payload['product']) == "CSPFIFUND") //alpha fund subscription
{
//check for product description, registerID, ixtrac accountNumber, and set initiatedPrice
$res = container('mutualFundModel')->accountNumber($payload['fundCode'], $payload['CustID']);
$decodedRes = json_decode(json_encode($res), true);
$payload['registerID'] = $decodedRes[0]['REGISTER_ID'];
$payload['accountNumber'] = $decodedRes[0]['ACCOUNT_NUMBER'];
$payload['productDescription'] = $decodedRes[0]['DESCRIPTION'];
//fetch current fund price
$ress = container('mutualFundModel')->lastMutualFundtransactionPrice($payload['fundCode']);
$decodedRess = json_decode(json_encode($ress), true);
// $payload['initiatedPrice'] = $decodedRess['BidPrice'];
$payload['initiatedPrice'] = $decodedRess['BidPrice'];
$payload['merchantId'] = PAYSTACK_ID;
$payload['channel'] = "Virtual Account";
// $payload['admin'] = "Virtual Account";
$payload['clientId'] = $payload['CAMID'];
$payload['companyName'] = "CAM";
$payload['currency'] = "566";
$payload['productId'] = FI10;
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Merchant ID: " .$payload["merchantId"];
$message3 = "Product ID: " .$payload["productId"];
$message4 = "Record prepared for processing";
$message5 = "Proceed to attempt funding";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//Gl posting
$glPost = container('PaystackGatewayModel')->postMutualfundsVirtualTransaction($payload, $payload['reference'],$payload['merchantId']);
// var_dump("code is " . $glPost["code"]);
// var_dump($glPost);\
if($glPost["code"] == 200) {
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Complete";
$message5 = "Proceeding to book Subscription";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//process subscription
$payload['subscriptionAmount'] = $payload['amount'];
// $payload['channel'] = "bank_transfer";
$res = container('mutualFundModel')->newWebhookFundSubscription($payload);
if($res["code"] == 200){
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Subscription Status Code: " .$res["code"];
$message3 = "Subscription Status Message: " .$res["message"];
$message4 = "Subscription successful";
$message5 = "Proceed to notify RICA";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['subscriptionAmount'],
"transactionType" => "SUBSCRIPTION",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification")
->usingView('admin_rica_notify', $mail)
->send();
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "processed",
]);
return $data = ["message" => "Subscription Successful", "code" => 200];
}else{
//log event
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Subscription Status Code: " .$res["code"];
$message3 = "Subscription Status Message: " .$res["message"];
$message4 = "Subscription failed";
$message5 = "Proceed to notify RICA of Failure";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['subscriptionAmount'],
"transactionType" => "SUBSCRIPTION",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification Failed")
->usingView('admin_rica_notify', $mail)
->send();
return $data = ["message" => "Subscription Failed", "code" => 400];
}
}else{
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "failed",
]);
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Failed";
$message5 = "Cannot Proceed to book Subscription";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
return $data = ["message" => $glPost["message"], "code" => $glPost["code"]];
}
}elseif(strtoupper($payload['product']) == "CSWALLET") //alpha fund subscription
{
$payload['merchantId'] = PAYSTACK_ID; //Should be changed to CSWALLET merchantId
$payload['channel'] = "Virtual Account";
$payload['admin'] = "Virtual Account";
$payload['clientId'] = $payload['CAMID'];
$payload['companyName'] = "CAM";
$payload['currency'] = "566";
$payload['productId'] = CSWALLET_CASHACCOUNT;
$payload['productDescription'] = CSWALLET_DESCRIPTION;
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Merchant ID: " .$payload["merchantId"];
$message3 = "Product ID: " .$payload["productId"];
$message4 = "Record prepared for processing";
$message5 = "Proceed to attempt funding";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//Gl posting
$glPost = container('PaystackGatewayModel')->postWalletVirtualTransaction($payload, $payload['reference'],$payload['merchantId']);
// var_dump("code is " . $glPost["code"]);
// var_dump($glPost);\
// file_put_contents('/tmp/nuban_webhook_paylaod13.txt', var_export($glPost, true), FILE_APPEND);
if($glPost["code"] == 200) {
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Complete";
$message5 = "Proceeding to Credit Wallet";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//process subscription
$payload['transactionAmount'] = $payload['amount'];
$payload["productType"] = "Virtual Account";
$payload["transactionRef"] = $payload['reference'];
$payload["narration"] = "Being credit to ". $payload["fullName"]."'s wallet from ". $payload["productType"]; //for wallet
$res = container('mutualFundModel')->newWebhookCreditWallet($payload);
// file_put_contents('/tmp/nuban_webhook_paylaod14.txt', var_export($res, true), FILE_APPEND);
if($res["code"] == 200){
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Wallet Credit Status Code: " .$res["code"];
$message3 = "Wallet Credit Status Message: " .$res["message"];
$message4 = "Wallet Credit successful";
$message5 = "Proceed to notify RICA";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['transactionAmount'],
"transactionType" => "DEPOSIT",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification")
->usingView('admin_rica_notify', $mail)
->send();
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "processed",
]);
return $data = ["message" => "Wallet Credit Successful", "code" => 200];
}else{
//log event
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Wallet Credit Status Code: " .$res["code"];
$message3 = "Wallet Credit Status Message: " .$res["message"];
$message4 = "Wallet Credit failed";
$message5 = "Proceed to notify RICA of Failure";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['transactionAmount'],
"transactionType" => "DEPOSIT",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Failure Notification")
->usingView('admin_rica_notify', $mail)
->send();
return $data = ["message" => "Wallet Credit Failed", "code" => 400];
}
}else{
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "failed",
]);
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Failed";
$message5 = "Cannot Proceed to Credit Wallet";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
return $data = ["message" => $glPost["message"], "code" => $glPost["code"]];
}
}elseif(strtoupper($payload['product']) == "EQF")
{
//check for product description, registerID, ixtrac accountNumber, and set initiatedPrice
$res = container('mutualFundModel')->accountNumber($payload['fundCode'], $payload['CustID']);
$decodedRes = json_decode(json_encode($res), true);
$payload['registerID'] = $decodedRes[0]['REGISTER_ID'];
$payload['accountNumber'] = $decodedRes[0]['ACCOUNT_NUMBER'];
$payload['productDescription'] = $decodedRes[0]['DESCRIPTION'];
//fetch current fund price
$ress = container('mutualFundModel')->lastMutualFundtransactionPrice($payload['fundCode']);
$decodedRess = json_decode(json_encode($ress), true);
// $payload['initiatedPrice'] = $decodedRess['BidPrice'];
$payload['initiatedPrice'] = $decodedRess['BidPrice'];
$payload['merchantId'] = PAYSTACK_ID;
$payload['channel'] = "Virtual Account";
// $payload['admin'] = "Virtual Account";
$payload['clientId'] = $payload['CAMID'];
$payload['companyName'] = "CAM";
$payload['currency'] = "566";
$payload['productId'] = EQF_01;
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Merchant ID: " .$payload["merchantId"];
$message3 = "Product ID: " .$payload["productId"];
$message4 = "Record prepared for processing";
$message5 = "Proceed to attempt funding";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//Gl posting
$glPost = container('PaystackGatewayModel')->postMutualfundsVirtualTransaction($payload, $payload['reference'],$payload['merchantId']);
// var_dump("code is " . $glPost["code"]);
// var_dump($glPost);\
if($glPost["code"] == 200)
{
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Complete";
$message5 = "Proceeding to book Subscription";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
//process subscription
$payload['subscriptionAmount'] = $payload['amount'];
// $payload['channel'] = "bank_transfer";
$res = container('mutualFundModel')->newWebhookFundSubscription($payload);
if($res["code"] == 200){
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Subscription Status Code: " .$res["code"];
$message3 = "Subscription Status Message: " .$res["message"];
$message4 = "Subscription successful";
$message5 = "Proceed to notify RICA";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['subscriptionAmount'],
"transactionType" => "SUBSCRIPTION",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification")
->usingView('admin_rica_notify', $mail)
->send();
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "processed",
]);
return $data = ["message" => "Subscription Successful", "code" => 200];
}else{
//log event
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Subscription Status Code: " .$res["code"];
$message3 = "Subscription Status Message: " .$res["message"];
$message4 = "Subscription failed";
$message5 = "Proceed to notify RICA of Failure";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
$mail = [
"fullName" => str_replace(",","",$payload['fullName']),
"CustID" => $payload['CustID'],
"admin" => $payload['admin'],
"phoneNumber" => $payload['phoneNumber'],
"emailAddress" => $payload['emailAddress'],
"productType" => $payload['productDescription'],
"amount" => $payload['subscriptionAmount'],
"transactionType" => "SUBSCRIPTION",
"redemptionDate" => date_create($res["date_"])
];
(new Mailer())
->to(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Virtual Account Transaction Notification Failed")
->usingView('admin_rica_notify', $mail)
->send();
return $data = ["message" => "Subscription Failed", "code" => 400];
}
}else{
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$payload["transactionRef"]],
])
->update([
'status' => "failed",
]);
//log event
$message1 = "CustID: " . $payload['CustID'] .", Biz ID: " . $payload['clientId'] ;
$message2 = "Funding Status Code: " .$glPost["code"];
$message3 = "Funding Status Message: " .$glPost["message"];
$message4 = "Virtual Funding Failed";
$message5 = "Cannot Proceed to book Subscription";
$this->activity_log($message1,$message2,$message3,$message4,$message5);
return $data = ["message" => $glPost["message"], "code" => $glPost["code"]];
}
}
}
}elseif($payload['webhookType'] == "paystack_recovery")
{
// var_dump("******************************************* payload ***********************************************************");
// var_dump($payload);
//fetch success records for today and verify subscriptions were made, otherwise, create subscription
$transaction_1 = $this->retrieveTransactionDetails_1();
$transaction_1 = json_decode(json_encode($transaction_1), true);
// var_dump("got here for fund1");
foreach($transaction_1 as $trans)
{
// var_dump("got here for fund2");
// check if process is mutual fund then initiate subsription
if($trans['cash_account_id'] == FI10)
{
// var_dump("got here for fund3");
//check if subscritpion exist in local subscription table
$sub = container('mutualFundModel')->subscriptionTable()
->where([["transactionRef","=",$trans['transaction_ref']]])
->first();
// var_dump($trans['transaction_ref']);
// var_dump(count($sub));
if(count($sub) == 0)
{
//fetch fundCode
$fundCode = container('mutualFundModel')->getAFundCode($trans['cash_account_id']);
$fundCode = json_decode(json_encode($fundCode), true);
$payload['fundCode'] = $fundCode['fundCode'];
//fetch current fund price
$ress = container('mutualFundModel')->lastMutualFundtransactionPrice($payload['fundCode']);
$decodedRess = json_decode(json_encode($ress), true);
$payload['initiatedPrice'] = $decodedRess['BidPrice'];
//prepare payload
$payload['CAMID'] = $trans['client_id'];
$payload['fullName'] = $trans['fullName'];
$payload['phoneNumber'] = $trans['phoneNumber'];
$payload['subscriptionAmount'] = $trans['amount'];
$payload['CustID'] = $trans['CustID'];
$payload['emailAddress'] = $trans['emailAddress'];
$payload['transactionRef'] = $trans['transaction_ref'];
$payload['channel'] = $trans['channel'];
//trigger subscription
// var_dump("got here for fund");
$subscribe = container('mutualFundModel')->newFundSubscription($payload);
// var_dump("******************************************* subscription ***********************************************************");
// var_dump($subscribe);
$message1 = "CustID: ". $payload['CustID']. ", BIZID: " . $payload['CAMID'] . ", FullName: " . $payload['fullName'] . ", Amount: " . $payload['subscriptionAmount'] . ", Email: " . $payload['emailAddress'] . ", Phone: " . $payload['phoneNumber'];
$message2 = "Cron job call from ip address: ". $payload['ipaddress'];
$message3 = "Reference: " . $payload['transactionRef'] . ", Code: 200, Message: " . $validate["message"] . " - " . $subscribe["message"] . " - Infoware Suspense Table ID: " . $subscribe["suspense table ID"] . " - Local Subscription Table ID: " . $subscribe["localdb ID"];
$message4 = "Processing incomplete subscription process for " . $payload['fundCode'];
$message5 = "Subscription Successfully Processed..";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
}
}elseif($trans['cash_account_id'] == EQF_01)
{
// var_dump("got here for fund3");
//check if subscritpion exist in local subscription table
$sub = container('mutualFundModel')->subscriptionTable()
->where([["transactionRef","=",$trans['transaction_ref']]])
->first();
// var_dump($trans['transaction_ref']);
// var_dump(count($sub));
if(count($sub) == 0)
{
//fetch fundCode
$fundCode = container('mutualFundModel')->getAFundCode($trans['cash_account_id']);
$fundCode = json_decode(json_encode($fundCode), true);
$payload['fundCode'] = $fundCode['fundCode'];
//fetch current fund price
$ress = container('mutualFundModel')->lastMutualFundtransactionPrice($payload['fundCode']);
$decodedRess = json_decode(json_encode($ress), true);
$payload['initiatedPrice'] = $decodedRess['BidPrice'];
//prepare payload
$payload['CAMID'] = $trans['client_id'];
$payload['fullName'] = $trans['fullName'];
$payload['phoneNumber'] = $trans['phoneNumber'];
$payload['subscriptionAmount'] = $trans['amount'];
$payload['CustID'] = $trans['CustID'];
$payload['emailAddress'] = $trans['emailAddress'];
$payload['transactionRef'] = $trans['transaction_ref'];
$payload['channel'] = $trans['channel'];
//trigger subscription
// var_dump("got here for fund");
$subscribe = container('mutualFundModel')->newFundSubscription($payload);
// var_dump("******************************************* subscription ***********************************************************");
// var_dump($subscribe);
$message1 = "CustID: ". $payload['CustID']. ", BIZID: " . $payload['CAMID'] . ", FullName: " . $payload['fullName'] . ", Amount: " . $payload['subscriptionAmount'] . ", Email: " . $payload['emailAddress'] . ", Phone: " . $payload['phoneNumber'];
$message2 = "Cron job call from ip address: ". $payload['ipaddress'];
$message3 = "Reference: " . $payload['transactionRef'] . ", Code: 200, Message: " . $validate["message"] . " - " . $subscribe["message"] . " - Infoware Suspense Table ID: " . $subscribe["suspense table ID"] . " - Local Subscription Table ID: " . $subscribe["localdb ID"];
$message4 = "Processing incomplete subscription process for " . $payload['fundCode'];
$message5 = "Subscription Successfully Processed..";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
}
}
}
//fetch initialized transaction details from paystack transaction table
$transaction = $this->retrieveTransactionDetails();
$transaction = json_decode(json_encode($transaction), true);
foreach($transaction as $trans)
{
//check if Transaction time is older than 5 mins
$now = Carbon::now()->format('Y-m-d H:i:s');
$tranCreated = Carbon::parse($trans["createdDate"]);
/* if($tranCreated->diffInMinutes($now) < 1){
continue;
} */
//validate payment
$transactionId = $trans['transaction_ref'];
$paystackRef = $trans['transaction_ref'];
$merchantId = PAYSTACK_ID;
// var_dump("******************************************* paystack table records ***********************************************************");
// var_dump($trans);
$validate = container('PaystackGatewayModel')->postTransaction($transactionId, $paystackRef, $merchantId);
// var_dump("******************************************* cash posting to GL ***********************************************************");
// var_dump($validate);
if ($validate && $validate['status'] === TRUE)
{
//update record in paystack webhook log table
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$trans['transaction_ref']],
])
->update([
'status' => "processed",
]);
// check if process is mutual fund then initiate subsription
if($trans['cash_account_id'] == FI10 || $trans['cash_account_id'] == EQF_01)
{
//fetch fundCode
$fundCode = container('mutualFundModel')->getAFundCode($trans['cash_account_id']);
$fundCode = json_decode(json_encode($fundCode), true);
$payload['fundCode'] = $fundCode['fundCode'];
//fetch current fund price
$ress = container('mutualFundModel')->lastMutualFundtransactionPrice($payload['fundCode']);
$decodedRess = json_decode(json_encode($ress), true);
$payload['initiatedPrice'] = $decodedRess['BidPrice'];
//prepare payload
$payload['CAMID'] = $trans['client_id'];
$payload['fullName'] = $trans['fullName'];
$payload['phoneNumber'] = $trans['phoneNumber'];
$payload['subscriptionAmount'] = $trans['amount'];
$payload['CustID'] = $trans['CustID'];
$payload['emailAddress'] = $trans['emailAddress'];
$payload['transactionRef'] = $trans['transaction_ref'];
$payload['channel'] = $trans['channel'];
//trigger mutual fund subscription
$subscribe = container('mutualFundModel')->newFundSubscription($payload);
// var_dump("******************************************* subscription ***********************************************************");
// var_dump($subscribe);
$message1 = "CustID: ". $payload['CustID']. ", BIZID: " . $payload['CAMID'] . ", FullName: " . $payload['fullName'] . ", Amount: " . $payload['subscriptionAmount'] . ", Email: " . $payload['emailAddress'] . ", Phone: " . $payload['phoneNumber'];
$message2 = "Cron job call from ip address: ". $payload['ipaddress'];
$message3 = "Reference: " . $payload['transactionRef'] . ", Code: 200, Message: " . $validate["message"] . " - " . $subscribe["message"] . " - Infoware Suspense Table ID: " . $subscribe["suspense table ID"] . " - Local Subscription Table ID: " . $subscribe["localdb ID"];
$message4 = "Initialized Paystack Process Completed for" . $payload['fundCode'];
$message5 = "Unprocessed Mutual Fund paystack payment Successful treated..";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
}elseif($trans['cash_account_id'] == VOUCHER_CAM || $trans['cash_account_id'] == VOUCHER_CSS)
{ // check if process is voucher purchase and send voucher code via email
//prepare payload
$voucher = $this->voucherTable()->where([["transactionID","=",$trans['transaction_ref']]])->first();
$voucher = json_decode(json_encode($voucher), true);
//fetch compay name
$voucher['company'] = $trans['companyName'];
//Send email
(new Mailer())
->to($voucher["recipientEmailAddress"])
// ->bcc($voucher["accountOfficerEmail"])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Gift Voucher Notification")
->usingView('gift_voucher', $voucher)
->send();
// var_dump("******************************************* Voucher **********************************************************");
$message1 = "CustID: ". $trans['CustID'].", Voucher purhcase by " . $voucher['senderFullName'] . " for " . $voucher['recipientFullName'];
$message2 = "Cron job call from ip address: ". $payload['ipaddress'];
$message3 = $message3 = "Reference: " . $trans['transaction_ref'] . ", Code: 200, Voucher Value: ". $voucher['voucherValue'] . ", Voucher Code: ". $voucher['voucherCode'] .", Recipient Email Address: " . $voucher['recipientEmailAddress'] . ", Recipient Phone: " . $voucher['recipientPhoneNumber'];
$message4 = "Voucher Successfully Sent via Email";
$message5 = "Gift Voucher Service from ". $voucher['company'];
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
}elseif($trans['cash_account_id'] == VALUATION_STATEMENT_FEE_CAM || $trans['cash_account_id'] == VALUATION_STATEMENT_FEE_CSS)
{
//prepare payload
// $filename = $trans['transaction_ref'].".pdf";
$filename = $trans['transaction_ref'];
$directory = dirname(__DIR__, 2) . "/public_view/files/valuation_report/";
$valuation['fullName'] = $trans['fullName'];
$valuation['CustID'] = $trans['CustID'];
$valuation['emailAddress'] = $trans['emailAddress'];
// $valuation['report'] = env('IMAGE_URL')."valuation_report/{$filename}";
$valuation['report1'] = env('IMAGE_URL')."valuation_report/{$filename}_1.pdf";
// $file_pointer = '/user01/work/gfg.txt';
$file_pointer = $directory."{$filename}_2.pdf";
if (file_exists($file_pointer))
{
$valuation['count'] = 2;
$valuation['report2'] = env('IMAGE_URL')."valuation_report/{$filename}_2.pdf";
}
$valuation['company'] = $trans['companyName'];
//send email
(new Mailer())
->to($valuation['emailAddress'])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Valuation Statement Notification")
->usingView('valuation_report', $valuation)
->send();
// var_dump("******************************************* Valuation ***********************************************************");
$message1 = "CustID: ". $trans['CustID']. ", BIZID: " . $trans['client_id'] . ", FullName: " . $trans['fullName'] ;
$message2 = "Cron job call from ip address: ". $payload['ipaddress'];
$message3 = "Reference: " . $trans['transaction_ref'] . ", Code: 200, Message: " . $validate["message"] ;
$message4 = "Valuation Statement Successfully Sent via Email";
$message5 = "Valutaion Statemement Service from ". $valuation['company'];
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
}
$message1 = "CustID: ". $trans['CustID']. ", BIZID: " . $trans['client_id'] . ", FullName: " . $trans['fullName'] . ", Amount: " . $trans['amount'] . ", Email: " . $trans['emailAddress'] . ", Phone: " . $trans['phoneNumber'];
$message2 = "Cron job call from ip address: ". $payload['ipaddress'];
$message3 = "Reference: " . $trans['transaction_ref'] . ", Code: 200, Status: ". $validate['message'];
$message4 = "Initialized Paystack Process Completed";
$message5 = "Cron Job for Paystack Payment Successful...";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
}else{
$this->paystackWebhookLogTable()
->where([
["transactionRef","=",$trans['transaction_ref']],
])
->update([
'status' => "failed",
]);
//log event
$message1 = "CustID: ". $trans['CustID']. ", BIZID: " . $trans['client_id'] . ", FullName: " . $trans['fullName'] . ", Amount: " . $trans['amount'] . ", Email: " . $trans['emailAddress'] . ", Phone: " . $trans['phoneNumber'];
$message2 = "Cron job call from ip address: ". $payload['ipaddress'];
$message3 = "Reference: " . $trans['transaction_ref'] . ", Code: 400, Status: Payment Failed";
$message4 = "Initialized Paystack Process Unsuccessful";
$message5 = "Unprocessed Paystack Payment Failed..";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
}
}
return ["code" => 200, "message" => "Paystack Recovery Webhook Successfully Processed"];
}elseif($payload['webhookType'] == "customerIdentification")
{
//insert payment details into paystack webhook log table
$this->paystackWebhookLogTable()
->insertGetId([
'emailAddress' => $payload["email"],
'accountNumber' => $payload["idType"],
'reference' => $payload["idValue"],
'channel' => $payload["webhookType"],
'event' => $payload["event"],
'status' => 'processed',
'customerCode' => $payload["customerCode"],
"ipAddress" => $payload["ipaddress"],
]);
//update nuban table with verified ID type and value
$update = $this->nubanTable()
->where([["customerCode", "=", $payload['customerCode']],
["idType", "=", null],
["idValue", "=", null],
])
->update([
'idType' => $payload['idType'],
'idValue' => $payload['idValue'],
]);
//fetch CustID from NUBAN table
$nuban = $this->getNubanforWebhook_1($payload);
if(count($nuban) > 0)
{
$decodedNuban = json_decode(json_encode($nuban), true);
$payload += $decodedNuban;
//proceed to create customer nuban account
$create = $this->createNubanAccount($payload);
return $data = ["message" => "Customer Verification Update Successful", "code" => 200];
}else{
return $data = ["message" => "Customer Verification Update Failed", "code" => 400];
}
}elseif($payload['webhookType'] == "transfer")
{
//Notify FINCON and RICA of payment failure
$msg = "Wallet Transfer Failure - " .$payload["accountName"] . ", " .$payload["accountNumber"] . ", " .$payload["bankName"] . ", N" .$payload["amount"] . ", " .$payload["transferCode"] . ", " .$payload["recipientCode"] . ", " .$payload["reason"];
$record = [
"accountName" => $payload["accountName"],
"accountNumber" => $payload["accountNumber"],
"bankName" => $payload["bankName"],
"amount" => $payload["amount"],
"transferCode" => $payload["transferCode"],
"recipientCode" =>$payload["recipientCode"],
"business" => "CAM",
"reason" => $payload['reason'],
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Failed Wallet Payout - Client Wallet Already Debited")
->usingView('failed_wallet_transfer_notification', $record)
->send();
return $data = ["message" => "Successfully notified FINCON and RICA", "code" => 200];
}elseif($payload['webhookType'] == "paystack_log"){
//just log record in paystack webhook log table
//insert payment details into paystack webhook log table
$this->paystackWebhookLogTable()
->insertGetId([
'transactionRef' => $payload["transactionRef"],
'reference' => $payload["reference"],
'fullName' => strtoupper($payload["fullName"]),
'accountNumber' => $payload["virtualAccountNumber"],
'paymentDetails' => $payload["cardDetails"],
'bankName' => $payload["bank"],
'channel' => $payload["channel"],
'phoneNumber' => $payload["phoneNumber"],
'emailAddress' => $payload["emailAddress"],
'event' => $payload["event"],
'status' => ( strtolower($payload["event"]) == "transfer.success") ? 'processed' : 'pending',
'customerCode' => $payload["customerCode"],
'actualAmount' => abs($payload['amount']),
'currency' => "NGN",
"ipAddress" => $payload["ipaddress"],
]);
return $data = ["message" => "Webhook data Successfully logged", "code" => 200];
}
}
/**
* Fetch details of a NUBAN customer record on our DB using customer code and bank details for webhook event
*/
public function getNubanforWebhook($payload) //create new fund
{
$nuban = $this->nubanTable()
->where([
["customerCode", "=", $payload['customerCode'] ],
["accountNumber", "=", $payload['virtualAccountNumber'] ],
["bankName", "=", $payload['bank'] ],
])->first();
return $nuban ?? [];
}
/**
* Fetch details of a NUBAN customer record on our DB using customer code only for webhook event to create account
*/
public function getNubanforWebhook_1($payload) //create new fund
{
$nuban = $this->nubanTable()
->where([
["customerCode", "=", $payload['customerCode'] ],
["accountNumber", "=", null],
["bankName", "=", null],
])->first();
return $nuban ?? [];
}
/**
* create a NUBAN customer record on our DB
*/
public function createNubanCustomer($payload) //create new fund
{
//check if customer has product involvement
$load["CustID"] = $payload["CustID"];
$BIZID = $payload["CAMID"];
$load["businessInvolvement"] = $DB = CAM_DB_NAME;
//get Involvement Type and company
$nubanProduct = $this->getNubanProduct(strtoupper($payload["product"]));
$payload['company'] = $nubanProduct->company;
$load["involvementType"] = $INVOLVEMENT = $nubanProduct->involvementType;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) != "TRUE")
{
$create = $this->createInvolvement($load);
if(!isset($payload["CAMID"]) || empty($payload["CAMID"]) || is_null($payload["CAMID"]) || $payload["CAMID"] == "")
{
$payload["CAMID"] = $create["BIZID"];
}
}
//check if kyc is complete
$kyc = $this->checkIfcustomerKYCIsComplete($payload["CustID"], MIDDLEWARE_DB_NAME)[0];
//get other middleware info
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload["CustID"], MIDDLEWARE_DB_NAME))['data'];
$payload['BVNMiddleName'] = str_replace(",","",$customers[0]['BVNMiddleName']);
$payload['BVNFirstName'] = str_replace(","," ",trim($customers[0]['BVNFirstName']));
$payload['BVNLastName'] = str_replace(","," ",trim($customers[0]['BVNLastName']));
$payload['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
//get BVN from bank details
$bank = $this->getCustomerBankDetails($payload["CustID"])[0];
if(count($bank) > 0 && strtoupper($kyc['IsKYC']) == "TRUE")
{
$payload['accountNumber'] = $bank['AcctNumber'];
$payload['bankCode'] = $bank['SortCode'];
if(is_null($payload['bankCode']) || empty($payload['bankCode']) || $payload['bankCode'] == "")
{
$icode = $this->bankCode($bank['BankName']);
$payload['bankCode'] = $icode->iCode;
}
$payload['bankName'] = $bank['BankName'];
$payload['BVN'] = (isset($payload['BVN']) && !is_null($payload['BVN']) && !empty($payload['BVN']) && $payload['BVN'] != "") ? $payload['BVN'] : $bank['BVN'];
$payload['idType'] = "bvn";
// $payload['idValue'] = $bank["BVN"]; -- to be restored in prod for account validation
//to be disabled on prod to enable account validation
// $payload['idValue'] = "22222222298";
// $payload['firstName'] = "Uchenna";
// $payload['lastName'] = "Okoro";
$payload['idValue'] = $payload['BVN'];
}else{
return [
"message" => "Bank details must be provided and KYC approved to proceed",
"code" => 400,
];
}
$result = $this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["fundCode", "=", $payload['fundCode'] ],
["CustID", "=", $payload['CustID'] ],
])->get();
if(!empty($result) && count($result) != 0 && !is_null($result[0]->accountName) && !is_null($result[0]->accountNumber))
{
$responseData = "Virtal account already exists";
return [
"message" => $responseData,
"code" => 200,
"data" => $result ?? []
];
// }elseif(!empty($result) && count($result) != 0 && is_null($result[0]->accountName) && is_null($result[0]->accountNumber))
}elseif(!empty($result) && count($result) != 0 && (is_null($result[0]->accountName) || is_null($result[0]->accountNumber)))
{
$this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["fundCode", "=", $payload['fundCode'] ],
["CustID", "=", $payload['CustID'] ],
])->update([
'description' => $payload['description'],
'idType' => "bvn",
'idValue' => $payload['BVN'] ?? 0,
]);
$payload['customerCode'] = $result[0]->customerCode;
$responseData = "Virtual Account Creation in Progress";
}else{
// create NUBAN customer
$res = container('PaystackRequest')->createNubanCustomer($payload, $payload['product']);
if($res['status'] == true)
{
$this->id = $this->nubanTable()
->insertGetId([
'CustID' => $payload['CustID'],
'SECID' => $payload['SECID'],
'CAMID' => $payload['CAMID'],
'ASSETID' => $payload['ASSETID'],
'firstName' => $payload['firstName'],
'middleName' => $payload['middleName'],
'lastName' => $payload['lastName'],
'fullName' => $payload['fullName'],
'BVNFirstName' => $payload['BVNFirstName'],
'BVNLastName' => $payload['BVNLastName'],
'BVNMiddleName' => $payload['BVNMiddleName'],
'customerCode' => $res['data']['customer_code'],
'emailAddress' => $payload['emailAddress'],
'phoneNumber' => $payload['phoneNumber'],
'product' => $payload['fundCode'],
'description' => $payload['description'],
'fundCode' => $payload['fundCode'],
'company' => $payload['company'],
'idType' => "bvn",
'idValue' => $payload['BVN'],
'paystackCustomerID' => $res['data']['id'],
'riskAction' => $res['data']['risk_action'],
'integration' => $res['data']['integration'],
]);
$payload['customerCode'] = $res['data']['customer_code'];
}
$responseData = $res['message'];
}
//trigger customer validation
$this->validateNubanCustomer($payload);
//attempt to create nuban account
$this->createNubanAccount($payload);
$result = $this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["fundCode", "=", $payload['fundCode'] ],
["CustID", "=", $payload['CustID'] ],
])->get();
return [
"message" => $responseData,
"code" => 200,
"data" => $result ?? []
];
}
/**
* Get a NUBAN customer record on our DB
*/
public function getNubanCustomer($payload) //create new fund
{
$result = $this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["CustID", "=", $payload['CustID'] ],
])->get();
if(!is_null($result) && !empty($result) && count($result) != 0 && $result != "")
{
$responseData = "NUBAN customer successfully retreived";
}elseif((!empty($result) && !is_null($result) && count($result) != 0 && $result != "" ) && (!is_null($result[0]->customerCode)&& !empty($result[0]->customerCode)&& $result[0]->customerCode != "")){
$res = container('PaystackRequest')->getNubanCustomer($result[0]->customerCode ,$payload['product']);
if($res['status'] == true)
{
$this->nubanTable()
->where([
["customerCode", "=", $result[0]->customerCode ],
["product", "=", $payload['product'] ],
["CustID", "=", $payload['CustID'] ],
])->update([
'customerCode' => $result['data']['customer_code'],
'paystackCustomerID' => $result['data']['id'],
'riskAction' => $result['data']['risk_action'],
'integration' => $result['data']['integration'],
]);
}
$responseData = $res['message'];
return [
"message" => $responseData,
"data" => $res ?? []
];
}else{
$responseData = "NUBAN customer does not exist";
}
return [
"message" => $responseData,
"data" => $result ?? []
];
}
/**
* create a NUBAN Account and update NUBAN Customer on our DB
*/
public function createNubanAccount($payload) //create new fund
{
$result = $this->nubanTable()
->where([
["customerCode", "=", $payload['customerCode'] ],
["product", "=", $payload['product'] ],
["CustID", "=", $payload['CustID'] ],
])->get();
if((!empty($result) && count($result) != 0) && (!is_null($result[0]->nubanAccountID)&& $result[0]->nubanAccountID != ""))
{
$responseData = "Virtal account already exists";
}else{
//create NUBAN account
$res = container('PaystackRequest')->createNubanAccount($payload['customerCode'], $payload['product']);
if($res['status'] == true)
{
$this->nubanTable()
->where([
["customerCode", "=", $payload['customerCode'] ],
["product", "=", $payload['product'] ],
["CustID", "=", $payload['CustID'] ],
])->update([
"accountName" => $res['data']['account_name'],
"accountNumber" => $res['data']['account_number'],
"bankName" => $res['data']['bank']['name'],
"bankSlug" => $res['data']['bank']['slug'],
"currency" =>$res['data']['currency'],
"bankID" =>$res['data']['bank']['id'],
"nubanAccountID" =>$res['data']['id'],
]);
//add virtual account to clients bank list if product is wallet
if(strtoupper($payload['product']) == "CSWALLET")
{
//{$CustID}|{$bankAcctName}|{$bankCode}|{$bankAcctNumber}|{$sortCode}|{$BVNNumber}
$bankInfo = $this->bankCode($res['data']['bank']['name']);
$payload['bankAcctName'] = $res['data']['account_name'];
$payload['bankCode'] = $bankInfo->bankCode;
$payload['bankAcctNumber'] = $res['data']['account_number'];
$payload['sortCode'] = $bankInfo->iCode;
$payload['BVNNumber'] = $result[0]->idValue;
$addBank = formatIWRes(container('IWSRequest')->addBankAccount($payload))["data"];
}
//check if customer exist in transfer client table
$rez = $this->transferTable()
->where([
["CustID", "=", $payload['CustID'] ],
])->get();
//check if product is CS Wallet and create transfer recipient for withdrawal purpose
if(strtoupper($payload['product']) == "CSWALLET" && count($rez) == 0)
{
//get bank details
$bank = $this->getCustomerBankDetails($payload["CustID"])[0];
if(count($bank) > 0)
{
$payload['accountNumber'] = $bank['AcctNumber'];
$payload['bankCode'] = $bank['SortCode'];
if(is_null($payload['bankCode']) || empty($payload['bankCode']) || $payload['bankCode'] == "")
{
$icode = $this->bankCode($bank['BankName']);
$payload['bankCode'] = $icode->iCode;
}
$payload['bankName'] = $bank['BankName'];
$payload['BVN'] = (isset($payload['BVN']) && !is_null($payload['BVN']) && !empty($payload['BVN']) && $payload['BVN'] != "") ? $payload['BVN'] : $bank['BVN'];
//verify bank account number
$verify = container('PaystackRequest')->resolveBankAccount($payload);
if($verify["status"] == true)
{
$transferClient = $this->transferTable()
->insertGetId([
'CustID' => $payload['CustID'],
'SECID' => $payload['SECID'],
'CAMID' => $payload['CAMID'],
'ASSETID' => $payload['ASSETID'],
'fullName' => $payload['fullName'],
'firstName' => $payload['firstName'],
'lastName' => $payload['lastName'],
'emailAddress' => $payload['emailAddress'],
'phoneNumber' => $payload['phoneNumber'],
'accountName' => $verify["data"]['account_name'],
'accountNumber' => $verify["data"]['account_number'],
'customerCode' => $payload['customerCode'],
'bankName' => $payload['BankName'],
'bankCode' => $payload['bankCode'],
'idType' => "bvn",
'idValue' => $payload['BVN'],
'fundCode' => $payload['fundCode'],
'company' => $payload['company'],
'integration' => $payload['integration'],
'product' => $payload['product'],
'currency' => "NGN",
]);
//Update transfer client with recipient code
$recipientCode = container('PaystackRequest')->createTransferRecipient($payload);
if($recipientCode["status"] == true)
{
$recipientCode = $this->transferTable()
->where([
["customerCode", "=", $payload['customerCode']],
["CustID", "=", $payload['CustID'] ],
])
->update([
"recipientCode" => $recipientCode["data"]['recipient_code'],
]);
}
}
}
}
//send nuban creation notification
$record = [
"fullName" => str_replace(",","",$result[0]->fullName),
"nuban" => $res['data']['account_number'] ,
"bank" => $res['data']['bank']['name'],
"product" => $result[0]->description,
"emailAddress" => $result[0]->emailAddress,
"customerCode" => $result[0]->customerCode,
"accountName" => $res['data']['account_name'],
];
// var_dump($record);
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
// ->bcc("[email protected]")
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("NUBAN Creation Notification for ". $result[0]->description)
->usingView('nuban_account_notification', $record)
->send();
}else{
(new Mailer())
->to($result[0]->emailAddress)
// ->bcc("[email protected]")
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("NUBAN Creation Notification for ". $result[0]->description)
->usingView('nuban_account_notification', $record)
->send();
}
}
$responseData = $res['message'];
return [
"message" => $responseData,
"data" => $res ?? []
];
}
return [
"message" => $responseData,
"data" => $result ?? []
];
}
/**
* create business and product involvement
*/
public function createInvolvement($payload) //create new fund
{
$lockKey = "lock:involvement:" . $payload['CustID'];
$lockTimeout = 60 * 5; // Lock timeout in seconds, adjust as needed
try
{
$cache = container('cache')->fetch($lockKey);
if($cache === false)
{
acquireLock($lockKey, $lockTimeout);
}
else {
return ["code" => 423, "message" => "Please hold off for a bit before retrying. Thank you for your patience!"];
}
$payload['company'] = $payload['businessInvolvement'];
$customerDetails = $this->verifyBusinessCode($payload);
if($customerDetails['code'] && $customerDetails['data'] == true)
{
return ["code" => 400, "message" => "Business involvement already exist"];
}
//get Middleware details
$decoded_data = formatIWRes(container('IWSRequest')->getUserDetailsFromMiddleware(MIDDLEWARE_DB_NAME, $payload['CustID']));
if(strtoupper($decoded_data['data'][0]['ClientType']) == "IND"){
$payload = $payload + [
"Title" => $decoded_data['data'][0]["Title"],
"firstName" => $decoded_data['data'][0]["FirstName"],
"lastName" => $decoded_data['data'][0]["LastName"],
"otherNames" =>$decoded_data['data'][0]["MiddleName"],
"gender" => $decoded_data['data'][0]["Gender"],
"compName" =>$decoded_data['data'][0]["Name"],
"maidenName" =>$decoded_data['data'][0]["Maiden Name"],
"accountType" =>$decoded_data['data'][0]["ClientType"],
"city" => $decoded_data['data'][0]["City"],
"country" => $decoded_data['data'][0]["Country"],
"dateOfBirth" => $decoded_data['data'][0]["Birthday"],
"address" => $decoded_data['data'][0]["Address1"],
"state" => $decoded_data['data'][0]["State"],
"emailAddress" => $decoded_data['data'][0]["Email1"],
"phoneNumber" => $decoded_data['data'][0]["Phone1"],
"occupation" => $decoded_data['data'][0]["Occupation"],
"bankAcctName" => $decoded_data['data'][0]["Bank_Acct_Name"],
"bankAcctNumber" => $decoded_data['data'][0]["Bank_Acct_No"],
"bankName" => $decoded_data['data'][0]["Bank_Name"],
"bankCode" => $decoded_data['data'][0]["bankCode"],
"BVNNumber" => $decoded_data['data'][0]['BVN'],
"beneficiaryName" => $decoded_data['data'][0]["Beneficiary Name"],
"beneficiaryAcctNo" => $decoded_data['data'][0]["Beneficiary Account No"],
"beneficiaryBankName" => $decoded_data['data'][0]["Beneficiary Bank"],
"beneficiaryBankAddress" => $decoded_data['data'][0]["Beneficiary Bank Address"],
"correspondentAcctNo" => $decoded_data['data'][0]["Correspondent Bank Acct No"],
"nextOfKin" => $decoded_data['data'][0]["Next of Kin Name"],
"nextOfKinPhone" => $decoded_data['data'][0]["Next of Kin Phone No"],
"nextOfKinEmail" => $decoded_data['data'][0]["Next of Kin Email Address"],
"nextOfKinAddress" => $decoded_data['data'][0]["Next of Kin Contact Address"],
"nextOfKinGender" => $decoded_data['data'][0]["Next of Kin Gender"],
"nextOfKinDOB" => $decoded_data['data'][0]["Next of Kin Date of Birth"],
"nextOfKinRelationship" => $decoded_data['data'][0]["Next of Kin Relationship"],
"identityType" => $decoded_data['data'][0]["Means of ID"],
"identityNumber" => $decoded_data['data'][0]["ID Number"],
"identityExpiryDate" => $decoded_data['data'][0]["Means of ID Expiration Date"],
"employerName" => $decoded_data['data'][0]["Employer"],
"employerNo" => $decoded_data['data'][0]["Employer Phone"],
"employerAddress" => $decoded_data['data'][0]["Employer_Address"],
"sortCode" => $decoded_data['data'][0]["Sort Code"],
"RCNo" => $decoded_data['data'][0]["RCNO"],
"swiftCode" => $decoded_data['data'][0]["Swift_ABA Code"],
"taxID" => $decoded_data['data'][0]["TaxID"],
"previousCHN" => $decoded_data['data'][0]["PreviousCHN"],
"correspondentBankName" => $decoded_data['data'][0]["Correspondent Bank"],
"primaryContactName" => $decoded_data['data'][0]["Primary Contact Name"],
"primaryContactEmail" => $decoded_data['data'][0]["Primary Contact Email"],
"primaryContactPhone" => $decoded_data['data'][0]["Primary Contact Phone"],
"primaryContactAddress" => $decoded_data['data'][0]["Primary Contact Address"],
"primaryContactGender" => $decoded_data['data'][0]["Primary Contact Gender"],
"primaryContactDesignation" => $decoded_data['data'][0]["Primary Contact Designation"],
"secondaryContactName" => $decoded_data['data'][0]["Secondary Contact Name"],
"secondaryContactEmail" => $decoded_data['data'][0]["Secondary Contact Email"],
"secondaryContactPhone" => $decoded_data['data'][0]["Secondary Contact Phone"],
"secondaryContactAddress" => $decoded_data['data'][0]["Secondary Contact Address"],
"secondaryContactGender" => $decoded_data['data'][0]["Secondary Contact Gender"],
"secondaryContactDesignation" => $decoded_data['data'][0]["Secondary Contact Designation"],
"SECID" => $decoded_data['data'][0]["SECID"],
"ASSETID" => $decoded_data['data'][0]["ASSETID"],
"CAMID" => $decoded_data['data'][0]["CAMID"],
"CSS" => $decoded_data['data'][0]["CSS"],
"CAM" => $decoded_data['data'][0]["CAM"],
"CSP" => $decoded_data['data'][0]["CSP"],
"CSA" => $decoded_data['data'][0]["CSA"],
"CST" => $decoded_data['data'][0]["CST"],
"CSRL" => $decoded_data['data'][0]["CSRL"],
"TROVE" => $decoded_data['data'][0]["TROVE"],
"MF" => $decoded_data['data'][0]["MF"],
"SMA" => $decoded_data['data'][0]["SMA"],
];
}else{
$payload = $payload + [
"Title" => $decoded_data['data'][0]["Title"],
"firstName" => $decoded_data['data'][0]["FirstName"],
"lastName" => $decoded_data['data'][0]["Name"],
"otherNames" =>$decoded_data['data'][0]["MiddleName"],
"gender" => "X",
"compName" =>$decoded_data['data'][0]["Name"],
"maidenName" =>$decoded_data['data'][0]["Maiden Name"],
"accountType" =>$decoded_data['data'][0]["ClientType"],
"city" => $decoded_data['data'][0]["City"],
"country" => $decoded_data['data'][0]["Country"],
"dateOfBirth" => $decoded_data['data'][0]["Date of Incorporation"],
"address" => $decoded_data['data'][0]["Address1"],
"state" => $decoded_data['data'][0]["State"],
"emailAddress" => $decoded_data['data'][0]["Email1"],
"phoneNumber" => $decoded_data['data'][0]["Phone1"],
"occupation" => $decoded_data['data'][0]["Occupation"],
"bankAcctName" => $decoded_data['data'][0]["Bank_Acct_Name"],
"bankAcctNumber" => $decoded_data['data'][0]["Bank_Acct_No"],
"bankName" => $decoded_data['data'][0]["Bank_Name"],
"bankCode" => $decoded_data['data'][0]["bankCode"],
"BVNNumber" => $decoded_data['data'][0]['BVN'],
"beneficiaryName" => $decoded_data['data'][0]["Beneficiary Name"],
"beneficiaryAcctNo" => $decoded_data['data'][0]["Beneficiary Account No"],
"beneficiaryBankName" => $decoded_data['data'][0]["Beneficiary Bank"],
"beneficiaryBankAddress" => $decoded_data['data'][0]["Beneficiary Bank Address"],
"correspondentAcctNo" => $decoded_data['data'][0]["Correspondent Bank Acct No"],
"nextOfKin" => $decoded_data['data'][0]["Next of Kin Name"],
"nextOfKinPhone" => $decoded_data['data'][0]["Next of Kin Phone No"],
"nextOfKinEmail" => $decoded_data['data'][0]["Next of Kin Email Address"],
"nextOfKinAddress" => $decoded_data['data'][0]["Next of Kin Contact Address"],
"nextOfKinGender" => $decoded_data['data'][0]["Next of Kin Gender"],
"nextOfKinDOB" => $decoded_data['data'][0]["Next of Kin Date of Birth"],
"nextOfKinRelationship" => $decoded_data['data'][0]["Next of Kin Relationship"],
"identityType" => $decoded_data['data'][0]["Means of ID"],
"identityNumber" => $decoded_data['data'][0]["ID Number"],
"identityExpiryDate" => $decoded_data['data'][0]["Means of ID Expiration Date"],
"employerName" => $decoded_data['data'][0]["Employer"],
"employerNo" => $decoded_data['data'][0]["Employer Phone"],
"employerAddress" => $decoded_data['data'][0]["Employer_Address"],
"sortCode" => $decoded_data['data'][0]["Sort Code"],
"RCNo" => $decoded_data['data'][0]["RCNO"],
"incorporationDate" => $decoded_data['data'][0]["Date of Incorporation"],
"swiftCode" => $decoded_data['data'][0]["Swift_ABA Code"],
"taxID" => $decoded_data['data'][0]["TaxID"],
"previousCHN" => $decoded_data['data'][0]["PreviousCHN"],
"correspondentBankName" => $decoded_data['data'][0]["Correspondent Bank"],
"primaryContactName" => $decoded_data['data'][0]["Primary Contact Name"],
"primaryContactEmail" => $decoded_data['data'][0]["Primary Contact Email"],
"primaryContactPhone" => $decoded_data['data'][0]["Primary Contact Phone"],
"primaryContactAddress" => $decoded_data['data'][0]["Primary Contact Address"],
"primaryContactGender" => $decoded_data['data'][0]["Primary Contact Gender"],
"primaryContactDesignation" => $decoded_data['data'][0]["Primary Contact Designation"],
"secondaryContactName" => $decoded_data['data'][0]["Secondary Contact Name"],
"secondaryContactEmail" => $decoded_data['data'][0]["Secondary Contact Email"],
"secondaryContactPhone" => $decoded_data['data'][0]["Secondary Contact Phone"],
"secondaryContactAddress" => $decoded_data['data'][0]["Secondary Contact Address"],
"secondaryContactGender" => $decoded_data['data'][0]["Secondary Contact Gender"],
"secondaryContactDesignation" => $decoded_data['data'][0]["Secondary Contact Designation"],
"SECID" => $decoded_data['data'][0]["SECID"],
"ASSETID" => $decoded_data['data'][0]["ASSETID"],
"CAMID" => $decoded_data['data'][0]["CAMID"],
"CSS" => $decoded_data['data'][0]["CSS"],
"CAM" => $decoded_data['data'][0]["CAM"],
"CSP" => $decoded_data['data'][0]["CSP"],
"CSA" => $decoded_data['data'][0]["CSA"],
"CST" => $decoded_data['data'][0]["CST"],
"CSRL" => $decoded_data['data'][0]["CSRL"],
"TROVE" => $decoded_data['data'][0]["TROVE"],
"MF" => $decoded_data['data'][0]["MF"],
"SMA" => $decoded_data['data'][0]["SMA"],
];
}
//intialize BIZID based on the business and involvement of interest
if(strtoupper($payload['businessInvolvement']) == strtoupper(ASSETMGMT_DB_NAME)){
$payload['BIZID'] = $payload['ASSETID'];
// $payload['CSP'] = 1;
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(STOCKBROKING_DB_NAME)){
$payload['BIZID'] = $payload['SECID'];
// $payload['CSS'] = 1;
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(CAM_DB_NAME)){
$payload['BIZID'] = $payload['CAMID'];
// $payload['CAM'] = 1;
}
//get bankCode from bankName
//if($payload['bankName'] == "" || is_null($payload['bankName']) ){
if($payload['bankCode'] == "" || is_null($payload['bankCode']) ){
$bankCode = container('mutualFundModel')->bankCode($payload['bankName']);
$payload['bankCode'] = $bankCode->bankCode;
}
//if user doesn't exist in the desired business, create user in desired business
if((is_null($payload['BIZID']) || empty($payload['BIZID']) || $payload['BIZID'] == "") && strtoupper($payload['businessInvolvement']) != "CSRL" && strtoupper($payload['businessInvolvement']) != "CSA")
{
$strt = formatIWRes(container('IWSRequest')->startCreateCustomerAccount($payload, $payload['businessInvolvement'])); //first level account creation on CAM
if($strt["StatusID"] == 0 && !is_null($strt["StatusID"]))
{
$payload['BIZID'] = $strt['OutValue']; //Obtain created BIZID
$strtDecoded = json_decode(json_encode($strt));
//update business ID with created ID
if(strtoupper($payload['businessInvolvement']) == strtoupper(ASSETMGMT_DB_NAME)){
$payload['ASSETID'] = $payload['BIZID'];
$payload['CSP'] = 1;
$BIZ = "CSP";
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(STOCKBROKING_DB_NAME)){
$payload['SECID'] = $payload['BIZID'];
$payload['CSS'] = 1;
$BIZ = "CSS";
}elseif(strtoupper($payload['businessInvolvement']) == strtoupper(CAM_DB_NAME)){
$payload['CAMID'] = $payload['BIZID'];
$payload['CAM'] = 1;
$BIZ = "CAM1";
}
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['compName'], "Status ID: " . $strtDecoded->StatusID . ", Out Value: " . $strtDecoded->OutValue, "Status Message is " .$strtDecoded->StatusMessage . " and Account created on " . $payload['businessInvolvement'] . " with CustAID " .$strtDecoded->OutValue, "New Account Creation");
$BIZID = $payload['BIZID'];
$comp = formatIWRes(container('IWSRequest')->completeCreateCustomerAccount($payload, $payload['businessInvolvement'], $BIZID)); //second level account creation on CAM
$compDecoded = json_decode(json_encode($comp));
if($comp["StatusID"] == 0 && !is_null($comp["StatusID"]))
{
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['compName'], "Status ID: " . $compDecoded->StatusID . ", Out Value: " . $compDecoded->OutValue, "Status Message is " .$compDecoded->StatusMessage, "Infoware Custom Attribute updated for " . $payload['BIZID']);
//return all business IDs to Middleware
$merge = formatIWRes(container('IWSRequest')->UpdateCustomerAccountIDToMiddleware($payload['CustID'], $payload['ASSETID'], $payload['SECID'], $payload['CAMID']));
// $merge = formatIWRes(container('IWSRequest')->MergeCustomerAccountIDToMiddleware($payload['CustID'], $payload['ASSETID'], $payload['SECID'], $payload['CAMID']));
$mergeDecoded = json_decode(json_encode($merge));
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['compName'], "ASSETID: " .$payload['ASSETID'] . ", SECID: " . $payload['SECID'] . ", CAMID: " . $payload['CAMID'] , "Status Message is " .$mergeDecoded->StatusMessage, "Infoware Middleware IDs merged for exisitng client");
}else{
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['compName'], "ASSETID: " .$payload['ASSETID'] . ", SECID: " . $payload['SECID'] . ", CAMID: " . $payload['CAMID'] , "Status Message is " .$mergeDecoded->StatusMessage, "completeCreateCustomerAccount failed");
return (["code" => 400, "message" => "unable to create involvement."]);
}
}else{
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['compName'], "ASSETID: " .$payload['ASSETID'] . ", SECID: " . $payload['SECID'] . ", CAMID: " . $payload['CAMID'] , "Status Message is " .$mergeDecoded->StatusMessage, "startCreateCustomerAccount failed");
return (["code" => 400, "message" => "unable to create involvement."]);
}
}
//check if involvementType is provided, else stop at business involvement creation
if(!is_null($payload['involvementType']) && !empty($payload['involvementType']) && $payload['involvementType'] != "" && strtoupper($payload['businessInvolvement']) != "CSRL" && strtoupper($payload['businessInvolvement']) != "CSA")
{
//Create mutual funds involvements
$result = formatIWRes(container('IWSRequest')->createInvolvement($payload));
$resultDecoded = json_decode(json_encode($result));
//var_dump("status id is ".$result["StatusID"]);
if($result["StatusID"] == 0)
{
//log Infoware response
$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['compName'], "StatusID: " .$result["StatusID"] ."ASSETID: " .$payload['ASSETID'] . ", SECID: " . $payload['SECID'] . ", CAMID: " . $payload['CAMID'] , "Status Message is " .$resultDecoded->StatusMessage, "Infoware involvement created for " .$payload['involvementType']);
//update buziness code to middleware
if($payload['involvementType'] == "CSPFI")
{
$payload['MF'] = 1;
$BIZ = "MF";
}elseif($payload['involvementType'] == "STK")
{
$payload['CSS'] = 1;
$BIZ = "CSS";
}elseif($payload['involvementType'] == "CAM")
{
$payload['CAM'] = 1;
$BIZ = "CAM1";
}elseif($payload['involvementType'] == "TROVE")
{
$payload['TROVE'] = 1;
$BIZ = "TROVE";
}elseif($payload['involvementType'] == "SMA-CAM")
{
$payload['SMA'] = 1;
$BIZ = "SMA";
}
// $updateBizCode = formatIWRes(container('IWSRequest')->updateBusinessCodeToMiddleware($payload['CustID'], $payload['CSS'], $payload['CAM'], $payload['CSP'], $payload['CST'], $payload['CSA'], $payload['CSRL'], $payload['TROVE'], $payload['MF'], $payload['SMA'], $payload['SOF']));
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], $BIZ));
return (["code" => 200, "message" => "Product Involvement successfully created", "BIZID" => $payload['BIZID']]);
}else{
//log failure involvement creation response
$log = $this->activity_log("Middleware ID: " . $payload['CustID'], $payload['compName'], "StatusID: " .$result["StatusID"] ."ASSETID: " .$payload['ASSETID'] . ", SECID: " . $payload['SECID'] . ", CAMID: " . $payload['CAMID'] , "Status Message is " .$resultDecoded->StatusMessage, "Infoware involvement creation failed for " .$payload['involvementType']);
return (["code" => 400, "message" => "unable to create involvement.."]);
}
}elseif(strtoupper($payload['businessInvolvement']) == "CSRL")
{
//pass client kyc details to shareholders local db
$payload["chn"] = $this->getCSCSNumber($payload)['data']['CsCsReg#'];
$createCSRLShareholder = container('IWSRequest')->createCSRLShareholder($payload);
if($createCSRLShareholder != 400)
{
//update buziness code to middleware
$BIZ = "CSRL";
// $payload['CSRL'] = 1;
// $updateBizCode = formatIWRes(container('IWSRequest')->updateBusinessCodeToMiddleware($payload['CustID'], $payload['CSS'], $payload['CAM'], $payload['CSP'], $payload['CST'], $payload['CSA'], $payload['CSRL'], $payload['TROVE'], $payload['MF'], $payload['SMA'], $payload['SOF']));
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], $BIZ));
return (["code" => 200, "message" => "External Product (CSRL) Involvement successfully created", "CustID" => $payload['CustID']]);
}else{
return (["code" => 400, "message" => "Involvement creation failed, please contact us", "CustID" => $payload['CustID']]);
}
}elseif(strtoupper($payload['businessInvolvement']) == "CSA")
{
//update buziness code to middleware
// $payload['CSA'] = 1;
$BIZ = "CSA";
// $updateBizCode = formatIWRes(container('IWSRequest')->updateBusinessCodeToMiddleware($payload['CustID'], $payload['CSS'], $payload['CAM'], $payload['CSP'], $payload['CST'], $payload['CSA'], $payload['CSRL'], $payload['TROVE'], $payload['MF'], $payload['SMA'], $payload['SOF']));
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], $BIZ));
//pass client kyc details to CS Advance local db
return (["code" => 200, "message" => "External Product (CS Advance) Involvement successfully created", "CustID" => $payload['CustID']]);
}else{
return (["code" => 200, "message" => "Product Involvement was not initiated, however, Business Involvement successfully created", "BIZID" => $payload['BIZID']]);
}
}catch(\Exception $e){
return ["code" => 500, "message" => "An error occurred: " . $e->getMessage()];
}finally{
// releaseLock($lockKey);
}
}
/**
* Get all cash accounts...
*/
public function getCashAccounts() //create new fund
{
$cashAccount = $this->cashAccountTable()->get();
return $cashAccount ?? [];
}
/**
* Get specific cash accounts...
*/
public function getCashAccount($payload) //create new fund
{
$cashAccount = $this->cashAccountTable()
->where([["accountOpeningProduct","=",strtoupper($payload["accountOpeningProduct"])],
["ledgerType","=", "NGN"],
])
->first();
if(count($cashAccount) > 0)
{
return ['code'=> 200, 'message' => 'Cash Account Fetched', 'data' => ["walletProduct" => $cashAccount->walletProduct,"cashAccount" => $cashAccount->cashAccountID,"involvementType" => $cashAccount->involvementType,"company" => $cashAccount->company,"accountOpeningProduct" => $cashAccount->accountOpeningProduct,"ledgerType" => $cashAccount->ledgerType]];
}else{
return ['code'=> 400, 'message' => 'Cash Account Not Found', 'data' => []];
}
}
/**
* Get all business Involvements...
*/
public function getBusinessInvolvement() //create new fund
{
$result = $this->businessInvolvement()->get();
return $result ?? [];
}
/**
* Get all product involvements...
*/
public function getProductInvolvements() //create new fund
{
$result = $this->productInvolvement()->get();
return $result ?? [];
}
/**
* Get Total Holding By Sector or AssetClass
*/
public function getTotalHoldingBySectorAssetClass($payload) //create new fund
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['SECID'] = $customerz[0]['SECID'];
$result = formatIWRes(container('IWSRequest')->getTotalHoldingBySectorAssetClass($payload))['data'];
$grandTotal = 0;
$i = 0;
/* foreach($result as $res)
{
$grandTotal = $grandTotal + $res['TotalValue'];
} */
$grandTotal = array_sum(array_column($result, 'TotalValue')) ?? 0;
// var_dump($grandTotal);
foreach($result as $res)
{
$result[$i]['grandTotal'] = $grandTotal;
$result[$i]['percent'] = ($grandTotal != 0) ? ($res['TotalValue']*100)/$grandTotal : 0;
$i = $i+1;
}
return $result ?? [];
}
/**
* Get Total Holding for CSS client per CSCS number
*/
public function getTotalSecurityHolding($payload) //create new fund
{
$result = formatIWRes(container('IWSRequest')->getTotalSecurityHolding($payload))['data'];
$totalMarketValue = $totalCost = $totalGainLoss = $totalGainLossPercent = 0;
$data = [];
// foreach($result as $res)
// {
// $totalMarketValue = $totalMarketValue + $res['MarketValue']*1;
$totalMarketValue = array_sum(array_column($result, 'MarketValue')) ?? 0;
// $totalCost = $totalCost + $res['Total Cost'];
$totalCost = array_sum(array_column($result, 'Total Cost')) ?? 0;
// $totalGainLoss = $totalGainLoss + $res['Gain/Loss'];
$totalGainLoss = array_sum(array_column($result, 'Gain/Loss')) ?? 0;
// $totalGainLossPercent = $totalGainLossPercent + $res['Gain/Loss%'];
$totalGainLossPercent = ($totalCost != 0) ? ($totalGainLoss*100)/$totalCost : 0;
// }
$data['totalMarketValue'] = $totalMarketValue;
$data['totalCost'] = $totalCost;
$data['totalGainLoss'] = $totalGainLoss;
$data['totalGainLossPercent'] = $totalGainLossPercent;
return $data ?? [];
}
/**
* Get Total Marginable Stock Holding for CSS client per CSCS number
*/
public function getTotalMarginSecurityHolding($payload) //create new fund
{
$result = formatIWRes(container('IWSRequest')->getTotalMarginSecurityHolding($payload))['data'];
// var_dump($result);
$totalMarketValue = $totalCost = $totalGainLoss = $totalGainLossPercent = 0;
$rez = $data = [];
$i = 0;
foreach($result as $res)
{
$stock = $this->marginStock()
->where([["stockCode","=",$res["StockCode"]]])
->first();
if(count($stock) > 0 )
{
// var_dump($res["StockCode"]);
$rez[$i] = $res;
// $totalMarketValue = $totalMarketValue + $res['MarketValue']*1;
// $totalCost = $totalCost + $res['Total Cost']*1;
// $totalGainLoss = $totalGainLoss + $res['Gain/Loss']*1;
// $totalGainLossPercent = $totalGainLossPercent + $res['Gain/Loss%']*1;
$i++;
}
}
// var_dump($rez);
$totalCost = array_sum(array_column($rez, 'Total Cost')) ?? 0;
$totalGainLoss = array_sum(array_column($rez, 'Gain/Loss')) ?? 0;
$totalMarketValue = array_sum(array_column($rez, 'MarketValue')) ?? 0;
$totalGainLossPercent = ($totalCost != 0) ? ($totalGainLoss*100)/$totalCost : 0;
$data['totalMarketValue'] = $totalMarketValue;
$data['totalCost'] = $totalCost;
$data['totalGainLoss'] = $totalGainLoss;
$data['totalGainLossPercent'] = $totalGainLossPercent;
return $data ?? [];
}
/**
* Get Client Stock Holding for CSS (All CSCS Numbers)
*/
public function getAllTotalSecurityHolding($payload) //create new fund
{
//get CSCS Numbers
$cscs = $this->getCSCSNumber($payload)['data'];
// var_dump($payload);
$totalMarketValue = $totalCost = $totalGainLoss = $totalGainLossPercent = 0;
$data = [];
foreach($cscs as $cscsNo)
{
$payload['CSCSNumber'] = $cscsNo['CsCsAcct#'];
$result = $this->getTotalSecurityHolding($payload);
// var_dump($result);
$totalMarketValue = $totalMarketValue + $result['totalMarketValue'];
$totalCost = $totalCost + $result['totalCost'];
// $totalGainLoss = $totalGainLoss + $result['totalGainLoss'];
// $totalGainLossPercent = $totalGainLossPercent + $result['totalGainLossPercent'];
}
$data['totalMarketValue'] = $totalMarketValue;
$data['totalCost'] = $totalCost;
$data['totalGainLoss'] = $totalMarketValue - $totalCost;
$data['totalGainLossPercent'] = (($totalMarketValue - $totalCost) * 100)/$totalCost;
return $data ?? [];
}
/**
* Get Client Stock Holding for CSS (All CSCS Numbers) available as margin collateral
*/
public function getAvailableStocksForMarginCollateral($payload) //create new fund
{
//get CSCS Numbers
$cscs = $this->getCSCSNumber($payload)['data'];
$existingMargin = $this->marginClientTable()
->selectRaw('SUM(loanAmount) as margin')
->where([
["CustID", "=", $payload["CustID"]],
])
->get()[0]->margin;
$existingCollateral = $this->marginCollateralTable()
->selectRaw('SUM(lienValue) as lienValue')
->where([
["CustID", "=", $payload["CustID"]],
["status", "=", "active"],
])
->get()[0]->lienValue;
// var_dump($payload);
$totalMarketValue = $totalCost = $totalGainLoss = $totalGainLossPercent = 0;
$payload['ledgerType'] = "NGN";
$payload['businessInvolvement'] = STOCKBROKING_DB_NAME;
$payload['involvementType'] = "STK";
//to return client cash balance as at now
$cashBalance = $this->getTotalCashBalanceByLedgerType($payload)['balance'];
$data = [];
foreach($cscs as $cscsNo)
{
$payload['CSCSNumber'] = $cscsNo['CsCsAcct#'];
$result = $this->getTotalMarginSecurityHolding($payload);
// var_dump($result);
$totalMarketValue = $totalMarketValue + $result['totalMarketValue'];
// $availableStockCollateral = $totalMarketValue - $existingMargin + $existingCollateral ?? 0;
$availableStockCollateral = ($totalMarketValue + $cashBalance) - ($existingMargin - $existingCollateral) ?? 0;
}
$data['totalMarketValue'] = $totalMarketValue;
$data['availableStockCollateral'] = $availableStockCollateral;
return $data ?? [];
}
/**
* Get Holding By Sector or AssetClass
*/
public function getHoldingBySectorAssetClass($payload) //create new fund
{
$payload['key'] = $this->stripVariable($payload['key']);
$result = formatIWRes(container('IWSRequest')->getHoldingBySectorAssetClass($payload))['data'];
$grandTotal = 0;
$i = 0;
/* foreach($result as $res)
{
$grandTotal = $grandTotal + $res['MarketValue'];
} */
$grandTotal = array_sum(array_column($result, 'MarketValue')) ?? 0;
foreach($result as $res)
{
$result[$i]['grandTotal'] = $grandTotal;
$result[$i]['percent'] = ($grandTotal != 0) ? ($res['MarketValue']*100)/$grandTotal : 0;
$i = $i + 1;
}
return $result ?? [];
}
/**
* Get all NUBAN product on our DB e.g alpha, wallet...
*/
public function getNubanProducts() //create new fund
{
$result = $this->nubanProduct()->get();
return $result ?? [];
}
/**
* Get a particular NUBAN product on our DB e.g alpha, wallet...
*/
public function getNubanProduct($product) //create new fund
{
$result = $this->nubanProduct()
->where([
["product", "=", strtoupper($product)],
])->first();
return $result ?? [];
}
/**
* Get NUBAN Accounts for a particulare customer record on our DB
*/
public function getNubanAccounts($payload) //create new fund
{
$result = $this->nubanTable()
->where([
["CustID", "=", $payload['CustID'] ],
["accountNumber", "!=", null ],
])->get();
return $result ?? [];
}
/**
* Get NUBAN Account details for a particular client and product from record on our DB
*/
public function getNubanAccount($payload) //create new fund
{
$result = $this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["CustID", "=", $payload['CustID'] ],
["accountNumber", "!=", null ],
])->get();
if(empty($result) || count($result) == 0)
{
$responseData = "NUBAN Customer/Account does not exist";
}elseif((is_null($result[0]->accountNumber) || empty($result[0]->accountNumber) || $result[0]->accountNumber == "") && (!is_null($result[0]->nubanAccountID)&& !empty($result[0]->nubanAccountID)&& $result[0]->nubanAccountID != ""))
{
//fetch NUBAN account from paystack
$res = container('PaystackRequest')->getNubanAccount($result[0]->nubanAccountID, $payload['product']);
if($res['status'] == true)
{
//update local db
$this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["nubanAccountID", "=", $result[0]->nubanAccountID ],
["CustID", "=", $payload['CustID'] ],
])->update([
"accountName" => $res['data']['account_name'],
"accountNumber" => $res['data']['account_number'],
"bankName" => $res['data']['bank']['name'],
"bankSlug" => $res['data']['bank']['slug'],
"currency" =>$res['data']['currency'],
"bankID" =>$res['data']['bank']['id'],
"nubanAccountID" =>$res['data']['id'],
]);
}
$responseData = $res['message'];
return [
"message" => $responseData,
"data" => $res ?? []
];
}elseif((is_null($result[0]->accountNumber) || empty($result[0]->accountNumber) || $result[0]->accountNumber == "") && (!is_null($result[0]->customerCode) && !empty($result[0]->customerCode) && $result[0]->customerCode != ""))
{
//create NUBAN account on paystack
$res = container('PaystackRequest')->createNubanAccount($result[0]->customerCode, $payload['product']);
if($res['status'] == true)
{
$this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["customerCode", "=", $result[0]->customerCode ],
["CustID", "=", $payload['CustID']],
])->update([
"accountName" => $res['data']['account_name'],
"accountNumber" => $res['data']['account_number'],
"bankName" => $res['data']['bank']['name'],
"bankSlug" => $res['data']['bank']['slug'],
"currency" =>$res['data']['currency'],
"bankID" =>$res['data']['bank']['id'],
"nubanAccountID" =>$res['data']['id'],
]);
//send nuban creation notification
$record = [
"fullName" => str_replace(",","",$result[0]->fullName),
"nuban" => $res['data']['account_number'] ,
"bank" => $res['data']['bank']['name'],
"product" => $result[0]->description,
"emailAddress" => $result[0]->emailAddress,
"accountName" => $res['data']['account_name'],
];
// var_dump($record);
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
// ->bcc("[email protected]")
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("NUBAN Creation Notification for ". $result[0]->description)
->usingView('nuban_account_notification', $record)
->send();
}else{
(new Mailer())
->to($result[0]->emailAddress)
// ->bcc("[email protected]")
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("NUBAN Creation Notification for ". $result[0]->description)
->usingView('nuban_account_notification', $record)
->send();
}
}
$responseData = $res['message'];
return [
"message" => $responseData,
"data" => $res ?? []
];
}else{
$responseData = "NUBAN successfully retreived";
}
return [
"message" => $responseData,
"data" => $result ?? []
];
}
/**
* List all NUBAN customers record on our DB
*/
public function listNubanCustomers($payload) //create new fund
{
$result = container('PaystackRequest')->listNubanCustomers($payload['product']);
/* if($result['status'] == true)
{
$responseData = "NUBAN customers successfully retreived";
} */
$responseData = $result['message'];
return [
"message" => $responseData,
"data" => $result ?? []
];
}
/**
* List all NUBAN customers record on our DB
*/
public function listNubanAccounts($payload) //create new fund
{
$result = container('PaystackRequest')->listNubanAccounts($payload['product']);
/* if($result['status'] == true)
{
$responseData = "NUBAN Accounts successfully retreived";
} */
$responseData = $result['message'];
return [
"message" => $responseData,
"data" => $result ?? []
];
}
/**
* Validate a NUBAN customer record on our DB
*/
public function validateNubanCustomer($payload) //create new fund
{
// $responseData = "NUBAN Customer not verified";
//get additional data from middlware
$decoded_data = formatIWRes(container('IWSRequest')->getUserDetailsFromMiddleware(MIDDLEWARE_DB_NAME, $payload['CustID']));
if(strtoupper($decoded_data['data'][0]['ClientType']) == "IND"){
$payload = $payload + [
"BVNFirstName" => $decoded_data['data'][0]["BVNFirstName"],
"BVNLastName" => $decoded_data['data'][0]["BVNLastName"],
"BVNMiddleName" =>$decoded_data['data'][0]["BVNMiddleName"],
"otherNames" =>$decoded_data['data'][0]["MiddleName"],
];
}else{
$payload = $payload + [
"BVNFirstName" => $decoded_data['data'][0]["BVNFirstName"],
"BVNLastName" => $decoded_data['data'][0]["BVNLastName"],
"BVNMiddleName" =>$decoded_data['data'][0]["BVNMiddleName"],
];
}
$result = container('PaystackRequest')->validateNubanCustomer($payload, $payload['product']);
$responseData = $result['message'];
return [
"message" => $responseData,
"data" => $result ?? []
];
}
/* public function IXTRACAuth(){
$result = paystackRequest::getClientNubanFromPaystack($checkIfUserNubanExists->nuban_account_id);
} */
public function moveUploadedFile($directory, UploadedFile $uploadedFile)
{
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8)); //
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename ?? [];
}
public function moveUploadedFile_valuation($basename, $directory, UploadedFile $uploadedFile)
{
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
// $basename = bin2hex(random_bytes(8)); //
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename ?? [];
}
public function moveUploadedFile_zenith($basename, $directory, UploadedFile $uploadedFile)
{
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
// $basename = bin2hex(random_bytes(8)); //
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename ?? [];
}
public function getAllCAMDealRates()
{
$rates = $this->CAMRateTable()->get();
return $rates ?? [];
}
public function getCAMProducts($payload)
{
$product = $this->CAMProductTable()->get();
return $product ?? [];
}
public function getCAMProduct($payload)
{
$product = $this->CAMProductTable()
->where([["productType", "=", $payload['productType']]])
->get();
return $product ?? [];
}
public function getCAMDealRate($payload)
{
$rate = $this->CAMRateTable()
->where([
// ["tenure", "=", $payload['tenure']],
["instrumentType", "=", $payload['instrumentType']],
["investmentType", "=", $payload['investmentType']],
])
->get();
return $rate ?? [];
}
public function getYochaaDealRate($payload)
{
$rate = $this->YochaaRateTable()
->where([
// ["tenure", "=", $payload['tenure']],
["instrumentType", "=", $payload['instrumentType']],
["investmentType", "=", $payload['investmentType']],
])
->get();
return $rate ?? [];
}
public function getNotifications($payload)
{
$notifications = $this->notificationTable()
->where([
// ["tenure", "=", $payload['tenure']],
["CustID", "=", $payload['CustID']],
])
->get();
return $notifications ?? [];
}
public function getCAMDealTenure($payload)
{
$tenure = $this->CAMRateTable()
->where([["instrumentType", "=", $payload['instrumentType']],
["investmentType", "=", $payload['investmentType']],
])
->get();
return $tenure ?? [];
}
public function createCAMDealRate($payload)
{
$rates = $this->CAMRateTable()
->insertGetId([
'product' => $payload['product'],
'rate' => $payload['rate'],
'charge' => $payload['charge'],
'tenure' => $payload['tenure'],
'investmentType' => $payload['investmentType'],
'instrumentType' => $payload['instrumentType'],
'admin' => $payload['admin'],
]);
return ['message' => $payload['product']. ' rate was successfully created.'];
}
public function udpateCAMDealRate($payload)
{
$rates = $this->CAMRateTable()
->where([["ID","=", $payload['ID']]])
->update([
// 'product' => $payload['product'],
'rate' => $payload['rate'] . "%",
'charge' => $payload['charge'],
// 'tenure' => $payload['tenure'],
// 'investmentType' => $payload['investmentType'],
// 'instrumentType' => $payload['instrumentType'],
'admin' => $payload['admin'],
"ipAddress" => $this->get_client_ip(),
]);
return ['message' => $payload['product']. ' rate was successfully updated.'];
}
public function createCAMProduct($payload)
{
$rates = $this->CAMProductTable()
->insertGetId([
'product' => $payload['product'],
'category' => $payload['category'],
'description' => $payload['description'],
'productType' => $payload['productType'],
'walletRecipient' => $payload['walletRecipient'],
'bookingType' => $payload['bookingType'],
'investmentType' => $payload['investmentType'],
'involvementType' => $payload['involvementType'],
'minInvestment' => $payload['minInvestment'],
'ledgerType' => $payload['ledgerType'],
'admin' => $payload['admin'],
]);
return ['message' => $payload['product']. ' was successfully created.'];
}
public function submitCAMDeal($payload)
{
$rates = $this->CAMDealTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'fullName' => $payload['fullName'],
'product' => $payload['product'],
'tenure' => $payload['tenure'],
'price' => $payload['price'],
'rate' => $payload['rate'],
// 'yield' => $payload['yield'],
'amount' => $payload['amount'],
'transNo' => $payload['transNo'],
'maturityDate' => $payload['maturityDate'],
'lastCouponDate' => $payload['lastCouponDate'],
'transactionType' => $payload['transactionType'],
'productType' => $payload['productType'],
'ledgerType' => $payload['ledgerType'],
'capitalizeOnRollover' => $payload['capitalizeOnRollover'],
'doAutomaticRollover' => $payload['doAutomaticRollover'],
'upfrontInterest' => $payload['upfrontInterest'],
'involvementType' => $payload['involvementType'],
'instrumentType' => $payload['instrumentType'],
"ipAddress" => $this->get_client_ip(),
]);
return ['code' => 200, 'message' => $payload['product']. ' transaction request successfully created.'];
}
public function submitBreakCAMInvestment($payload)
{
$rates = $this->CAMDealBreakTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'fullName' => $payload['fullName'],
'tenure' => $payload['tenure'],
'chgAmount' => $payload['chgAmount'],
'rate' => $payload['rate'],
'transNo' => $payload['transNo'],
'instrumentType' => $payload['instrumentType'],
'productType' => $payload['productType'],
'penalty' => $payload['penalty'],
'product' => $payload['product'],
]);
return ['code' => 200, 'message' => 'Investment liquidation request successfully submitted.'];
}
public function getCurrentCAMDeals()
{
$deals = $this->CAMDealTable()
->where([["createdDate", 'like', Carbon::now()->format('Y-m-d') . '%']])
->get();
return $deals ?? [];
}
/*
public function rejectCAMDeal($payload)
{
$deals = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["status", "=", "pending"],
])
->update([
"status" => "rejected",
"processedBy" => $payload['admin'],
"processedDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($deals > 0)
{
return ["code" => 200,"message" => "Investment Booking Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
}
}
public function approveCAMDeal($payload)
{
$deals = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["status", "=", "pending"],
])
->update([
"status" => "approved",
"processedBy" => $payload['admin'],
"processedDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($deals > 0)
{
//execute booking
if(strtoupper($payload['type']) == "BONDS")
{
$book = formatIWRes(container('IWSRequest')->bookBondsInvestment($payload));
}elseif(strtoupper($payload['type']) == "TBILLS")
{
$book = formatIWRes(container('IWSRequest')->bookTbillsInvestment($payload));
}elseif(strtoupper($payload['type']) == "CP")
{
$payload['interestRate'] = $payload['rate'];
$book = formatIWRes(container('IWSRequest')->bookCAMInvestment($payload));
}
if($book["StatusID"] == 0)
{
return ["code" => 200, "message" => "Investment Booking Request Approved and Investment Booked"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Approved, but Investment Booking Failed. Please Contact IT"] ?? [];
}
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
}
}
*/
public function submitMarginApplication($payload)
{
//check if portfolio value is sufficient for loan amount
$maxLoan = ($payload['portfolioValuation'] + $payload['collateralValue']);
if($payload['loanAmount'] > $maxLoan)
{
return ["code" => 400,"message" => "Your Loan Request is Above Limit. Maximum Loan Amount is N".number_format($maxLoan, 2, '.', ',')];
}
//check if application exist
$check = $this->marginApplicationTable()
->where([['CustID' ,"=", $payload['CustID']],
['loanType' ,"=", $payload['loanType']],
])
->get();
// if(count($check) > 0)
// {
// return ["code" => 400,"message" => "Margin Loan Application Already Exist"];
// }
$applicationID = $payload['CustID']."-".mt_rand(100000, 999999)."-".Carbon::now()->format('N');
$marginApplication = $this->marginApplicationTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'SECID' => $payload['SECID'],
'fullName' => $payload['fullName'],
'emailAddress' => $payload['emailAddress'],
'portfolioValuation' => $payload['portfolioValuation'],
'loanAmount' => $payload['loanAmount'],
'loanType' => $payload['loanType'],
'rate' => $payload['rate'],
'applicationID' => $applicationID,
// 'collateral' => $payload['collateral'],
// 'collateralValue' => $payload['collateralValue'],
]);
foreach($payload['collateral'] as $collateral)
{
$collateral = $this->marginCollateralTable()
->insertGetId([
'CustID' => $payload['CustID'],
'fullName' => $payload['fullName'],
'applicationID' => $applicationID,
'collateral' => $collateral['collateral'],
'instrumentType' => $collateral['instrumentType'],
'cashAccount' => $collateral['cashAccount'],
'collateralValue' => $collateral['collateralValue'],
'lienValue' => $collateral['lienValue'],
'loanType' => $payload['loanType'],
]);
}
return ['message' => 'Margin Loan Application Successfully Submitted.'];
}
public function getMarginApplication($payload)
{
if(strtoupper($payload['action']) == "ALL")
{
$data = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->get();
// }elseif(strtoupper($payload['action']) == "PENDING")
}else
{
$data = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where(strtolower($payload['role'])."_status","=", strtolower($payload['action']))
->get();
}
return ['message' => 'Margin Loan Applications Successfully fetched.' , 'data' => $data];
}
public function getMarginCollateral($payload)
{
//check if application exist
$data = $this->marginCollateralTable()
->where([["applicationID","=",$payload['applicationID']]])
->get();
if(count($data) > 0)
{
return ['message' => 'Margin Collateral Successfully fetched.' , 'data' => $data];
}else{
return ['message' => 'No Margin Collateral Found.'];
}
}
public function getMarginCollaterals()
{
//check if application exist
$data = $this->marginCollateralTable()
->get();
if(count($data) > 0)
{
return ['message' => 'Margin Collateral Successfully fetched.' , 'data' => $data];
}else{
return ['message' => 'No Margin Collateral Found.'];
}
}
public function getMarginLien()
{
//check if application exist
$data = $this->marginLienTable()
->get();
if(count($data) > 0)
{
return ['message' => 'Margin Collateral Successfully fetched.' , 'data' => $data];
}else{
return ['message' => 'No Margin Collateral Found.'];
}
}
public function getMarginApplicationDetails($payload)
{
//check if application exist
// $data = $this->marginApplicationTable()->get();
$data = $this->marginApplicationTable()->where([["CustID","=",$payload['CustID']]])->get();
$data = json_decode(json_encode($data),true);
//append collaterals
if(count($data) > 0)
{
$i=0;
foreach($data as $d)
{
$data[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
return ['message' => 'Margin Application Details Successfully fetched.' , 'data' => $data];
}else{
return ['message' => 'No Margin Application Found.', 'data' => $data ?? []];
}
}
public function getMarginDetails($payload)
{
//check if application exist
$data = $this->marginClientTable()
->where([["CustID","=",$payload['CustID']]])
->get();
return ['message' => 'Margin Details Successfully fetched.' , 'data' => $data ?? []];
}
public function terminateMarginLoan($payload)
{
//check if application exist
$data = $this->marginClientTable()
->where([["CustID","=",$payload['CustID']],
["id","=",$payload['ID']],
])
->update([
"loanAmount" => 0.00,
"status" => 0,
"admin" => $payload["admin"],
]);
//check if application exist
$data = $this->marginClientTable()
->where([["CustID","=",$payload['CustID']],
["id","=",$payload['ID']],
["loanType","=",$payload['loanType']],
])
->update([
"loanAmount" => 0.00,
"admin" => $payload["admin"],
]);
if(count($data) > 0)
{
// if(strtoupper($payload["completeTermination"]) == "TRUE")
// {
$this->marginLienTable()
->where([["CustID","=",$payload['CustID']],
["loanType","=",$payload['loanType']],
])
->update([
"lienValue" => 0.00,
]);
$this->marginCollateralTable()
->where([["CustID","=",$payload['CustID']],
["loanType","=",$payload['loanType']],
])
->update([
"status" => "closed",
]);
//remove client from SPA list
$this->removeSPAClient($payload);
// }
return ['code' => 200, 'message' => 'Margin Loan Successfully Closed.'];
}else{
return ['code' => 400, 'message' => 'Margin Loan Closure Failed.'];
}
}
public function getValuationFee()
{
//check if application exist
// $data = $this->marginClientTable()
// ->where([["CustID","=",$payload['CustID']]])
// ->get();
// return ['message' => 'Margin Details Successfully fetched.' , 'data' => $data];
return ["fee" => "2500"];
}
/*
public function approveMarginApplication($payload)
{
$deals = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["status", "=", "pending"],
])
->update([
"status" => "approved",
"processedBy" => $payload['admin'],
"processedDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($deals > 0)
{
//check if application exist
$check = $this->marginClientTable()
->where([['CustID' ,"=", $payload['CustID']],
['loanType' ,"=", $payload['loanType']],
])
->get();
if(count($check) > 0)
{
return ["code" => 400,"message" => "Margin Loan Facility Already Exist"];
}
//create margin involvement for client and set margin limit
$payload['businessInvolvement'] = STOCKBROKING_DB_NAME;
$payload['involvementType'] = MARGIN_INVOLVEMENT;
$payload['BIZID'] = $payload['SECID'];
$result = formatIWRes(container('IWSRequest')->createInvolvement($payload));
$resultDecoded = json_decode(json_encode($result));
//var_dump("status id is ".$result["StatusID"]);
if($result["StatusID"] == 0)
{
$margin = $this->marginClientTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'SECID' => $payload['SECID'],
'fullName' => $payload['fullName'],
'emailAddress' => $payload['emailAddress'],
'marginID' => (strtoupper($payload['loanType']) == "STAFF") ? "MAS-".$payload['CustID'] : "MAC-".$payload['CustID'],
'rate' => $payload['rate'],
'loanAmount' => $payload['loanAmount'],
'loanType' => $payload['loanType'],
]);
if($margin > 0)
{
return ["code" => 200, "message" => "Margin Application Approved and Processed"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Approved, but Not Processed. Please Contact IT"] ?? [];
}
}
}else{
return ["code" => 400,"message" => "Margin Application Not Found"] ?? [];
}
} */
public function getPortalMarginClients()
{
//check if application exist
$data = $this->marginClientTable()
// ->where([["fincon_status", "=", "approved"]])
->get();
return ['message' => 'Margin Clients Successfully fetched.' , 'data' => $data];
}
public function getMarginAccruedInterest()
{
//check if application exist
$data = $this->marginInterestAccruedTable()
->get();
return ['message' => 'Margin Accrued Interests Successfully fetched.' , 'data' => $data];
}
public function getClientMarginAccruedInterest($payload)
{
//check if application exist
$data = $this->marginInterestAccruedTable($payload)
->where([["CustID", "=", $payload["CustID"]]])
->get();
return ['message' => 'Margin Accrued Interests Successfully fetched.' , 'data' => $data];
}
public function getMarginInterestLog()
{
//check if application exist
$data = $this->marginInterestTable()
->get();
return ['message' => 'Margin Interest Log Successfully fetched.' , 'data' => $data];
}
/*
public function rejectMarginApplication($payload)
{
$deals = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["status", "=", "pending"],
])
->update([
"status" => "rejected",
"processedBy" => $payload['admin'],
"processedDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($deals > 0)
{
return ["code" => 200,"message" => "Margin Application Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Not Found"] ?? [];
}
}
public function postMarginTransaction()
{
//check if application exist
$data = $this->marginClientTable()
->get();
return ['message' => 'Margin Clients Successfully fetched.' , 'data' => $data];
} */
public function getExistingMarginAmount($payload)
{
$margin = $this->marginClientTable()
->selectRaw('SUM(loanAmount) as margin')
->where([
["CustID", "=", $payload["CustID"]],
])
->get()[0]->margin;
return["margin" => $margin ?? "0"];
}
/* public function getInvestmentSummary($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['CAMID'] = $customerz[0]['CAMID'];
$payload['SECID'] = $customerz[0]['SECID'];
$payload['date'] = Carbon::now()->format('Y-m-d');
if(strtoupper($payload["ledgerType"]) == "NGN")
{
$stock = $asset = $sma = $totalPort = $mf = $mf_ = 0;
$stock = $this->getAllTotalSecurityHolding($payload)['totalMarketValue'] ?? 0;
$asset = $this->getAllCAMTotalHoldingByInvestmentType($payload)[0]['Portfolio Value'] ?? 0;
$sma = $this->getSMAInvestmentTotal($payload)?? 0;
//get all fund codes
$funds = container('mutualFundModel')->getFundCode();
$funds = json_decode(json_encode($funds), true);
foreach($funds as $fund)
{
$mf_ = container('mutualFundModel')->getCAMMFAccountDetails($payload["CAMID"], $fund["fundCode"])["investment_details"][0]["MktValue"] ?? 0;
$mf = $mf + $mf_;
}
$totalPort = $stock + $asset + $sma + $mf;
$stockPercent = ($totalPort != 0) ? (($stock * 100) / $totalPort) : 0.00;
$assetPercent = ($totalPort != 0) ? (($asset * 100) / $totalPort) : 0.00;
$smaPercent = ($totalPort != 0) ? (($sma * 100) / $totalPort) : 0.00;
$mfPercent = ($totalPort != 0) ? (($mf * 100) / $totalPort) : 0.00;
return[["business" => "Securities Trading", "businessInvolvement" => STOCKBROKING_DB_NAME, "involvementType" => STOCKBROKING_INVOLVEMENT, "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","businessInvolvement" => CAM_DB_NAME, "involvementType" => FI_INVOLVEMENT, "value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "businessInvolvement" => CAM_DB_NAME, "involvementType" => SMA_INVOLVEMENT, "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $mf, "percent" => $mfPercent, "total" => $totalPort]] ?? [];
}elseif(strtoupper($payload["ledgerType"]) == "USD")
{
$stock = $asset = $sma = $totalPort = $mf = $mf_ = 0;
$troveID = container('foreignEquityModel')->getUserForeignEquityDetails($payload['CustID']);
$payload['troveID'] = $troveID['troveID'];
$payload['accountID'] = $troveID['accountID'];
if(!is_null($payload['accountID']) && !empty($payload['accountID']) && $payload['accountID'] != "")
{
$stock = container('foreignEquityModel')->getUserTradingAccountPositionFromTrove($payload['accountID'])['data'][0]['totalHolding'] ?? 0;
}else{
$stock = 0;
}
$asset = $this->getAllCAMTotalHoldingByInvestmentType($payload)[0]['Portfolio Value'] ?? 0;
$sma = $this->getSMAInvestmentTotal($payload)?? 0;
$totalPort = $stock + $asset + $sma + $mf;
$stockPercent = ($totalPort != 0) ? (($stock * 100) / $totalPort) : 0.00;
$assetPercent = ($totalPort != 0) ? (($asset * 100) / $totalPort) : 0.00;
$smaPercent = ($totalPort != 0) ? (($sma * 100) / $totalPort) : 0.00;
$mfPercent = ($totalPort != 0) ? (($mf * 100) / $totalPort) : 0.00;
$sofPercent = 0.00;
// return["stock" => $stock, "stockPercent" => $stockPercent, "asset" => $asset, "assetPercent" => $assetPercent, "sma" => $sma, "smaPercent" => $smaPercent, "mf" => $mf, "mfPercent" => $mfPercent, "totalPort" => $totalPort];
// return[["business" => "Securities Trading", "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds","value" => $mf, "percent" => $mfPercent, "total" => $totalPort]];
return[["business" => "Securities Trading", "businessInvolvement" => STOCKBROKING_DB_NAME, "involvementType" => TROVE_INVOLVEMENT, "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","businessInvolvement" => CAM_DB_NAME, "involvementType" => FI_USD_INVOLVEMENT, "value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $mf, "percent" => $mfPercent, "total" => $totalPort], ["business" => "SOF", "businessInvolvement" => CAM_DB_NAME, "involvementType" => SOF_INVOLVEMENT, "value" => $sof, "percent" => $sofPercent, "total" => $totalPort]] ?? [];
}elseif(strtoupper($payload["ledgerType"]) == "GBP")
{
$stock = $asset = $sma = $totalPort = $mf = $mf_ = 0;
$asset = $this->getAllCAMTotalHoldingByInvestmentType($payload)[0]['Portfolio Value'] ?? 0;
$sma = $this->getSMAInvestmentTotal($payload)?? 0;
$totalPort = $stock + $asset + $sma + $mf;
$stockPercent = ($totalPort != 0) ? (($stock * 100) / $totalPort) : 0.00;
$assetPercent = ($totalPort != 0) ? (($asset * 100) / $totalPort) : 0.00;
$smaPercent = ($totalPort != 0) ? (($sma * 100) / $totalPort) : 0.00;
$mfPercent = ($totalPort != 0) ? (($mf * 100) / $totalPort) : 0.00;
$sofPercent = 0.00;
// return["stock" => $stock, "stockPercent" => $stockPercent, "asset" => $asset, "assetPercent" => $assetPercent, "sma" => $sma, "smaPercent" => $smaPercent, "mf" => $mf, "mfPercent" => $mfPercent, "totalPort" => $totalPort];
// return[["business" => "Securities Trading", "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds","value" => $mf, "percent" => $mfPercent, "total" => $totalPort]];
return[["business" => "Securities Trading", "businessInvolvement" => STOCKBROKING_DB_NAME, "involvementType" => "N/A", "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","businessInvolvement" => CAM_DB_NAME, "involvementType" => FI_GBP_INVOLVEMENT, "value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $mf, "percent" => $mfPercent, "total" => $totalPort], ["business" => "SOF", "businessInvolvement" => CAM_DB_NAME, "involvementType" => SOF_INVOLVEMENT, "value" => $sof, "percent" => $sofPercent, "total" => $totalPort]] ?? [];
}
} */
public function getInvestmentSummary($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['ASSETID'] = $customerz[0]['ASSETID'];
$payload['CAMID'] = $customerz[0]['CAMID'];
$payload['SECID'] = $customerz[0]['SECID'];
$payload['date'] = Carbon::now()->format('Y-m-d');
if(strtoupper($payload["ledgerType"]) == "NGN")
{
$sof = $stock = $asset = $sma = $totalPort = $mf = $mf_ = 0;
$sof = container('mutualFundModel')->getCAMMFAccountDetails($payload["ASSETID"], "CSOF")["investment_details"][0]["MktValue"] ?? 0;
$stock = $this->getAllTotalSecurityHolding($payload)['totalMarketValue'] ?? 0;
$asset = $this->getAllCAMTotalHoldingByInvestmentType($payload)[0]['Portfolio Value'] ?? 0;
$sma = $this->getSMAInvestmentTotal($payload)?? 0;
//get all fund codes
$funds = container('mutualFundModel')->getFundCode();
$funds = json_decode(json_encode($funds), true);
$exemptedArray = array_filter($funds, function ($fund) {
return $fund['fundCode'] !== 'DF';
});
foreach($exemptedArray as $fund)
{
$mf_ = container('mutualFundModel')->getCAMMFAccountDetails($payload["CAMID"], $fund["fundCode"])["investment_details"][0]["MktValue"] ?? 0;
$mf = $mf + $mf_;
}
$totalPort = $stock + $asset + $sma + $mf + $sof;
$stockPercent = ($totalPort != 0) ? (($stock * 100) / $totalPort) : 0.00;
$assetPercent = ($totalPort != 0) ? (($asset * 100) / $totalPort) : 0.00;
$smaPercent = ($totalPort != 0) ? (($sma * 100) / $totalPort) : 0.00;
$mfPercent = ($totalPort != 0) ? (($mf * 100) / $totalPort) : 0.00;
$sofPercent = ($totalPort != 0) ? (($sof * 100) / $totalPort) : 0.00;
return[["business" => "Securities Trading", "businessInvolvement" => STOCKBROKING_DB_NAME, "involvementType" => STOCKBROKING_INVOLVEMENT, "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","businessInvolvement" => CAM_DB_NAME, "involvementType" => FI_INVOLVEMENT, "value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "businessInvolvement" => CAM_DB_NAME, "involvementType" => SMA_INVOLVEMENT, "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $mf, "percent" => $mfPercent, "total" => $totalPort], ["business" => "SOF", "businessInvolvement" => CAM_DB_NAME, "involvementType" => SOF_INVOLVEMENT, "value" => $sof, "percent" => $sofPercent, "total" => $totalPort]] ?? [];
}elseif(strtoupper($payload["ledgerType"]) == "USD")
{
$stock = $asset = $sma = $totalPort = $mf = $mf_ = 0;
$troveID = container('foreignEquityModel')->getUserForeignEquityDetails($payload['CustID']);
$payload['troveID'] = $troveID['troveID'];
$payload['accountID'] = $troveID['accountID'];
if(!is_null($payload['accountID']) && !empty($payload['accountID']) && $payload['accountID'] != "")
{
$stock = container('foreignEquityModel')->getUserTradingAccountPositionFromTrove($payload['accountID'])['data'][0]['totalHolding'] ?? 0;
}else{
$stock = 0;
}
$funds = container('mutualFundModel')->getFundCode();
$funds = json_decode(json_encode($funds), true);
$exemptedArray = array_filter($funds, function ($fund) {
return $fund['fundCode'] === 'DF';
});
foreach($exemptedArray as $fund)
{
$mf_ = container('mutualFundModel')->getCAMMFAccountDetails($payload["CAMID"], $fund["fundCode"])["investment_details"][0]["MktValue"] ?? 0;
$mf = $mf + $mf_;
}
$asset = $this->getAllCAMTotalHoldingByInvestmentType($payload)[0]['Portfolio Value'] ?? 0;
$sma = $this->getSMAInvestmentTotal($payload)?? 0;
$totalPort = $stock + $asset + $sma + $mf;
$stockPercent = ($totalPort != 0) ? (($stock * 100) / $totalPort) : 0.00;
$assetPercent = ($totalPort != 0) ? (($asset * 100) / $totalPort) : 0.00;
$smaPercent = ($totalPort != 0) ? (($sma * 100) / $totalPort) : 0.00;
$mfPercent = ($totalPort != 0) ? (($mf * 100) / $totalPort) : 0.00;
$sofPercent = 0.00;
// return["stock" => $stock, "stockPercent" => $stockPercent, "asset" => $asset, "assetPercent" => $assetPercent, "sma" => $sma, "smaPercent" => $smaPercent, "mf" => $mf, "mfPercent" => $mfPercent, "totalPort" => $totalPort];
// return[["business" => "Securities Trading", "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds","value" => $mf, "percent" => $mfPercent, "total" => $totalPort]];
return[["business" => "Fixed Income","businessInvolvement" => CAM_DB_NAME, "involvementType" => FI_USD_INVOLVEMENT, "value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $mf, "percent" => $mfPercent, "total" => $totalPort]] ?? [];
}elseif(strtoupper($payload["ledgerType"]) == "GBP")
{
$stock = $asset = $sma = $totalPort = $mf = $mf_ = 0;
$asset = $this->getAllCAMTotalHoldingByInvestmentType($payload)[0]['Portfolio Value'] ?? 0;
$sma = $this->getSMAInvestmentTotal($payload)?? 0;
$totalPort = $stock + $asset + $sma + $mf;
$stockPercent = ($totalPort != 0) ? (($stock * 100) / $totalPort) : 0.00;
$assetPercent = ($totalPort != 0) ? (($asset * 100) / $totalPort) : 0.00;
$smaPercent = ($totalPort != 0) ? (($sma * 100) / $totalPort) : 0.00;
$mfPercent = ($totalPort != 0) ? (($mf * 100) / $totalPort) : 0.00;
$sofPercent = 0.00;
// return["stock" => $stock, "stockPercent" => $stockPercent, "asset" => $asset, "assetPercent" => $assetPercent, "sma" => $sma, "smaPercent" => $smaPercent, "mf" => $mf, "mfPercent" => $mfPercent, "totalPort" => $totalPort];
// return[["business" => "Securities Trading", "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds","value" => $mf, "percent" => $mfPercent, "total" => $totalPort]];
return[["business" => "Fixed Income","businessInvolvement" => CAM_DB_NAME, "involvementType" => FI_GBP_INVOLVEMENT, "value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $mf, "percent" => $mfPercent, "total" => $totalPort]] ?? [];
} elseif(strtoupper($payload["ledgerType"]) == "EUR")
{
$stock = $asset = $sma = $totalPort = $mf = $mf_ = 0;
$asset = $this->getAllCAMTotalHoldingByInvestmentType($payload)[0]['Portfolio Value'] ?? 0;
$sma = $this->getSMAInvestmentTotal($payload)?? 0;
$totalPort = $stock + $asset + $sma + $mf;
$stockPercent = ($totalPort != 0) ? (($stock * 100) / $totalPort) : 0.00;
$assetPercent = ($totalPort != 0) ? (($asset * 100) / $totalPort) : 0.00;
$smaPercent = ($totalPort != 0) ? (($sma * 100) / $totalPort) : 0.00;
$mfPercent = ($totalPort != 0) ? (($mf * 100) / $totalPort) : 0.00;
$sofPercent = 0.00;
// return["stock" => $stock, "stockPercent" => $stockPercent, "asset" => $asset, "assetPercent" => $assetPercent, "sma" => $sma, "smaPercent" => $smaPercent, "mf" => $mf, "mfPercent" => $mfPercent, "totalPort" => $totalPort];
// return[["business" => "Securities Trading", "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds","value" => $mf, "percent" => $mfPercent, "total" => $totalPort]];
return[["business" => "Securities Trading", "businessInvolvement" => STOCKBROKING_DB_NAME, "involvementType" => "N/A", "value" => $stock, "percent" => $stockPercent, "total" => $totalPort], ["business" => "Fixed Income","businessInvolvement" => CAM_DB_NAME, "involvementType" => FI_EUR_INVOLVEMENT, "value" => $asset, "percent" => $assetPercent, "total" => $totalPort],["business" => "Managed Account", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $sma, "percent" => $smaPercent, "total" => $totalPort], ["business" => "Mutual Funds", "businessInvolvement" => CAM_DB_NAME, "involvementType" => "N/A", "value" => $mf, "percent" => $mfPercent, "total" => $totalPort], ["business" => "SOF", "businessInvolvement" => CAM_DB_NAME, "involvementType" => SOF_INVOLVEMENT, "value" => $sof, "percent" => $sofPercent, "total" => $totalPort]] ?? [];
}
}
public function getMarginConversionRate()
{
$rate = $this->marginConversionRateTable()->get();
return["data" => $rate];
}
public function notifyMarginDefaulters()
{
//get all margin default clients
$defaulter = $this->getMarginDefaulters();
$defaulter = json_decode(json_encode($defaulter),true);
return $defaulter;
}
public function getMarginDefaulters()
{
//get all margine clients
$marginClients = $this->marginClientTable()->get();
$marginClients = json_decode(json_encode($marginClients),true);
foreach($marginClients as $payload)
{
$payload['ledgerType'] = "NGN";
$payload['involvementType'] = "STK";
$payload['businessInvolvement'] = STOCKBROKING_DB_NAME;
$result = formatIWRes(container('IWSRequest')->getCashBalanceByLedgerType($payload))['data'];
$margin = $this->marginClientTable()
->selectRaw('SUM(loanAmount) as margin')
->where([
["CustID", "=", $payload["CustID"]],
])
->get()[0]->margin;
$collateral = $this->marginCollateralTable()
->selectRaw('SUM(lienValue) as lienValue')
->where([
["CustID", "=", $payload["CustID"]],
["status", "=", "active"],
])
->get()[0]->lienValue;
$grandTotal = $marginSpent = 0;
// $i = 0;
/* foreach($result as $res)
{
$grandTotal = $grandTotal + $res['Balance']*1;
} */
$grandTotal = array_sum(array_column($result, 'Balance')) ?? 0;
if($grandTotal < 0)
{
$marginSpent = $grandTotal * -1;
// $default = (($marginSpent * -1) >= ($margin * 60/100)) ? true : false;
$stockValue = $this->getAllTotalSecurityHolding($payload)['totalMarketValue'];
$breach = ($stockValue + $collateral)/$marginSpent;
// $default = ($breach <= 1.4) ? true : false;
// if($default == true)
if($breach <= 1.4)
{
$this->marginClientTable()
->where([
["CustID", "=", $payload["CustID"]],
])
->update([
"default" => "YES",
"admin" => "webhook",
]);
}elseif($breach <= 1.5 && $breach > 1.4)
{
$this->marginClientTable()
->where([
["CustID", "=", $payload["CustID"]],
])
->update([
"default" => "ALMOST",
"admin" => "webhook",
]);
}else{
$this->marginClientTable()
->where([
["CustID", "=", $payload["CustID"]],
])
->update([
"default" => "NO",
"admin" => "webhook",
]);
}
}else{
$this->marginClientTable()
->where([
["CustID", "=", $payload["CustID"]],
])
->update([
"default" => "NO",
"admin" => "webhook",
]);
}
}
//fetch all defaulters
$data = $this->marginClientTable()
->where([
["default", "=", "ALMOST"],
])
->get();
$data = json_decode(json_encode($data),true);
//fetch all Calls
$data_ = $this->marginClientTable()
->where([
["default", "=", "YES"],
])
->get();
$data_ = json_decode(json_encode($data_),true);
return ["message" => "All Margin Defaulters Fetched" , "default" => $data, "call" => $data_] ?? [];
}
public function getClientMarginDefaultStatus($load)
{
//get all margine clients
// $marginClients = $this->marginClientTable()->get();
$marginClients = $this->marginClientTable()->where([["CustID","=",$load['CustID']]])->get();
$marginClients = json_decode(json_encode($marginClients),true);
foreach($marginClients as $payload)
{
$payload['ledgerType'] = "NGN";
$payload['involvementType'] = "STK";
$payload['businessInvolvement'] = STOCKBROKING_DB_NAME;
$result = formatIWRes(container('IWSRequest')->getCashBalanceByLedgerType($payload))['data'];
$margin = $this->marginClientTable()
->selectRaw('SUM(loanAmount) as margin')
->where([
["CustID", "=", $payload["CustID"]],
])
->get()[0]->margin;
$collateral = $this->marginCollateralTable()
->selectRaw('SUM(lienValue) as lienValue')
->where([
["CustID", "=", $payload["CustID"]],
["status", "=", "active"],
])
->get()[0]->lienValue;
$grandTotal = $marginSpent = 0;
// $i = 0;
/* foreach($result as $res)
{
$grandTotal = $grandTotal + $res['Balance']*1;
} */
$grandTotal = array_sum(array_column($result, 'Balance')) ?? 0;
if($grandTotal < 0)
{
$marginSpent = $grandTotal * -1;
// $default = (($marginSpent * -1) >= ($margin * 60/100)) ? true : false;
$stockValue = $this->getAllTotalSecurityHolding($payload)['totalMarketValue'];
$breach = ($stockValue + $collateral)/$marginSpent;
// $default = ($breach <= 1.4) ? true : false;
// var_dump("marginSpent: ".number_format($marginSpent, 2, '.', ','));
// var_dump("stockValue: ".number_format($stockValue, 2, '.', ','));
// var_dump("breach: ".number_format($breach, 2, '.', ','));
// if($default == true)
if($breach <= 1.4)
{
return [["Response" => "Yes"]];
}elseif($breach <= 1.5 && $breach > 1.4)
{
return [["Response" => "Almost"]];
}else{
return [["Response" => "No"]];
}
}else{
/* $this->marginClientTable()
->where([
["CustID", "=", $payload["CustID"]],
])
->update([
"default" => "NO",
]); */
return [["Response" => "No"]];
}
}
return [["Response" => "No"]];
/* //fetch all defaulters
$data = $this->marginClientTable()
->where([
["default", "=", "YES"],
])
->get(); */
// $status = (count($marginStatus) > 0) ? "True" : "False";
}
public function computeMarginInterest()
{
$message1 = "Webhook Called->>";
$message2 = "Analyzing Details->>";
$message3 = "Validating Payload->>";
$message4 = "Verifying Originating IP Address->>" . $_SERVER['REMOTE_ADDR'];
$message5 = "Computing Daily Margin Interest";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
//get all margin clients
$marginClients = $this->marginClientTable()->selectRaw('DISTINCT(CustID), SECID, fullName')->get();
$marginClients = json_decode(json_encode($marginClients), true);
/************ fetch stock purchase records from T-3 **********************/
/* $date_3_ = Carbon::now()->format('Y-m-d');
$date_3_ = date_create($date_3_);
$date_3 = date_format(date_sub($date_3_, date_interval_create_from_date_string("3 days")), "Y-m-d"); */
// $date_check = Carbon::now()->subDays(1)->format('Y-m-d');
$ik = $j = 0;
while ($j < 3) {
$ik = $ik + 1;
$date_check = Carbon::now()->subDays($ik)->format('Y-m-d');
if((container('customerModel')->checkIfHoliday($date_check) == false) && (container('customerModel')->checkIfWeekend_2($date_check) == false))
{
$j = $j + 1;
}
}
while((container('customerModel')->checkIfHoliday($date_check) == true) || (container('customerModel')->checkIfWeekend_2($date_check) == true))
{
$ik = $ik + 1;
$date_check = Carbon::now()->subDays($ik)->format('Y-m-d');
}
foreach($marginClients as $client)
{
//get margin loan limit (combine both staff and commercial if applicable)
$marginLimit = $this->marginClientTable()
->selectRaw('SUM(loanAmount) as margin')
->where([
["CustID", "=", $client["CustID"]],
])
->get()[0]->margin;
//get current margin balance from cash balance endpoint
$client['ledgerType'] = "NGN";
$client['businessInvolvement'] = STOCKBROKING_DB_NAME;
$client['involvementType'] = "STK";
//to return client cash balance as at now
// $marginBalance = $this->getTotalCashBalanceByLedgerType($client)['margin'];
$date = Carbon::now()->format('Y-m-d');
//to return client cash balance (excluding stock purchase transactions) where value date is equal to today
$debitBalance_ = formatIWRes(container('IWSRequest')->PGetData2('csp_0036', "{$date}|{$client['SECID']}|" . STOCKBROKING_MARGIN_ACC_ID . "|NGN", STOCKBROKING_DB_NAME))['data']??[];
// $debitBalance = array_sum(array_column($debitBalance_, 'Balance')) ?? 0;
$debitBalance_1 = end($debitBalance_);
$debitBalance = $debitBalance_1['Balance'];
//to return client cash balance (excluding stock purchase transactions) where value date is equal to today
$debitStockBalance_ = formatIWRes(container('IWSRequest')->PGetData2('csp_0037', "{$date_check}|{$client['SECID']}|" . STOCKBROKING_MARGIN_ACC_ID . "|NGN", STOCKBROKING_DB_NAME))['data']??[];
$debitStockBalance = array_sum(array_column($debitStockBalance_, 'Debit')) ?? 0;
$marginSpent_ = $marginSpent = $isStaffRate = $notStaffRate = $isStaffDailyRate = $notStaffDailyRate = $isStaffLimit = $notStaffLimit = $staffTodayInterest = $notStaffTodayInterest = $TodayInterest = 0;
//get margin balance
$cashBalance = $debitBalance + $debitStockBalance;
$marginSpent_ = ($cashBalance < 0) ? $cashBalance : 0;
$marginBalance = $marginLimit + $marginSpent_;
/* var_dump($client["CustID"]);
// var_dump($debitBalance_);
var_dump("debitBalance: ".number_format($debitBalance, 2, '.', ','));
var_dump($date_check);
// var_dump($debitStockBalance_);
var_dump("debitStockBalance: ".number_format($debitStockBalance, 2, '.', ','));
var_dump("cashBalance: ".number_format($cashBalance, 2, '.', ','));
var_dump("marginLimit: ".number_format($marginLimit, 2, '.', ','));
var_dump("marginBalance: ".number_format($marginBalance, 2, '.', ','));
var_dump("marginSpent: ".number_format($marginSpent_, 2, '.', ',')); */
if($marginSpent_ < 0)
{
$marginSpent = $marginSpent_ * -1;
//compute today's interest rate 1. check if client is staff to use staff rate for the allocated limit
$isStaff = $this->marginClientTable()->where([["CustID", "=", $client["CustID"]],["loanType", "=", "staff"],])->first();
$isStaff = json_decode(json_encode($isStaff), true);
$staffLoan = count($isStaff); //check if user has staff account
$isStaffRate = $isStaff['rate']/100 ?? 0;
$isStaffDailyRate = ($isStaffRate > 0) ? $isStaffRate/365 : 0;
$isStaffLimit = $isStaff['loanAmount'] ?? 0;
$notStaff = $this->marginClientTable()->where([["CustID", "=", $client["CustID"]],["loanType", "!=", "staff"],])->first();
$notStaff = json_decode(json_encode($notStaff), true);
$notStaffLoan = count($notStaff); //check if user has commercial account
$notStaffRate = $notStaff['rate']/100 ?? 0;
$notStaffDailyRate = ($notStaffRate > 0) ? $notStaffRate/365 : 0;
$notStaffLimit = $notStaff['loanAmount'] ?? 0;
if($staffLoan > 0)
{
if($marginSpent < $isStaffLimit)
{
$TodayInterest = $TodayInterest + ($marginSpent * $isStaffDailyRate);
//check if user exist in margin Interest Accrued Table
$check = $this->marginInterestAccruedTable()->where([["CustID", "=", $client['CustID']],])->get();
$check = json_decode(json_encode($check), true);
if(count($check ) > 0)
{
//update today's staff interest in interest accrued table
$interestAccrued = $this->marginInterestAccruedTable()
->where([
// ["marginID", "=", $client['marginID']],
["CustID", "=", $client['CustID']],
])
->update([
"interest" => $check[0]["interest"]*1 + $TodayInterest,
]);
}else{
//insert today's staff interest to interest accrude table for first timers
$interestAccrued = $this->marginInterestAccruedTable()
->insertGetId([
'CustID' => $client['CustID'],
'SECID' => $client['SECID'],
'fullName' => $client['fullName'],
'interest' => $TodayInterest,
]);
}
//insert today's staff interest to interest log table
$dailyInterest = $this->marginInterestTable()
->insertGetId([
'CustID' => $client['CustID'],
'SECID' => $client['SECID'],
'fullName' => $client['fullName'],
'interest' => $TodayInterest,
'utilized' => $marginSpent,
]);
}elseif($marginSpent > $isStaffLimit)
{
$TodayInterest = $TodayInterest + ($isStaffLimit * $isStaffDailyRate);
$TodayInterest = $TodayInterest + (($marginSpent-$isStaffLimit) * $notStaffDailyRate);
//check if user exist in margin Interest Accrued Table
$check = $this->marginInterestAccruedTable()->where([["CustID", "=", $client['CustID']],])->get();
$check = json_decode(json_encode($check), true);
// var_dump($check[0]["interest"]);
if(count($check ) > 0)
{
//update today's staff interest in interest accrued table
$interestAccrued = $this->marginInterestAccruedTable()
->where([
// ["marginID", "=", $client['marginID']],
["CustID", "=", $client['CustID']],
])
->update([
"interest" => $check[0]["interest"]*1 + $TodayInterest,
]);
}else{
//insert today's staff interest to interest accrude table for first timers
$interestAccrued = $this->marginInterestAccruedTable()
->insertGetId([
'CustID' => $client['CustID'],
'SECID' => $client['SECID'],
'fullName' => $client['fullName'],
'interest' => $TodayInterest,
]);
}
//insert today's staff interest to interest log table
$dailyInterest = $this->marginInterestTable()
->insertGetId([
'CustID' => $client['CustID'],
'SECID' => $client['SECID'],
'fullName' => $client['fullName'],
'interest' => $TodayInterest,
'utilized' => $marginSpent,
]);
}
}elseif($notStaffLoan > 0){
$TodayInterest = $TodayInterest + ($marginSpent * $notStaffDailyRate);
//check if user exist in margin Interest Accrued Table
$check = $this->marginInterestAccruedTable()->where([["CustID", "=", $client['CustID']],])->get();
$check = json_decode(json_encode($check), true);
if(count($check ) > 0)
{
//update today's staff interest in interest accrued table
$interestAccrued = $this->marginInterestAccruedTable()
->where([
// ["marginID", "=", $client['marginID']],
["CustID", "=", $client['CustID']],
])
->update([
"interest" => $check[0]["interest"]*1 + $TodayInterest,
]);
}else{
//insert today's staff interest to interest accrude table for first timers
$interestAccrued = $this->marginInterestAccruedTable()
->insertGetId([
'CustID' => $client['CustID'],
'SECID' => $client['SECID'],
'fullName' => $client['fullName'],
'interest' => $TodayInterest,
]);
}
//insert today's staff interest to interest log table
$dailyInterest = $this->marginInterestTable()
->insertGetId([
'CustID' => $client['CustID'],
'SECID' => $client['SECID'],
'fullName' => $client['fullName'],
'interest' => $TodayInterest,
'utilized' => $marginSpent,
]);
}
/* var_dump("a staff");
var_dump("staff interest rate: ". $isStaffRate);
var_dump("staff marging limit: ". $isStaffLimit);
var_dump("staff daily rate: ". $isStaffDailyRate );
var_dump("not a staff");
var_dump("non staff interest rate: ". $notStaffRate);
var_dump("non staff marging limit: ". $notStaffLimit);
var_dump("non staff daily rate: ". $notStaffDailyRate);
var_dump("total margin limit: ". $marginLimit);
var_dump("total margin balance: ". $marginBalance);
var_dump("total margin spent: ". $marginSpent);
var_dump("staff today interest: ". $TodayInterest);
die(); */
}
}
return ['message' => 'Margin Interests for Today successfully Computed.'];
}
public function postMarginInterest()
{
$message1 = "Webhook Called->>";
$message2 = "Analyzing Details->>";
$message3 = "Validating Payload->>";
$message4 = "Verifying Originating IP Address->>" . $_SERVER['REMOTE_ADDR'];
$message5 = "Posting Monthly Margin Accrued Interest";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
//fetch all accrued interests from marginInterestAccruedTable
$data = $this->marginInterestAccruedTable()
->get();
$data = json_decode(json_encode($data), true);
//post accrued interests to GL
foreach($data as $d)
{
if($d["interest"] > 0)
{
$postInterest = container('IWSRequest')->postMarginInterest($d,STOCKBROKING_DB_NAME);
if($postInterest->StatusID == 0)
{
//reset interest accrued for client to 0
$this->marginInterestAccruedTable()
->where([["SECID", "=", $d['SECID']],])
->update(["interest" => 0.00]);
}
}
}
return ['message' => 'Margin Interests Accrued Successfully posted.'];
}
public function postMarginInterest__($payload)
{
$message1 = "Webhook Called->>";
$message2 = "Analyzing Details->>";
$message3 = "Validating Payload->>";
$message4 = "Verifying Originating IP Address->>" . $_SERVER['REMOTE_ADDR'];
$message5 = "Posting Monthly Margin Accrued Interest";
$log = $this->activity_log($message1,$message2,$message3,$message4,$message5);
//fetch all accrued interests from marginInterestAccruedTable
// $data = $this->marginInterestAccruedTable()
// ->get();
// $data = json_decode(json_encode($data), true);
//post accrued interests to GL
if($payload["marginInterest"] > 0)
{
$postInterest = container('IWSRequest')->postMarginInterest($payload,STOCKBROKING_DB_NAME);
// if($postInterest->StatusID == 0)
// {
// //reset interest accrued for client to 0
// $this->marginInterestAccruedTable()
// ->where([["SECID", "=", $d['SECID']],])
// ->update(["interest" => 0.00]);
// }
}
return ['message' => 'Margin Interests Accrued Successfully posted.'];
}
/* public function processMarginReport()
{
$marginClients = formatIWRes(container('IWSRequest')->getMarginClients())['data'];
return $marginClients;
}
*/
public function processMarginReport()
{
//get last 3 working days of last month
$today = date_create(date());
$today_ = date_format($today,"Y-m-d");
$lastMonth = date_format(date_sub(date_create(date()), date_interval_create_from_date_string("1 month")), "Y-m-d");
$prevLast = new \DateTime($lastMonth);
$lastDayOfLastMonth= $prevLast->format("Y-m-t");
$breakLastDayOfLastMonth =(explode("-",$lastDayOfLastMonth));
$lastDay = $day = $breakLastDayOfLastMonth[2];
$month = $breakLastDayOfLastMonth[1];
$year = $breakLastDayOfLastMonth[0];
$lastDayNumber = date("N", mktime(0,0,0,$month,$day,$year));
$lastDayName = date("l", mktime(0,0,0,$month,$day,$year));
// var_dump("Today is ". $today_);
// var_dump("Last month is ".$lastMonth);
// var_dump("Last date of last month is ".$lastDayOfLastMonth);
// var_dump("Last day of last month is ".$lastDay);
// var_dump("Last day of last month number is ".$lastDayNumber);
// var_dump("Last day of last month name is ".$lastDayName);
//get report start date i.e 3 to the last working day last month
$k = 0;
for($i=0; $i<=20; $i=$i+1)
{
$breakLastDayOfLastMonth =(explode("-",$lastDayOfLastMonth));
$lastDay = $day = $breakLastDayOfLastMonth[2];
$month = $breakLastDayOfLastMonth[1];
$year = $breakLastDayOfLastMonth[0];
$lastDayNumber = date("N", mktime(0,0,0,$month,$day,$year));
$lastDayName = date("l", mktime(0,0,0,$month,$day,$year));
//check date is not a weekend
// $checkWeekend = $this->checkIfHoliday(lastDayNumber);
$checkWeekend = $this->checkIfWeekend($lastDayNumber);
if($checkWeekend == false)
{
//check if date is a holiday
// $checkHols = $this->checkIfHoliday(lastDayNumber);
$checkHols = $this->checkIfHoliday($lastDayOfLastMonth);
if($checkHols == false)
{
$lastWorkingDay[$k] = $lastDayOfLastMonth;
// var_dump("Temp last working day of last month is ".$lastWorkingDay[$k]);
$k = $k +1;
// var_dump("K is: ".$k);
if($k == 4)
{
break;
}
}
}
// $lastDayOfLastMonth = date_format(date_sub(date_create($lastDayOfLastMonth), date_interval_create_from_date_string("1 day")), "Y-m-d");
$lastDayOfLastMonth_ = date_format(date_sub(date_create($lastDayOfLastMonth), date_interval_create_from_date_string("1 day")), "Y-m-d");
}
// var_dump($lastWorkingDay);
// die();
//proceed to process report for each client
//get all margin clients
$marginClients = formatIWRes(container('IWSRequest')->getMarginClients())['data'];
// var_dump($marginClients);
$z = 0; //to hold total margin balance per client for the month
$tVal = [];
foreach($marginClients as $client)
{
//get daily balances for each client
$SECID = $client['CustAID'];
$lastWorkingDay_ = $lastWorkingDay[2]; //actual last working date of last month
$sdate = $lastWorkingDay[3]; //a day before last working date of last month
$edate = $today_;
$dailyBalance = formatIWRes(container('IWSRequest')->getMarginClientDailyBalance($SECID,$sdate,$edate ))['data'];
// var_dump($dailyBalance);
// var_dump(count($dailyBalance));
//begin processing
$u=0; //initialize to skip first record, becuase it's a control record (a day before actual last working day)
$tBal = 0; //total balance per client
foreach($dailyBalance as $bal)
{
if($u > 0 )
{
/* if today's balance is equal to last working day's balance, no transaction took place, so skip
if today's balance is greater than last working day's balance, a credit transaction took place, so skip
if today's balance is less than last working day's balance, a debit transaction took place, so process */
//check if a debit transaction took place
if(($bal['CashBalance'] == $dailyBalance[$u-1]['CashBalance']) || ($bal['CashBalance'] > $dailyBalance[$u-1]['CashBalance']))
{
$tBal = $bal['CashBalance'];
$u=$u+1;
continue;
}elseif($bal['CashBalance'] < $dailyBalance[$u-1]['CashBalance'])
{
$tBal = $bal['CashBalance'];
}
}
$u=$u+1;
}
// die();
$z=$z+1;
}
// die();
return $marginClients ?? [];
}
public function checkIfHoliday($lastDayOfLastMonth)
{
$holidays = $this->getHolidays();
$hol = 0;
foreach($holidays as $holiday)
{
//var_dump("Holiday date is ".$holiday['HolidayDate']);
// if($holiday['HolidayDate'] == $lastDayOfLastMonth || $lastDayOfLastMonth == "2021-09-28")
if($holiday['HolidayDate'] == $lastDayOfLastMonth)
{
$hol = $hol + 1;
break;
}
}
// var_dump($hol);
if($hol > 0)
{
return true;
}else{
return false;
}
}
public function checkIfHoliday_US($lastDayOfLastMonth)
{
//get holidays
// var_dump($lastDayOfLastMonth);
// us_holidayTable
$holiday = $this->us_holidayTable()->where([["holidayDate", "=", $lastDayOfLastMonth]])->get();
if(count($holiday) > 0)
{
return true;
}else{
return false;
}
}
public function checkIfWeekend($lastDayNumber)
{
if($lastDayNumber == 6 || $lastDayNumber == 7)
{
return true;
}else{
return false;
}
}
public function checkIfWeekend_2($lastDayOfLastMonth)
{
$breakLastDayOfLastMonth =(explode("-",$lastDayOfLastMonth));
$lastDay = $day = $breakLastDayOfLastMonth[2];
$month = $breakLastDayOfLastMonth[1];
$year = $breakLastDayOfLastMonth[0];
$lastDayNumber = date("N", mktime(0,0,0,$month,$day,$year));
if($lastDayNumber == 6 || $lastDayNumber == 7)
{
return true;
}else{
return false;
}
}
public function getMarginClientDailyBalance($SECID, $sdate, $edate)
{
$marginClients = formatIWRes(container('IWSRequest')->getMarginClientDailyBalance($SECID, $sdate, $edate))['data'];
return $marginClients ?? [];
}
public function getMarginClients()
{
$marginClients = formatIWRes(container('IWSRequest')->getMarginClients())['data'];
return $marginClients ?? [];
}
/*
public function getClientMarginStatus($payload)
{
$marginStatus = formatIWRes(container('IWSRequest')->getClientMarginStatus($payload))['data'];
return $marginStatus ?? [];
} */
public function getClientMarginStatus($payload)
{
// $marginStatus = formatIWRes(container('IWSRequest')->getClientMarginStatus($payload))['data'];
$marginStatus = $this->marginClientTable()->where([["CustID","=",$payload['CustID']],
["status","=", 1]
])
->get();
$status = (count($marginStatus) > 0) ? "True" : "False";
return [["Response" => $status]];
}
public function getClientWalletStatus($payload)
{
// $marginStatus = formatIWRes(container('IWSRequest')->getClientMarginStatus($payload))['data'];
$walletStatus = $this->nubanTable()
->where([
["product", "=", "CSWALLET" ],
["CustID", "=", $payload['CustID'] ],
["accountNumber", "!=", null ],
])->get();
if(count($walletStatus) > 0)
{
$verify = formatIWRes(container('IWSRequest')->verifyProductInvolvement($payload['CAMID'] , "CSWALLET" , CAM_DB_NAME))['data'][0]['Response'];
return [["Response" => $verify]];
}else{
return [["Response" => "False"]];
}
}
public function getHolidays()
{
if (!$result = container('cache')->fetch('holidayData')) {
$data = formatIWRes(container('IWSRequest')->getHolidays())['data'];
$result = $data;
container('cache')->save('holidayData', $result, 60 * 60 * 24);
}
return $result;
}
/* public function getSectorAssetData($payload)
{
$payload['key'] = $this->stripVariable($payload['key']);
$payload['value'] = $this->stripVariable($payload['value']);
// var_dump($payload);
$res = formatIWRes(container('IWSRequest')->getSectorAssetData($payload))['data'];
// var_dump($res);
//get additional data from md per StockCode
$i=$j=0;
$instrument = formatIWRes(container('IWSRequest')->MD(90001041, null, STOCKBROKING_DB_NAME))['data'] ?? [];
$instrument_ = formatIWRes(container('IWSRequest')->getSectorAssetData_($payload))['data'] ?? [];
//update stockcode that have information in MD response
foreach($res as $md)
{
foreach($instrument as $details)
{
if($md['StockCode'] == $details['Symbol'] || $md['StockCode'] == "ABBEYBDS")
// if($md['StockCode'] == "ABBEYBDS")
{
// $res[$i] = array_merge($res[$i],$details);
// var_dump($md['StockCode']);
// var_dump($details['Symbol']);
// var_dump($dts);
// die();
continue;
}
}
$i=$i+1;
}
//update stockcode that do not have information in MD response by getting additional info from CS_0028
foreach($res as $quote)
{
foreach($instrument_ as $detail)
{
if($quote['StockCode'] == $detail['StockCode'] && (!isset($quote['% Chg']) || is_null($quote['% Chg'])))
{
$res[$j] = array_merge($res[$j],$detail);
$res[$j]['% Chg'] = "0.00";
$res[$j]['Symbol'] = $quote['StockCode'];
$res[$j]['Change'] = "0.0000";
continue;
}
}
$res[$j]['PClose'] = ($res[$j]['PClose'] == "" || is_null($res[$j]['PClose']) || empty($res[$j]['PClose']) ||!isset($res[$j]['PClose'])) ? "0" : $res[$j]['PClose'];
$res[$j]['Trades'] = ($res[$j]['Trades'] == "" || is_null($res[$j]['Trades']) || empty($res[$j]['Trades']) ||!isset($res[$j]['Trades'])) ? "0" : $res[$j]['Trades'];
$res[$j]['Open'] = ($res[$j]['Open'] == "" || is_null($res[$j]['Open']) || empty($res[$j]['Open']) ||!isset($res[$j]['Open'])) ? "0" : $res[$j]['Open'];
$res[$j]['Close'] = ($res[$j]['Close'] == "" || is_null($res[$j]['Close']) || empty($res[$j]['Close']) ||!isset($res[$j]['Close'])) ? "0" : $res[$j]['Close'];
$j=$j+1;
}
return $res ?? [];
} */
/* public function getSectorAssetType($payload)
{
$payload['key'] = $this->stripVariable($payload['key']);
$res = formatIWRes(container('IWSRequest')->getSectorAssetType($payload))['data'];
return $res ?? [];
} */
public function getSectorAssetType($payload)
{
$payload['key'] = $this->stripVariable($payload['key']);
$var = [];
$var = $payload['key'];
/*
$res = $this->assetClass_SectorTable()
->select('count(*) as Total', $payload['key'])
->groupBy($payload['key'])
->get(); */
$res = $this->assetClass_SectorTable()
// ->selectRaw($payload['key'], "{$payload['key']}, count({$payload['key']})")
->selectRaw("{$payload['key']}, count(*)")
->groupBy($payload['key'])
->get();
return $res ?? [];
}
public function getAllCAMDeals()
{
$deals = $this->CAMDealTable()->get();
return $deals ?? [];
}
public function bookCAMInvestment($payload)
{
$book = formatIWRes(container('IWSRequest')->bookCAMInvestment($payload));
return $book;
}
public function breakCAMInvestment($payload)
{
if(strtoupper($payload['instrumentType'] == "CAM-MMI") || strtoupper($payload['instrumentType']) == "CAM-MMIGBP" || strtoupper($payload['instrumentType'] == "MMI") || strtoupper($payload['instrumentType']) == "MMI-GBP")
{
$payload['penalRate'] = 50;
$payload['penalAmount'] = 0;
}elseif(strtoupper($payload['instrumentType']) == "CAM-EIN" || strtoupper($payload['instrumentType']) == "EIN" )
{
$payload['penalRate'] = 0;
$payload['penalAmount'] = $payload['penalty'];
}elseif(strtoupper($payload['instrumentType']) == "CAM-FI" || strtoupper($payload['instrumentType']) == "FI-FI" )
{
$payload['penalRate'] = 30;
$payload['penalAmount'] = 0;
}else
{
// $payload['penalRate'] = 0;
// $payload['penalAmount'] = $payload['penalty'] ?? 0;
return["code" => 400, "message" => "You are not allowed to break " . $payload['instrumentType']];
}
$break = formatIWRes(container('IWSRequest')->breakCAMInvestment($payload))['data'];
return $break ?? [];
}
public function computeBreakCAMInvestment($payload)
{
/* if(strtoupper($payload['instrumentType'] == "CAM-MMI") || strtoupper($payload['instrumentType']) == "CAM-MMIGBP" || strtoupper($payload['instrumentType'] == "MMI") || strtoupper($payload['instrumentType']) == "MMI-GBP")
{
$payload['penalRate'] = 50;
}elseif(strtoupper($payload['instrumentType']) == "CAM-EIN" || strtoupper($payload['instrumentType']) == "EIN" )
{
$payload['penalRate'] = 50;
}elseif(strtoupper($payload['instrumentType']) == "CAM-FI" || strtoupper($payload['instrumentType']) == "FI-FI" )
{
$payload['penalRate'] = 30;
}else{
$payload['penalRate'] = 0;
}
$payload['penalAmount'] = 0; */
//get investment details using Trans No
// $actual = formatIWRes(container('IWSRequest')->getActiveCAMInvestmentByTransNo($payload))['data'];
/* $active = formatIWRes(container('IWSRequest')->getActiveCAMInvestment($payload))['data']; //temporary until kolade gets an endpoint to fetch investment by TransNo
foreach($active as $investment)
{
if($investment["Trans#"] == $payload["transNo"])
{
$actual = $investment;
break;
}
} */
$actual = formatIWRes(container('IWSRequest')->getActiveCAMInvestmentByTransNo($payload))['data'][0];
//check if instrument types matched
// var_dump($actual['InstrumentType']);
if(strtoupper($payload['instrumentType']) != strtoupper($actual['InstrumentType']))
{
return ["code" => 400,"message" => "Mismatched Instrument Types"];
}
//check if chgAmount is gteater to Market Value
if(strtoupper($payload['chgAmount']) > strtoupper($actual['MarketValue']))
{
return ["code" => 400,"message" => "Liquidation Amount Exceeds Investment Market Value"];
}
//Check if there is unused tenure
$transNo = $payload['transNo'];
$instrumentType = $actual['InstrumentType'];
$product = $actual['Eurobond Name'];
$remainderTenure = $actual["RemainderTenure"] *1;
$usedTenure = $actual["ExpiredTenure"] *1 ;
$oldTenure = $remainderTenure + $usedTenure;
$accruedCoupon = $actual["Interest"] *1;
$oldRate = $rate = ($actual["Rate"] *1)/100;
$principal = $actual["Principal Amount"] *1;
$chgAmount = $payload['chgAmount'];
$currentValue = $actual["MarketValue"] *1;
if(strtoupper($actual["InstrumentType"]) == "CAM-EIN" || strtoupper($actual["InstrumentType"]) == "EIN" )
{
$newTenure = (is_int($usedTenure/365)) ? ($usedTenure/365) : floor($usedTenure/365) + 1;
$newTenure = $newTenure . " years";
$getNewRate = $this->CAMRateTable()->where([["tenure", "=", $newTenure],["instrumentType", "=", "CAM-EIN"]])->first();
// $getNewRate = $this->CAMRateTable()->where([["tenure", "=", $newTenure],["instrumentType", "=", strtoupper($actual["InstrumentType"])]])->first();
}elseif(strtoupper($actual["InstrumentType"]) == "CAM-FI" || strtoupper($actual["InstrumentType"]) == "FI-FI" ){
if($remainderTenure <= 30)
{
$newTenure = 30;
}if($remainderTenure > 30 && $remainderTenure <= 60 )
{
$newTenure = 60;
}elseif($remainderTenure > 60 && $remainderTenure <= 90 )
{
$newTenure = 90;
}elseif($remainderTenure > 90 && $remainderTenure <= 180 )
{
$newTenure = 180;
}elseif($remainderTenure > 180 && $remainderTenure <= 365 )
{
$newTenure = 365;
}
$newTenure = $newTenure . " days";
// var_dump($newTenure);
$getNewRate = $this->CAMRateTable()->where([["tenure", "=", $newTenure],["instrumentType", "=", "CAM-FI"]])->first();
// $getNewRate = $this->CAMRateTable()->where([["tenure", "=", $newTenure],["instrumentType", "=", strtoupper($actual["InstrumentType"])]])->first();
}elseif(strtoupper($actual["InstrumentType"]) == "CAM-MMI" || strtoupper($actual["InstrumentType"]) == "MMI"){
if($remainderTenure <= 90 )
{
$newTenure = 90;
}elseif($remainderTenure > 90 && $remainderTenure <= 180 )
{
$newTenure = 180;
}elseif($remainderTenure > 180 && $remainderTenure <= 365 )
{
$newTenure = 365;
}
$newTenure = $newTenure . " days";
$getNewRate = $this->CAMRateTable()->where([["tenure", "=", $newTenure],["instrumentType", "=", "CAM-MMI"]])->first();
// $getNewRate = $this->CAMRateTable()->where([["tenure", "=", $newTenure],["instrumentType", "=", strtoupper($actual["InstrumentType"])]])->first();
}elseif(strtoupper($actual["InstrumentType"]) == "CAM-MMIGBP" || strtoupper($actual["InstrumentType"]) == "MMI-GBP"){
$newTenure = 365;
$newTenure = $newTenure . " days";
$getNewRate = $this->CAMRateTable()->where([["tenure", "=", $newTenure],["instrumentType", "=", "CAM-MMIGBP"]])->first();
// $getNewRate = $this->CAMRateTable()->where([["tenure", "=", $newTenure],["instrumentType", "=", strtoupper($actual["InstrumentType"])]])->first();
}
$newRate = (trim($getNewRate->rate,"%") * 1)/100;
$oldDailyRate = $oldRate/360;
$newDailyRate = $newRate/360;
/* $getNewRate = $this->CAMRateTable()->where([["tenure", "=", "3 years"],["instrumentType", "=", "CAM-EIN"]])->first();
var_dump($getNewRate);
$newRate = trim($getNewRate->rate,"%");
var_dump($newRate); */
// var_dump($transNo);
// var_dump($principal);
// die();
//check if investment is running or terminated
if ($remainderTenure > 0)
{
//check if instrumentType is EIN or CAM-EIN
if(strtoupper($actual["InstrumentType"]) == "CAM-MMI" || strtoupper($actual["InstrumentType"]) == "CAM-MMIGBP" || strtoupper($actual["InstrumentType"]) == "MMI" || strtoupper($actual["InstrumentType"]) == "MMI-GBP")
{
if($remainderTenure <= 0)
{
$penalty = 0.00;
$liquidationAmount = $chgAmount + $accruedCoupon - $penalty;
}else{
$penalty = ($accruedCoupon > 0) ? $accruedCoupon/2 : 0.00;
$liquidationAmount = $chgAmount + $accruedCoupon - $penalty;
}
}elseif(strtoupper($actual["InstrumentType"]) == "CAM-FI" || strtoupper($actual["InstrumentType"]) == "FI-FI" )
{
if($remainderTenure <= 0)
{
$penalty = 0.00;
$liquidationAmount = $chgAmount + $accruedCoupon - $penalty;
}else{
$penalty = ($accruedCoupon > 0) ? ($accruedCoupon * 30/100) : 0.00;
$liquidationAmount = $chgAmount + $accruedCoupon - $penalty;
}
}elseif(strtoupper($actual["InstrumentType"]) == "CAM-EIN" || strtoupper($actual["InstrumentType"]) == "EIN" ){
// var_dump("got here");
if($remainderTenure <= 0)
{
$penalty = 0.00;
$liquidationAmount = $chgAmount + $accruedCoupon - $penalty;
}else{
//compute paidCoupoun
$investmentDate = $actual['EffectiveDate'];
$investmentDate_ = date_create($payload['investmentDate']);
$investmentDate_1 = date_create($payload['investmentDate']);
$investmentDate = date_format($investmentDate_,"Y-m-d");
$idate = explode("-",$investmentDate);
$iyear = $idate[0]*1;
$imonth = $idate[1]*1;
$iday = $idate[2]*1;
$currentDate = Carbon::now()->format('Y-m-d');
$currentDate_ = date_create($currentDate);
$cdate = explode("-",$currentDate);
$cyear = $cdate[0]*1;
$cmonth = $cdate[1]*1;
$cday = $cdate[2]*1;
$date_diff_paidCoupon = date_diff($investmentDate_,$currentDate_);
// $date_diff_date_diff_paidCoupon_ = $date_diff_paidCoupon->format("%R%m");
$date_diff_date_diff_paidCoupon_ = $date_diff_paidCoupon->format("%R%a");
/* $today = date_create(date());
$today_ = date_format($today,"Y-m-d");
$lastMonth = date_format(date_sub(date_create(date()), date_interval_create_from_date_string("1 month")), "Y-m-d");
$prevLast = new \DateTime($lastMonth);
$lastDayOfLastMonth= $prevLast->format("Y-m-t");
$breakLastDayOfLastMonth =(explode("-",$lastDayOfLastMonth));
$lastDay = $day = $breakLastDayOfLastMonth[2];
$month = $breakLastDayOfLastMonth[1];
$year = $breakLastDayOfLastMonth[0];
$lastDayNumber = date("N", mktime(0,0,0,$month,$day,$year));
$lastDayName = date("l", mktime(0,0,0,$month,$day,$year));
*/
$noOfPaidCoupoun = $i = 0;
// $investmentDate_1 = date_create("4/23/2021 12:00:00 AM");
$i = 1;
$noOfPaidCoupoun = 0;
while ($i <= $date_diff_date_diff_paidCoupon_)
{
$nextDay = date_format(date_add($investmentDate_1, date_interval_create_from_date_string("1 day")), "Y-m-d");
//check if day is March 31 or Sept 30
$pdate = explode("-",$nextDay);
$pyear = $pdate[0]*1;
$pmonth = $pdate[1]*1;
$pday = $pdate[2]*1;
if(($pmonth == 3 && $pday == 31) || ($pmonth == 9 && $pday == 30))
{
$noOfPaidCoupoun = $noOfPaidCoupoun + 1;
}
// echo $nextDay . "<BR>";
$i = $i + 1;
}
// echo $noOfPaidCoupoun . "<BR>";
$paidCoupoun = ($principal * ($oldRate/2)) * $noOfPaidCoupoun;
// $paidCoupoun = (($principal * ($oldRate/100))/2) * $noOfPaidCoupoun;
$newAccruedCoupoun = $usedTenure * $newDailyRate * $principal;
$accruedCoupon = $newAccruedCoupoun;
// var_dump($newAccruedCoupoun);
// var_dump($accruedCoupon);
// var_dump($newDailyRate);
// var_dump($oldDailyRate);
// var_dump($newRate);
// var_dump($principal);
// var_dump($oldRate);
// var_dump($paidCoupoun);
// var_dump($newTenure);
// var_dump($usedTenure);
$penalty = ($newAccruedCoupoun > 0) ? ($newAccruedCoupoun/2) : 0.00;
$penalty = $penalty - $paidCoupoun;
// $liquidationAmount = $principal + $accruedCoupon;
// $liquidationAmount = $chgAmount + $penalty; -- 1
// $liquidationAmount = $chgAmount + $accruedCoupon - $penalty; -- 2
$liquidationAmount = $chgAmount + $newAccruedCoupoun - $penalty;
}
}
$data = ["chgAmount" => $chgAmount , "interestRate" => round($newRate*100,2) , "transNo" => $transNo , "instrumentType" => $instrumentType , "remainderTenure" => $remainderTenure ,"accruedCoupon" => $accruedCoupon ,"penalty" => $penalty ,"liquidationAmount" => $liquidationAmount,"product" => $product] ?? [];
return ["code" => 200, "message" => "Investment Liquidation Summary successfully Computed", "data" => $data] ;
}else{
return ["code" => 400, "message" => "This Investment is Terminated"];
}
}
public function getActiveCAMInvestment($payload)
{
$get = formatIWRes(container('IWSRequest')->getActiveCAMInvestment($payload))['data'];
$i = 0;
foreach($get as $active)
{
//update book Type
$book = $this->CAMProductTable()
->where([["instrumentType", "=", $active['InstrumentType']]])
->get();
if(count($book) == 0)
{
$book = $this->cpTable()
->where([["instrumentType", "=", $active['InstrumentType']]])
->get();
if(count($book) == 0)
{
$book = $this->tbillsTable()
->where([["instrumentType", "=", $active['InstrumentType']]])
->get();
}
}
$get[$i]['bookingType'] = $book[0]->bookingType;
$get[$i]['productType'] = $book[0]->productType;
$get[$i]['investmentType'] = $book[0]->investmentType;
$get[$i]['tenure'] = $get[$i]['RemainderTenure'] + $get[$i]['ExpiredTenure'];
//cater for CSP-ASSET management left over investments
if(strtoupper($active['InstrumentType']) == "MMI" || strtoupper($active['InstrumentType']) == "FI-FI" || strtoupper($active['InstrumentType']) == "MMI-GBP" || strtoupper($active['InstrumentType']) == "EIN")
{
$get[$i]['bookingType'] = "book";
}elseif(strtoupper($active['InstrumentType']) == "EUR-BOND" || strtoupper($active['InstrumentType']) == "FGN-BOND")
{
$get[$i]['bookingType'] = "request";
}
$i=$i+1;
}
return $get ?? [];
}
public function getActiveSMACAMInvestment($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['CAMID'] = $customerz[0]['CAMID'];
$cam = formatIWRes(container('IWSRequest')->getActiveSMACAMInvestment($payload))['data'];
return $cam ?? [];
}
public function getActiveSMACSSInvestment($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['CAMID'] = $customerz[0]['CAMID'];
$css = formatIWRes(container('IWSRequest')->getActiveSMACSSInvestment($payload))['data'];
return $css ?? [];
}
public function getSMAInvestmentTotal($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['CAMID'] = $customerz[0]['CAMID'];
if($payload["ledgerType"] == "NGN")
{
$total = 0;
// $css = formatIWRes(container('IWSRequest')->getActiveSMACSSInvestment($payload))['data'];
$cssTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACSSInvestment($payload))['data'];
// var_dump($cssTotal);
$total = array_sum(array_column($cssTotal, 'TotalCurrentValue')) ?? 0;
// $cam = formatIWRes(container('IWSRequest')->getActiveSMACAMInvestment($payload))['data'];
$camTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACAMInvestment($payload))['data'];
// var_dump($camTotal);
$total_ = array_sum(array_column($camTotal, 'TotalCurrentValue')) ?? 0;
$total = $total + $total_;
return $total ?? [];
}elseif($payload["ledgerType"] == "USD")
{
$total = 0;
/* $cssTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACSSInvestment($payload))['data'];
$total = array_sum(array_column($cssTotal, 'TotalCurrentValue')) ?? 0; */
$camTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACAMInvestment($payload))['data'];
$total_ = array_sum(array_column($camTotal, 'TotalCurrentValue')) ?? 0;
$total = $total + $total_;
return $total ?? [];
}elseif($payload["ledgerType"] == "GBP")
{
$total = 0;
/* $cssTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACSSInvestment($payload))['data'];
$total = array_sum(array_column($cssTotal, 'TotalCurrentValue')) ?? 0; */
$camTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACAMInvestment($payload))['data'];
$total_ = array_sum(array_column($camTotal, 'TotalCurrentValue')) ?? 0;
$total = $total + $total_;
return $total ?? [];
}
}
public function getAllSMAInvestments($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['CAMID'] = $customerz[0]['CAMID'];
if($payload["ledgerType"] == "NGN")
{
$totalPort = 0;
$cssTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACSSInvestment($payload))['data'];
$cssTotal_ = array_sum(array_column($cssTotal, 'TotalCurrentValue')) ?? 0;
$camTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACAMInvestment($payload))['data'];
$camTotal_ = array_sum(array_column($camTotal, 'TotalCurrentValue')) ?? 0;
$totalPort = $cssTotal_ + $camTotal_;
$cssPercentHolding = ($totalPort != 0) ? (($cssTotal_* 100)/$totalPort) : 0.00;
$camPercentHolding = ($totalPort != 0) ? (($camTotal_* 100)/$totalPort) : 0.00;
return[["business" => "Securities Trading", "holding" => $cssTotal_ , "percent" => $cssPercentHolding, "total" => $totalPort],["business" => "Fixed Income", "holding" => $camTotal_ , "percent" => $camPercentHolding, "total" => $totalPort]];
}elseif($payload["ledgerType"] == "USD")
{
$totalPort = 0;
$cssTotal = 0.00;
$cssTotal_ = 0.00;
$camTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACAMInvestment($payload))['data'];
$camTotal_ = array_sum(array_column($camTotal, 'TotalCurrentValue')) ?? 0;
$totalPort = $cssTotal_ + $camTotal_;
$cssPercentHolding = ($totalPort != 0) ? (($cssTotal_* 100)/$totalPort) : 0.00;
$camPercentHolding = ($totalPort != 0) ? (($camTotal_* 100)/$totalPort) : 0.00;
return[["business" => "Securities Trading", "holding" => $cssTotal_ , "percent" => $cssPercentHolding, "total" => $totalPort],["business" => "Fixed Income", "holding" => $camTotal_ , "percent" => $camPercentHolding, "total" => $totalPort]];
}elseif($payload["ledgerType"] == "GBP")
{
$totalPort = 0;
$cssTotal = 0.00;
$cssTotal_ = 0.00;
$camTotal = formatIWRes(container('IWSRequest')->getActiveTotalSMACAMInvestment($payload))['data'];
$camTotal_ = array_sum(array_column($camTotal, 'TotalCurrentValue')) ?? 0;
$totalPort = $cssTotal_ + $camTotal_;
$cssPercentHolding = ($totalPort != 0) ? (($cssTotal_* 100)/$totalPort) : 0.00;
$camPercentHolding = ($totalPort != 0) ? (($camTotal_* 100)/$totalPort) : 0.00;
return[["business" => "Securities Trading", "holding" => $cssTotal_ , "percent" => $cssPercentHolding, "total" => $totalPort],["business" => "Fixed Income", "holding" => $camTotal_ , "percent" => $camPercentHolding, "total" => $totalPort]];
}
}
public function getMFInvestmentTotal($payload)
{
$total = 0;
$result = formatIWRes(container('IWSRequest')->getAllMFInvestments($payload))['data'];
$total = array_sum(array_column($result, 'TotalAssetValue')) ?? 0;
return $total ?? [];
}
public function getAllMFInvestments($payload)
{
$totalPort = 0;
$result = formatIWRes(container('IWSRequest')->getAllMFInvestments($payload))['data'];
$totalPort = array_sum(array_column($result, 'TotalAssetValue')) ?? 0;
$i =0;
foreach($result as $res)
{
$percentHolding = ($totalPort != 0) ? (($res['TotalAssetValue']* 100)/$totalPort) : 0.00;
$result[$i]['percentHolding'] = $percentHolding;
$result[$i]['totalValue'] = $totalPort;
$MFLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $res["cashAccount"]],['instrumentType' ,"=", $res["FundCode"]]])->first();
$MFLien = json_decode(json_encode($MFLien),true);
$result[$i]['existingLien'] = $MFLien["lienValue"]*1 ?? 0;
$i=$i+1;
}
return $result;
}
public function getActiveCAMInvestmentByTransNo($payload)
{
$get = formatIWRes(container('IWSRequest')->getActiveCAMInvestmentByTransNo($payload))['data'];
$i = 0;
foreach($get as $active)
{
//update book Type
$book = $this->CAMProductTable()
->where([["instrumentType", "=", $active['InstrumentType']]])
->get();
if(count($book) == 0)
{
$book = $this->cpTable()
->where([["instrumentType", "=", $active['InstrumentType']]])
->get();
if(count($book) == 0)
{
$book = $this->tbillsTable()
->where([["instrumentType", "=", $active['InstrumentType']]])
->get();
}
}
$get[$i]['bookingType'] = $book[0]->bookingType;
$get[$i]['productType'] = $book[0]->productType;
$get[$i]['investmentType'] = $book[0]->investmentType;
$get[$i]['tenure'] = $get[$i]['RemainderTenure'] + $get[$i]['ExpiredTenure'];
//cater for CSP-ASSET management left over investments
if(strtoupper($active['InstrumentType']) == "MMI" || strtoupper($active['InstrumentType']) == "FI-FI" || strtoupper($active['InstrumentType']) == "MMI-GBP" || strtoupper($active['InstrumentType']) == "EIN")
{
$get[$i]['bookingType'] = "book";
}elseif(strtoupper($active['InstrumentType']) == "EUR-BOND" || strtoupper($active['InstrumentType']) == "FGN-BOND")
{
$get[$i]['bookingType'] = "request";
}
$i=$i+1;
}
return $get ?? [];
}
public function getTerminatedCAMInvestment($payload)
{
$get = formatIWRes(container('IWSRequest')->getTerminatedCAMInvestment($payload))['data'];
return $get ?? [];
}
public function getAllTerminatedCAMInvestment($payload)
{
$get = formatIWRes(container('IWSRequest')->getAllTerminatedCAMInvestment($payload))['data'];
return $get ?? [];
}
public function getPaymentChannel($payload)
{
$get = ["Card" => "card","Bank Transfer" => "bank_transfer","Bank" => "bank","USSD" => "ussd"];
return $get ?? [];
}
public function verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB)
{
$verify = formatIWRes(container('IWSRequest')->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB))['data'][0]['Response'];
if(strtoupper($verify) == "TRUE")
{
return ["code"=>200, "message"=>"Client has ".$INVOLVEMENT . " involvement", "data"=> $verify];
}else{
return ["code"=>200, "message"=>"Client does not have ".$INVOLVEMENT . " involvement", "data"=> $verify];
}
}
public function getClientProductInvolvements($payload)
{
$productInvolvement = formatIWRes(container('IWSRequest')->getClientProductInvolvements($payload))['data'];
return $productInvolvement ?? [];
}
public function getNonClientProductInvolvements($payload)
{
$productInvolvement = formatIWRes(container('IWSRequest')->getNonClientProductInvolvements($payload))['data'];
return $productInvolvement ?? [];
}
public function getCSCSNumber($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['SECID'] = $customerz[0]['SECID'];
$cscs = formatIWRes(container('IWSRequest')->getCSCSNumber($payload))['data'];
if(count($cscs) > 0)
{
return ["code"=>200, "message"=>"CSCS Number(s) Fetched", "data"=> $cscs];
}else{
return ["code"=>200, "message"=>"No CSCS Number Found", "data"=> $cscs ?? []];
}
}
public function isCSCSNumber($SECID)
{
$payload["SECID"] = $SECID;
$cscs = formatIWRes(container('IWSRequest')->getCSCSNumber($payload))['data'];
if(count($cscs) > 0)
{
return true;
}else{
return false;
}
}
public function resolveBankAccount($payload)
{
//verify bank account number
$verify = container('PaystackRequest')->resolveBankAccount($payload);
if($verify["status"] == true)
{
return ["code"=>200, "message"=>"Successfully Verfied Bank Details", "data"=> $verify["data"]];
}else{
return ["code"=>400, "message"=>"Failed to Verfy Bank Details", "data"=> $verify["message"]];
}
}
public function createTransferRecipient($payload)
{
//create Transfer Client
$normalizedString = preg_replace('/\s+/', ' ', $payload['fullName']); // Replace multiple spaces with a single space
$fullName = explode(' ',$normalizedString);
$payload['fundCode'] = 'CSWALLET';
$payload['product'] = 'CSWALLET';
$payload['company'] = 'GROUP';
$payload['firstName'] = $fullName[1];
$payload['lastName'] = $fullName[0];
$verifyDetails = container('PaystackRequest')->resolveBankAccount($payload);
if($verifyDetails["status"] == true)
{
$transferClient = $this->transferTable()
->insertGetId([
'CustID' => $payload['CustID'],
'SECID' => $payload['SECID'],
'CAMID' => $payload['CAMID'],
'ASSETID' => $payload['ASSETID'],
'fullName' => $payload['fullName'],
'firstName' => $payload['firstName'],
'lastName' => $payload['lastName'],
'emailAddress' => $payload['emailAddress'],
'phoneNumber' => $payload['phoneNumber'],
'accountName' => $verifyDetails["data"]['account_name'],
'accountNumber' => $verifyDetails["data"]['account_number'],
'customerCode' => $payload['customerCode'],
'bankName' => $payload['bankName'],
'bankCode' => $payload['bankCode'],
'idType' => "bvn",
'idValue' => $payload['idValue'],
'fundCode' => $payload['fundCode'],
'product' => $payload['product'],
'company' => $payload['company'],
'integration' => $payload['integration'],
'currency' => "NGN",
]);
}
else{
return ["code"=>400, "message"=>"Unable to verify your bank details. Please contact us"];
}
$verify = container('PaystackRequest')->createTransferRecipient($payload);
if($verify["status"] == true)
{
//update transfer recipient table with recipient code
$this->transferTable()
->where([
// ["customerCode", "=", $payload['customerCode']],
["accountNumber", "=", $payload['accountNumber']],
])
->update([
"recipientCode" => $verify["data"]['recipient_code'],
'customerCode' => $verify["data"]['recipient_code'],
"integration" => $verify["data"]['integration'],
"accountName" => $verify["data"]['details']['account_name'],
"bankName" => $verify["data"]['details']['bank_name'],
]);
return ["code"=>200, "message"=>"Transfer Client Successfully Created", "data"=> $verify["data"]];
}else{
return ["code"=>400, "message"=>"Failed to Create Transfer Client", "data"=> $verify["message"]];
}
}
//Wallet Withdrawal below 5m for immediate processed
public function withdrawFromWallet($payload)
{
$lockKey = "lock:wallet:" . $payload['CustID'];
$lockTimeout = 60 * 5; // Lock timeout in seconds, adjust as needed
try
{
$cache = container('cache')->fetch($lockKey);
if($cache === false)
{
acquireLock($lockKey, $lockTimeout);
}
else
{
return ["code" => 423, "message" => "Please hold off for a bit before retrying your transaction. Thank you for your patience!"];
}
//check if limit is okay
$dailyBalance = $this->dailyWalletSpent($payload["CustID"]);
if($payload["transactionAmount"] > $dailyBalance["dailyBalance"])
{
return [
"message" => "You have exceeded your withdrawal limit for today. Try again tomorrow",
"code" => 400,
];
}
//check kyc status
$kyc = $this->checkIfcustomerKYCIsComplete($payload['CustID'],MIDDLEWARE_DB_NAME)[0]["IsKYC"];
if(strtoupper($kyc) == "TRUE")
{
//check wallet balance
$balance = container('mutualFundModel')->getWalletBalance($payload);
if($balance['balance'] < $payload['amount'] )
{
return [
"message" => "You have insufficent cash balance for this transaction",
"code" => 400,
"data" => ["Your current balance is: N" . number_format($balance['balance'], 2, '.', ',') ] ?? []
];
}
//get customer details and recipient code from transfer client table
$customer = $this->transferTable()
->where([
// ["product", "=", "CSWALLET" ],
["recipientCode", "=", $payload['recipientCode'] ],
])->get()[0];
if(count($customer) > 0)
{
$payload += json_decode(json_encode($customer),true);
// var_dump($payload);
$payload['BVN'] = $payload['idValue'];
}else{
}
//post wallet transaction for debit
$payload['transactionType'] = "DEBIT";
$payload['transactionAmount'] = $payload['amount'];
$payload['cash_account_id'] = CSWALLET_DEBIT_ACCOUNT;
$payload['productType'] = "BANK";
$payload["client_id"] = $payload["CAMID"];
$payload["reference"] = "CWD". container('mutualFundModel')->generateWalletTransactionId();
$payload["narration"] = "Being debit from ". $payload["fullName"]."'s wallet to credit Bank"; //for wallet withdrawal to customer's bank
$post = container('PaystackGatewayModel')->createTransactionOnInfowareForWalletWithdrawal($payload);
if($post["code"] == 200)
{
$payload['valueDate'] = $post["date_"] ;
$payload["transactionRef"] = $payload["reference"];
$payload["fundCode"] = CSWALLET_INVOLVEMENT;
//create wallet spent
$this->createDailyWalletSpent($payload);
//process cash transfer on paystack
$withdraw = container('PaystackRequest')->withdrawFromWallet($payload);
if($withdraw["status"] == true)
{
$data_res = ["code"=>200, "message"=>"Transfer to bank is successful", "data"=> $withdraw["message"] ?? []];
$payload["comment"] = "processed by client";
$payload["isPaid"] = 1;
$payload["isPaidDate"] = Carbon::now()->format('Y-m-d H:i:s');
}else{
//Notify RICA of transaction failure
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Partial Failed Wallet Transaction - Paystack: " .$withdraw["message"])
->usingView('failed_wallet_transaction_notification', $record)
->send();
// $data_res = ["code"=>200, "message"=>"Transfer To Bank in Progress", "data"=> "Transfer in progress"];
$data_res = ["code"=>200, "message"=>"Transfer to bank in progress", "data"=> []];
$payload["comment"] = "to be processed by FINCON";
}
}else{
//Notify RICA of transaction failure
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Failed Wallet Transaction - Posting issue on Infoware")
->usingView('failed_wallet_transaction_notification', $record)
->send();
// return ["code"=>200, "message"=>"Transfer To Bank in Progress", "data"=> []];
return ["code"=>400, "message"=>"Your withdrawal request failed. Please contact us", "data"=> []];
}
//Post debit to client's wallet in local table
$wallet = container('mutualFundModel')->debitWallet($payload);
if($wallet["code"] == 200)
{
//log withdrawal request to table
$submitRequest = $this->withdrawRequestTable()
->insertGetId([
'CustID' => $payload['CustID'],
'SECID' => $payload['SECID'],
'CAMID' => $payload['CAMID'],
'amount' => $payload['amount'],
'fullName' => $payload['fullName'],
'initiator' => $payload['fullName'],
'initiatorDate' => Carbon::now()->format('Y-m-d H:i:s'),
'authorizer' => $payload['fullName'],
'authorizerDate' => Carbon::now()->format('Y-m-d H:i:s'),
'emailAddress' => $payload['emailAddress'],
'accountOfficerEmail' => $payload['accountOfficerEmail'],
'phoneNumber' => $payload['phoneNumber'],
'bankName' => $payload['bankName'],
'status' => "approved",
'ipaddress' => $this->get_client_ip(),
'authorizer_status' => "processed_by_client",
'rica_status' => "processed_by_client",
'fincon_status' => "processed_by_client",
'pm_status' => "processed_by_client",
'ia_status' => "processed_by_client",
'accountNumber' => $payload['accountNumber'],
'recipientCode' => $payload['recipientCode'],
'payment_status' => ($withdraw["status"] == true) ? "TRUE" : "FALSE",
'payment_comment' => $withdraw["message"],
'transactionRef' => $payload['reference'],
'iapm' => "client",
'autopay_status' => "processed_by_client",
'autopay' => $payload['fullName'],
'autopay_comment' => "Auto Processed By Client",
'autopayDate' => Carbon::now()->format('Y-m-d H:i:s'),
'BVN' => $payload['BVN'],
]);
// var_dump("3 ".$payload['BVN']);
//notify FINCON for bank to bank posting
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Successful Wallet Transaction")
->usingView('wallet_transaction_notification', $record)
->send();
return $data_res;
}else //Notify RICA of transaction failure
{
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"],
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->bcc(\getenv("IT-UNIT-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Partial Failed Wallet Transaction - Unable to update wallet report database")
->usingView('failed_wallet_transaction_notification', $record)
->send();
return ["code"=>200, "message"=>"Transfer To Bank in Progress", "data"=> []];
}
}else{
return ["code"=>400, "message"=>"Unable to Process Transfer Request Due to Incomplete KYC. Please Complete your KYC", "data"=> []];
}
}catch(\Exception $e){
return ["code" => 500, "message" => "An error occurred: " . $e->getMessage()];
}finally{
// releaseLock($lockKey);
}
}
//Wallet Withdrawal bewteen 5m and 100m to be processed by IA
public function withdrawFromWalletIAPM($payload)
{
$lockKey = "lock:wallet:" . $payload['CustID'];
$lockTimeout = 60 * 5; // Lock timeout in seconds, adjust as needed
try
{
$cache = container('cache')->fetch($lockKey);
if($cache === false)
{
acquireLock($lockKey, $lockTimeout);
}
else {
return ["code" => 423, "message" => "Please hold off for a bit before retrying your transaction. Thank you for your patience!"];
}
//check wallet balance
$balance = container('mutualFundModel')->getWalletBalance($payload);
if($balance['balance'] < $payload['amount'] )
{
return [
"message" => "You have insufficent cash balance for this transaction",
"code" => 400,
"data" => ["Your current balance is: " . $balance['balance']] ?? []
];
}
//get customer details and recipient code from transfer client table
$customer = $this->transferTable()
->where([
// ["product", "=", "CSWALLET" ],
["recipientCode", "=", $payload['recipientCode'] ],
])->get()[0];
if(count($customer) > 0)
{
$payload += json_decode(json_encode($customer),true);
// var_dump($payload);
$payload['BVN'] = $payload['idValue'];
}
//post wallet transaction for debit
$payload['transactionType'] = "DEBIT";
$payload['transactionAmount'] = $payload['amount'];
$payload['cash_account_id'] = CSWALLET_DEBIT_ACCOUNT;
$payload['productType'] = "BANK";
$payload["client_id"] = $payload["CAMID"];
$payload["reference"] = "CWD". container('mutualFundModel')->generateWalletTransactionId();
$payload["narration"] = "Being debit from ". $payload["fullName"]."'s wallet to credit Bank"; //for wallet withdrawal to customer's bank
$post = container('PaystackGatewayModel')->createTransactionOnInfowareForWalletWithdrawal($payload);
if($post["code"] == 200)
{
$payload['valueDate'] = $post["date_"] ;
$payload["transactionRef"] = $payload["reference"];
$payload["fundCode"] = CSWALLET_INVOLVEMENT;
//create wallet spent
$this->createDailyWalletSpent($payload);
// $data_res = ["code"=>200, "message"=>"Your withdrawal request was submitted successfully", "data"=> []];
$payload["comment"] = "to be processed by FINCON";
}else{ //Notify RICA of transaction failure
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Failed Wallet Transaction - Posting issue on Infoware")
->usingView('failed_wallet_transaction_notification', $record)
->send();
return ["code"=>400, "message"=>"Your withdrawal request failed. Please contact us", "data"=> []];
}
//Post debit to client's wallet in local table
$wallet = container('mutualFundModel')->debitWallet($payload);
if($wallet["code"] == 200)
{
//log withdrawal request to table
$submitRequest = $this->withdrawRequestTable()
->insertGetId([
'CustID' => $payload['CustID'],
'SECID' => $payload['SECID'],
'CAMID' => $payload['CAMID'],
'amount' => $payload['amount'],
'fullName' => $payload['fullName'],
'emailAddress' => $payload['emailAddress'],
'accountOfficerEmail' => $payload['accountOfficerEmail'],
'phoneNumber' => $payload['phoneNumber'],
'bankName' => $payload['bankName'],
'accountNumber' => $payload['accountNumber'],
'recipientCode' => $payload['recipientCode'],
'iapm' => ($payload["amount"]*1 > SELF_APPROVE*1 && $payload["amount"]*1 <= IA_APPROVE*1) ? "IA" : "PM",
'initiator' => $payload['fullName'],
'initiatorDate' => Carbon::now()->format('Y-m-d H:i:s'),
'BVN' => $payload['BVN'],
]);
//send withrawal request via email to IA and PM
$payload['transactionType'] = "DEBIT";
$payload['transactionAmount'] = $payload['amount'];
$payload['cash_account_id'] = CSWALLET_DEBIT_ACCOUNT;
$payload['productType'] = "BANK";
$payload["client_id"] = $payload["CAMID"];
$payload["narration"] = "Being debit from ". $payload["fullName"]."'s wallet to credit Customer Bank Account"; //for wallet withdrawal to customer's bank
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"accountNumber" => $payload["accountNumber"],
"bankName" => $payload["bankName"],
"business" => $payload["company"],
];
$recipient = ($payload["transactionAmount"]*1 > SELF_APPROVE*1 && $payload["transactionAmount"]*1 <= IA_APPROVE*1) ? $payload["accountOfficerEmail"] : $payload["accountOfficerEmail"] . ", " . getenv("PM-EMAIL");
$view = ($payload["transactionAmount"]*1 > SELF_APPROVE*1 && $payload["transactionAmount"]*1 <= IA_APPROVE*1) ? 'IA_wallet_withdrawal_request' : 'PM_wallet_withdrawal_request';
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Wallet Withdrawal Request")
->usingView($view , $record)
->send();
}else{
(new Mailer())
->to($recipient)
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Wallet Withdrawal Request")
->usingView($view , $record)
->send();
}
return ["code"=>200, "message"=>"Your withdrawal request was submitted successfully", "data"=> []];
}else //Notify RICA of transaction failure
{
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"],
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->bcc(\getenv("IT-UNIT-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Partial Failed Wallet Transaction - Unable to update wallet report database")
->usingView('failed_wallet_transaction_notification', $record)
->send();
return ["code"=>200, "message"=>"Your withdrawal request was submitted successfully", "data"=> []];
}
}catch(\Exception $e){
return ["code" => 500, "message" => "An error occurred: " . $e->getMessage()];
}finally{
// releaseLock($lockKey);
}
}
/* //Wallet Withdrawal above 100m to be processed by PM
public function withdrawFromWalletPM($payload)
{
//check wallet balance
$balance = container('mutualFundModel')->getWalletBalance($payload);
if($balance['balance'] < $payload['amount'] )
{
return [
"message" => "You have insufficent cash balance for this transaction",
"code" => 400,
"data" => ["Your current balance is: " . $balance['balance']] ?? []
];
}
//get customer details and recipient code from transfer client table
$customer = $this->transferTable()
->where([
["product", "=", "CSWALLET" ],
["CustID", "=", $payload['CustID'] ],
])->get()[0];
if(count($customer) > 0)
{
$payload += json_decode(json_encode($customer),true);
}else{
//get client details from nuban Table
$customer = $this->nubanTable()
->where([
["product", "=", "CSWALLET" ],
["CustID", "=", $payload['CustID'] ],
])->get()[0];
if(count($customer) > 0)
{
$payload += json_decode(json_encode($customer),true);
}else{
return ["code"=>400, "message"=>"NUBAN customer does not exist", "data"=> []];
}
//get bank details
$bank = $this->getCustomerBankDetails($payload["CustID"])[0];
if(count($bank) > 0)
{
$payload['accountNumber'] = $bank['AcctNumber'];
$payload['bankCode'] = $bank['SortCode'];
if(is_null($payload['bankCode']) || empty($payload['bankCode']) || $payload['bankCode'] == "")
{
$icode = $this->bankCode($bank['BankName']);
$payload['bankCode'] = $icode->iCode;
}
$payload['bankName'] = $bank['BankName'];
$payload['BVN'] = (isset($payload['BVN']) && !is_null($payload['BVN']) && !empty($payload['BVN']) && $payload['BVN'] != "") ? $payload['BVN'] : $bank['BVN'];
//verify bank account number
$verify = container('PaystackRequest')->resolveBankAccount($payload);
if($verify["status"] == true)
{
$transferClient = $this->transferTable()
->insertGetId([
'CustID' => $payload['CustID'],
'SECID' => $payload['SECID'],
'CAMID' => $payload['CAMID'],
'ASSETID' => $payload['ASSETID'],
'fullName' => $payload['fullName'],
'firstName' => $payload['firstName'],
'lastName' => $payload['lastName'],
'emailAddress' => $payload['emailAddress'],
'phoneNumber' => $payload['phoneNumber'],
'accountName' => $verify["data"]['account_name'],
'accountNumber' => $verify["data"]['account_number'],
'customerCode' => $payload['customerCode'],
'bankName' => $payload['bankName'],
'bankCode' => $payload['bankCode'],
'idType' => "bvn",
'idValue' => $payload['BVN'],
'fundCode' => $payload['fundCode'],
'product' => $payload['product'],
'company' => $payload['company'],
'integration' => $payload['integration'],
'currency' => "NGN",
]);
//create transfer recipient code
$code = container('PaystackRequest')->createTransferRecipient($payload);
if($code["status"] == true)
{
//update transfer recipient table with recipient code
$this->transferTable()
->where([
["customerCode", "=", $payload['customerCode']],
["CustID", "=", $payload['CustID']],
])
->update([
"recipientCode" => $code["data"]['recipient_code'],
"accountName" => $code["data"]['details']['account_name'],
"bankName" => $code["data"]['details']['bank_name'],
]);
$payload['recipientCode'] = $code["data"]['recipient_code'];
$payload['accountName'] = $code["data"]['details']['account_name'];
$payload['bankName'] = $code["data"]['details']['bank_name'];
}
}
}
}
//send withrawal request via email to FINCON and RICA
$payload['transactionType'] = "DEBIT";
$payload['transactionAmount'] = $payload['amount'];
$payload['cash_account_id'] = CSWALLET_DEBIT_ACCOUNT;
$payload['productType'] = "BANK";
$payload["client_id"] = $payload["CAMID"];
$payload["narration"] = "Being debit from ". $payload["fullName"]."'s wallet to credit Bank"; //for wallet withdrawal to customer's bank
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"accountNumber" => $payload["accountNumber"],
"bankName" => $payload["bankName"],
"business" => "CAM",
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Wallet Withdrawal Request")
->usingView('wallet_withdrawal_request', $record)
->send();
return ["code"=>200, "message"=>"Your withdrawal request was submitted successfully", "data"=> []];
} */
public function fetchPayoutAuthorizer($payload)
{
$fetchPayoutAuthorizer = $this->redemptionAuthorizerTable()
->where([[strtoupper("class"), "=", strtoupper($payload["class"])]])
->get();
$fetchPayoutAuthorizer = json_decode(json_encode($fetchPayoutAuthorizer), true);
return["code" => 200, "message" => "Payout Authorizers successfully fetched", "data" => $fetchPayoutAuthorizer ?? []];
}
public function fetchPayoutByBatchID($payload)
{
$fetchPayoutByBatchID = $this->redemptionTable()
->where([["batchID", "=", $payload["batchID"]]])
->get();
$fetchPayoutByBatchID = json_decode(json_encode($fetchPayoutByBatchID), true);
$totalAmount = array_sum(array_column($fetchPayoutByBatchID, 'netPayableAmount')) ?? 0;
$class = ($totalAmount * 1 <= CLASS_A * 1) ? "A" : "B";
return["code" => 200, "message" => "Batch successfully fetched", "data" => $fetchPayoutByBatchID ?? [], "totalAmount" => $totalAmount ?? 0, "class" => $class];
}
public function fetchPayoutByRedemptionID($payload)
{
$fetchPayoutByInfowareID = $this->redemptionTable()
->where([["infowareRedemptionID", "=", $payload["redemptionID"]]])
->first();
$fetchPayoutByInfowareID = json_decode(json_encode($fetchPayoutByInfowareID), true);
return["code" => 200, "message" => "Record successfully fetched", "data" => $fetchPayoutByInfowareID ?? []];
}
public function updateRedemptionRecord($payload)
{
$updateRecord = $this->redemptionTable()
->where([["infowareRedemptionID", "=", $payload["redemptionID"]]])
->update([
"ppApproval" => 'approved',
"ppComments" => $payload['comment'],
"isPaid" => 1,
"isPaidDate" => Carbon::now()->format('Y-m-d H:i:s'),
"ppApprovedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
return["code" => 200, "message" => "Record successfully updated", "data" => $updateRecord ?? []];
}
public function getRedemptionPayoutSummary($payload)
{
if(strtoupper($payload['role']) == PM)
{
$all = $this->redemptionTable()->get();
$pending = $this->redemptionTable()
->where([
["ppApproval", "=", "pending"],
["batchID", "=", null],
["netPayableAmount", "!=", null ]
])
->get();
$approved = $this->redemptionTable()
->where([
["ppApproval", "=", "approved"],
["batchID", "!=", null],
["netPayableAmount", "!=", null ]
])
->get();
$paid = $this->redemptionPayoutTable()
->where([
["isPaid", "=", 1],
])->get();
return ["code" => 200,"message" => "Redemption Payout Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "paid" => count($paid) ?? 0];
}elseif(strtoupper($payload['role']) == FINCON)
{
$all = $this->redemptionTable()->get();
$pending = $this->redemptionTable()
->where([
["ppApproval", "=", "approved"],
["fincon", "=", null],
["batchID", "!=", null],
["netPayableAmount", "!=", null ]
])
->get();
$approved = $this->redemptionTable()
->where([
["ppApproval", "=", "approved"],
["fincon", "!=", null],
["batchID", "!=", null],
["netPayableAmount", "!=", null ]
])
->get();
$paid = $this->redemptionPayoutTable()
->where([
["isPaid", "=", 1],
])->get();
return ["code" => 200,"message" => "Redemption Payout Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "paid" => count($paid) ?? 0];
}elseif(strtoupper($payload['role']) == VP)
{
$all = $this->redemptionTable()->get();
$pending = $this->redemptionPayoutTable()
->where([
// ["class", "=", "A"],
["fincon", "!=", null],
["batchID", "!=", null],
["isPaid", "=", 0],
["authorizer_1", "=", $payload['adminEmailAddress']],
["totalAmount", "!=", 0 ]
])
->orWhere([
// ["class", "=", "A"],
["fincon", "!=", null],
["batchID", "!=", null],
["isPaid", "=", 0],
["authorizer_2", "=", $payload['adminEmailAddress']],
["totalAmount", "!=", 0 ]
])
->get();
$approved = $this->redemptionPayoutTable()
->where([
// ["class", "=", "A"],
["authorizer_1_status", "=", "approved"],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
// ["class", "=", "A"],
["authorizer_2_status", "=", "approved"],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->get();
$rejected = $this->redemptionPayoutTable()
->where([
// ["class", "=", "B"],
["authorizer_1_status", "=", "rejected"],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
// ["class", "=", "B"],
["authorizer_2_status", "=", "rejected"],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->get();
$paid = $this->redemptionPayoutTable()
->where([
["isPaid", "=", 1],
])->get();
return ["code" => 200,"message" => "Redemption Payout Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0, "paid" => count($paid) ?? 0];
}elseif(strtoupper($payload['role']) == EXCO)
{
$all = $this->redemptionTable()->get();
$pending = $this->redemptionPayoutTable()
->where([
["class", "=", "B"],
["fincon", "!=", null],
["batchID", "!=", null],
["isPaid", "=", 0],
["authorizer_1", "=", $payload['adminEmailAddress']],
["totalAmount", "!=", 0 ]
])
->orWhere([
["class", "=", "B"],
["fincon", "!=", null],
["batchID", "!=", null],
["isPaid", "=", 0],
["authorizer_2", "=", $payload['adminEmailAddress']],
["totalAmount", "!=", 0 ]
])
->get();
$approved = $this->redemptionPayoutTable()
->where([
["class", "=", "B"],
["authorizer_1_status", "=", "approved"],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
["class", "=", "B"],
["authorizer_2_status", "=", "approved"],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->get();
$rejected = $this->redemptionPayoutTable()
->where([
["class", "=", "B"],
["authorizer_1", "=", $payload['adminEmailAddress']],
["authorizer_1_status", "=", "rejected"],
])
->orWhere([
["class", "=", "B"],
["authorizer_2", "=", $payload['adminEmailAddress']],
["authorizer_2_status", "=", "rejected"],
])
->get();
$paid = $this->redemptionPayoutTable()
->where([
["isPaid", "=", 1],
])->get();
return ["code" => 200,"message" => "Redemption Payout Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0, "paid" => count($paid) ?? 0];
}else{
return ["code" => 400,"message" => "Invalide role provided", "all" => 0, "pending" => 0, "approved" => 0, "paid" => 0];
}
}
public function processRedemptionPayout($payload)
{
if(strtoupper($payload['role']) == PM)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$batchID = Carbon::now()->format('Y-m-d') .$this->randomCode();
foreach ($payload['infowareRedemptionID'] as $infowareRedemptionID)
{
$this->redemptionTable()
->where([
["infowareRedemptionID", "=", $infowareRedemptionID],
["netPayableAmount", "!=", null ],
["ppApproval", "=", "pending" ]
])
->update([
"ppApproval" => "approved",
"batchID" => $batchID,
"ppComments" => "Approved by ". $payload['admin'] ,
"ppApprovedDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}
//send email to fincon
return ["code" => 200,"message" => "Pending Redemption Payout Requests Approved"];
}elseif(strtoupper($payload['action']) == "PENDING")
{
$pending = $this->redemptionTable()
->where([
["ppApproval", "=", "pending"],
["batchID", "=", null],
["netPayableAmount", "!=", null ]
])
->get();
$pending = json_decode(json_encode($pending), true);
return ["code" => 200,"message" => "Pending Redemption Payout Requests Fetched", "data" => $pending] ?? [];
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$fetchAll = $this->redemptionTable()
// ->where([
// ["ppApproval", "=", "pending"],
// ["batchID", "=", null],
// ["netPayableAmount", "!=", null ]
// ])
->get();
$fetchAll = json_decode(json_encode($fetchAll), true);
return ["code" => 200,"message" => "All Redemption Payout Requests Fetched", "data" => $fetchAll] ?? [];
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$approved = $this->redemptionTable()
->where([
["ppApproval", "=", "approved"],
["batchID", "!=", null],
["netPayableAmount", "!=", null ]
])
->get();
$approved = json_decode(json_encode($approved), true);
return ["code" => 200,"message" => "Approved Redemption Payout Requests Fetched", "data" => $approved] ?? [];
}elseif(strtoupper($payload['action']) == "PAID")
{
$paid = $this->redemptionPayoutTable()
->where([
["isPaid", "=", 1],
])->get();
$paid = json_decode(json_encode($paid), true);
return ["code" => 200,"message" => "Paid Redemption Payout Requests Fetched", "data" => $paid] ?? [];
}
}elseif(strtoupper($payload['role']) == FINCON)
{
if(strtoupper($payload['action']) == "APPROVE")
{
//check if batchID exist in redemption payout table
$check = $this->redemptionPayoutTable()
->where([["batchID","=", $payload["batchID"]]])
->get();
if(count($check) > 0) return ["code" => 400, "message" => "Batch already exist in payout table"];
//insert into payout table
$approve = $this->redemptionPayoutTable()
->insertGetId([
"batchID" => $payload["batchID"],
"authorizer_1" => $payload["authorizer_1"],
"authorizer_2" => $payload["authorizer_2"],
"fincon" => $payload['admin'],
// "totalAmount" => number_format($payload['totalAmount'], 2, '.', ','),
"totalAmount" => round($payload['totalAmount'], 2),
"class" => strtoupper($payload['class']),
"debitAccountNumber" => CS_ALPHA_ZENITH_ACCOUNT,
"authorization_score" => 0,
"finconDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
//update redemption table
$this->redemptionTable()
->where([
["batchID", "=", $payload['batchID']],
["netPayableAmount", "!=", null ],
["fincon", "=", null ],
["ppApproval", "=", "approved" ]
])
->update([
"fincon" => "Approved by ". $payload['admin'] ,
"finconDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
//send email to authorizer(s)
return ["code" => 200,"message" => "Pending Redemption Payout Requests Assigned"] ?? [];
}elseif(strtoupper($payload['action']) == "PENDING")
{
$pending = $this->redemptionTable()
->selectRaw('mutualfunds_redemption.batchID, SUM(netPayableAmount) as totalAmount')
->groupBy('batchID')
->where([
["ppApproval", "=", "approved"],
["fincon", "=", null],
["batchID", "!=", null],
["netPayableAmount", "!=", null ]
])
->get();
$pending = json_decode(json_encode($pending), true);
return ["code" => 200,"message" => "Pending Redemption Payout Requests Fetched", "data" => $pending ?? []];
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$fetchAll = $this->redemptionTable()
// ->where([
// ["ppApproval", "=", "pending"],
// ["batchID", "=", null],
// ["netPayableAmount", "!=", null ]
// ])
->get();
return ["code" => 200,"message" => "All Redemption Payout Requests Fetched", "data" => $fetchAll] ?? [];
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$approved = $this->redemptionTable()
->where([
["ppApproval", "=", "approved"],
["fincon", "!=", null],
["batchID", "!=", null],
["netPayableAmount", "!=", null ]
])
->get();
$approved = json_decode(json_encode($approved), true);
return ["code" => 200,"message" => "Approved Redemption Payout Requests Fetched", "data" => $approved] ?? [];
}elseif(strtoupper($payload['action']) == "PAID")
{
$paid = $this->redemptionPayoutTable()
->where([
["isPaid", "=", 1],
])->get();
$paid = json_decode(json_encode($paid), true);
return ["code" => 200,"message" => "Paid Redemption Payout Requests Fetched", "data" => $paid] ?? [];
}
}elseif(strtoupper($payload['role']) == VP)
{
if(strtoupper($payload['action']) == "APPROVE")
{
//check if admin has already approved
$check = $this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
["authorizer_1_status", "!=", null],
["authorizer_1_comment", "!=", null],
["fincon", "!=", null],
// ["class", "=", "A"],
])
->orWhere([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
["authorizer_2_status", "!=", null],
["authorizer_2_comment", "!=", null],
["fincon", "!=", null],
// ["class", "=", "A"],
])
->get();
if(count($check) > 0)
{
return ["code" => 400,"message" => "You already treated this batch"];
}
$this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
["fincon", "!=", null],
["isPaid", "=", 0],
])
->update([
"authorizer_1_status" => "approved",
"authorizer_1_comment" => $payload['comment'],
"authorizer_1_otp" => $payload['otp'],
"authorization_score" => $payload['authorization_score'] + 1,
"authorizer_1_date" => Carbon::now()->format('Y-m-d H:i:s'),
]);
$this->redemptionPayoutTable()
->Where([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
["fincon", "!=", null],
["isPaid", "=", 0],
])
->update([
"authorizer_2_status" => "approved",
"authorizer_2_comment" => $payload['comment'],
"authorizer_2_otp" => $payload['otp'],
"authorization_score" => $payload['authorization_score'] + 1,
"authorizer_2_date" => Carbon::now()->format('Y-m-d H:i:s'),
]);
//check if authorization_score is 1
if($payload['authorization_score'] == 1)
{
//send to zenith for payment
$pay = $this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->update([
"isPaid" => 1,
"isPaidDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
//send email to fincon and PM
}
return ["code" => 200,"message" => "Pending Redemption Payout Request Approved for Payment by Custodian"];
}elseif(strtoupper($payload['action']) == "REJECT")
{
//check if admin has already approved
$check = $this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
["authorizer_1_status", "!=", null],
["authorizer_1_comment", "!=", null],
["fincon", "!=", null],
// ["class", "=", "A"],
])
->orWhere([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
["authorizer_2_status", "!=", null],
["authorizer_2_comment", "!=", null],
["fincon", "!=", null],
// ["class", "=", "A"],
])
->get();
if(count($check) > 0)
{
return ["code" => 400,"message" => "You already treated this batch"];
}
$this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
["fincon", "!=", null],
["isPaid", "=", 0],
])
->update([
"authorizer_1_status" => "rejected",
"authorizer_1_comment" => $payload['comment'],
"authorizer_1_otp" => $payload['otp'],
"authorization_score" => 3,
"authorizer_1_date" => Carbon::now()->format('Y-m-d H:i:s'),
]);
$this->redemptionPayoutTable()
->Where([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
["fincon", "!=", null],
["isPaid", "=", 0],
])
->update([
"authorizer_2_status" => "rejected",
"authorizer_2_comment" => $payload['comment'],
"authorizer_2_otp" => $payload['otp'],
"authorization_score" => 3,
"authorizer_2_date" => Carbon::now()->format('Y-m-d H:i:s'),
]);
return ["code" => 200,"message" => "Pending Redemption Payout Request Approved Rejected"];
}elseif(strtoupper($payload['action']) == "PENDING")
{
$pending = $this->redemptionPayoutTable()
->select('batchID','totalAmount')
->where([
["authorizer_1", "=", $payload["adminEmailAddress"]],
["fincon", "!=", null],
["batchID", "!=", null],
["totalAmount", "!=", null],
["isPaid", "=", 0],
// ["class", "=", "A"],
])
->orWhere([
["authorizer_2", "=", $payload["adminEmailAddress"]],
["fincon", "!=", null],
["batchID", "!=", null],
["totalAmount", "!=", null],
["isPaid", "=", 0],
// ["class", "=", "A"],
])
->get();
$pending = json_decode(json_encode($pending), true);
return ["code" => 200,"message" => "Pending Redemption Payout Requests Fetched", "data" => $pending ?? []];
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$fetchAll = $this->redemptionPayoutTable()
->get();
return ["code" => 200,"message" => "All Redemption Payout Requests Fetched", "data" => $fetchAll] ?? [];
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$approved = $this->redemptionPayoutTable()
->where([
// ["class", "=", "A"],
["authorizer_1_status", "=", "approved"],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
// ["class", "=", "A"],
["authorizer_2_status", "=", "approved"],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->get();
$approved = json_decode(json_encode($approved), true);
return ["code" => 200,"message" => "Approved Redemption Payout Requests Fetched", "data" => $approved] ?? [];
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$rejected = $this->redemptionPayoutTable()
->where([
// ["class", "=", "A"],
["authorizer_1_status", "=", "rejected"],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
// ["class", "=", "A"],
["authorizer_2_status", "=", "rejected"],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->get();
$rejected = json_decode(json_encode($rejected), true);
return ["code" => 200,"message" => "Rejected Redemption Payout Requests Fetched", "data" => $rejected] ?? [];
}elseif(strtoupper($payload['action']) == "PAID")
{
$paid = $this->redemptionPayoutTable()
->where([
["isPaid", "=", 1],
])->get();
$paid = json_decode(json_encode($paid), true);
return ["code" => 200,"message" => "Paid Redemption Payout Requests Fetched", "data" => $paid] ?? [];
}
}elseif(strtoupper($payload['role']) == EXCO)
{
if(strtoupper($payload['action']) == "APPROVE")
{
//check if admin has already approved
$check = $this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
["authorizer_1_status", "!=", null],
["authorizer_1_comment", "!=", null],
["fincon", "!=", null],
["class", "=", "B"],
])
->orWhere([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
["authorizer_2_status", "!=", null],
["authorizer_2_comment", "!=", null],
["fincon", "!=", null],
["class", "=", "B"],
])
->get();
if(count($check) > 0)
{
return ["code" => 400,"message" => "You already treated this batch"];
}
$this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
["fincon", "!=", null],
["isPaid", "=", 0],
["class", "=", "B"],
])
->update([
"authorizer_1_status" => "approved",
"authorizer_1_comment" => $payload['comment'],
"authorizer_1_otp" => $payload['otp'],
"authorization_score" => $payload['authorization_score'] + 1,
"authorizer_1_date" => Carbon::now()->format('Y-m-d H:i:s'),
]);
$this->redemptionPayoutTable()
->Where([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
["fincon", "!=", null],
["isPaid", "=", 0],
["class", "=", "B"],
])
->update([
"authorizer_2_status" => "approved",
"authorizer_2_comment" => $payload['comment'],
"authorizer_2_otp" => $payload['otp'],
"authorization_score" => $payload['authorization_score'] + 1,
"authorizer_2_date" => Carbon::now()->format('Y-m-d H:i:s'),
]);
//check if authorization_score is 1
if($payload['authorization_score'] == 1)
{
//send to zenith for payment
$pay = $this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->update([
"isPaid" => 1,
"isPaidDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
//send email to fincon and PM
}
return ["code" => 200,"message" => "Pending Redemption Payout Request Approved for Payment by Custodian"];
}elseif(strtoupper($payload['action']) == "REJECT")
{
//check if admin has already approved
$check = $this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
["authorizer_1_status", "!=", null],
["authorizer_1_comment", "!=", null],
["fincon", "!=", null],
["class", "=", "B"],
])
->orWhere([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
["authorizer_2_status", "!=", null],
["authorizer_2_comment", "!=", null],
["fincon", "!=", null],
["class", "=", "B"],
])
->get();
if(count($check) > 0)
{
return ["code" => 400,"message" => "You already treated this batch"];
}
$this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
["authorizer_1", "=", $payload['adminEmailAddress']],
["fincon", "!=", null],
["isPaid", "=", 0],
["class", "=", "B"],
])
->update([
"authorizer_1_status" => "rejected",
"authorizer_1_comment" => $payload['comment'],
"authorizer_1_otp" => $payload['otp'],
"authorization_score" => 4,
"authorizer_1_date" => Carbon::now()->format('Y-m-d H:i:s'),
]);
$this->redemptionPayoutTable()
->Where([
["batchID", "=", $payload['batchID']],
["authorizer_2", "=", $payload['adminEmailAddress']],
["fincon", "!=", null],
["isPaid", "=", 0],
["class", "=", "B"],
])
->update([
"authorizer_2_status" => "rejected",
"authorizer_2_comment" => $payload['comment'],
"authorizer_2_otp" => $payload['otp'],
"authorization_score" => 4,
"authorizer_2_date" => Carbon::now()->format('Y-m-d H:i:s'),
]);
return ["code" => 200,"message" => "Pending Redemption Payout Request Approved Rejected"];
}elseif(strtoupper($payload['action']) == "PENDING")
{
$pending = $this->redemptionPayoutTable()
->select('batchID','totalAmount')
->where([
["authorizer_1", "=", $payload["adminEmailAddress"]],
["fincon", "!=", null],
["batchID", "!=", null],
["totalAmount", "!=", null],
["isPaid", "=", 0],
["class", "=", "B"],
])
->orWhere([
["authorizer_2", "=", $payload["adminEmailAddress"]],
["fincon", "!=", null],
["batchID", "!=", null],
["totalAmount", "!=", null],
["isPaid", "=", 0],
["class", "=", "B"],
])
->get();
$pending = json_decode(json_encode($pending), true);
return ["code" => 200,"message" => "Pending Redemption Payout Requests Fetched", "data" => $pending ?? []];
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$fetchAll = $this->redemptionPayoutTable()
->get();
return ["code" => 200,"message" => "All Redemption Payout Requests Fetched", "data" => $fetchAll] ?? [];
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$approved = $this->redemptionPayoutTable()
->where([
["class", "=", "B"],
["authorizer_1_status", "=", "approved"],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
["class", "=", "B"],
["authorizer_2_status", "=", "approved"],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->get();
$approved = json_decode(json_encode($approved), true);
return ["code" => 200,"message" => "Approved Redemption Payout Requests Fetched", "data" => $approved] ?? [];
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$rejected = $this->redemptionPayoutTable()
->where([
["class", "=", "B"],
["authorizer_1_status", "=", "rejected"],
["authorizer_1", "=", $payload['adminEmailAddress']],
])
->orWhere([
["class", "=", "B"],
["authorizer_2_status", "=", "rejected"],
["authorizer_2", "=", $payload['adminEmailAddress']],
])
->get();
$rejected = json_decode(json_encode($rejected), true);
return ["code" => 200,"message" => "Rejected Redemption Payout Requests Fetched", "data" => $rejected] ?? [];
}elseif(strtoupper($payload['action']) == "PAID")
{
$paid = $this->redemptionPayoutTable()
->where([
["isPaid", "=", 1],
])->get();
$paid = json_decode(json_encode($paid), true);
return ["code" => 200,"message" => "Paid Redemption Payout Requests Fetched", "data" => $paid] ?? [];
}
}
}
public function processWithdrawRequests($payload)
{
//filter action
if(strtoupper($payload['role']) == IA)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump($roleLimit );
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "pending"],
["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
])
->update([
"ia_status" => "approved",
"ia" => $payload['admin'],
"ia_comment" => $payload['comment'],
"iaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "pending"],
["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
])
->update([
"ia_status" => "rejected",
"authorizer_status" => "canceled",
// "pm_status" => "canceled",
"rica_status" => "canceled",
"fincon_status" => "canceled",
"ia" => $payload['admin'],
"ia_comment" => $payload['comment'],
"iaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
])
->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$withdraw = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "pending"],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Pending Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$withdraw = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "approved"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Approved Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$withdraw = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "rejected"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Rejected Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$withdraw = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "All Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == IALEAD)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump($roleLimit );
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "pending"],
])
->update([
"ia_status" => "approved",
"ia" => $payload['admin'],
"ia_comment" => $payload['comment'],
"iaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "pending"],
])
->update([
"ia_status" => "rejected",
"authorizer_status" => "canceled",
// "pm_status" => "canceled",
"rica_status" => "canceled",
"fincon_status" => "canceled",
"ia" => $payload['admin'],
"ia_comment" => $payload['comment'],
"iaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
])
->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$withdraw = $this->withdrawRequestTable()
->where([
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "pending"],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Pending Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "approved"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Approved Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
["ia_status", "=", "rejected"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Rejected Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$withdraw = $this->withdrawRequestTable()
->where([
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "All Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == PM)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump(PM_APPROVE*1);
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", ">", IA_APPROVE*1],
["pm_status", "=", "pending"],
])
->update([
"pm_status" => "approved",
"pm" => $payload['admin'],
"pm_comment" => $payload['comment'],
"pmDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", ">", IA_APPROVE*1],
["pm_status", "=", "pending"],
])
->update([
"pm_status" => "rejected",
"authorizer_status" => "canceled",
"rica_status" => "canceled",
// "ia_status" => "canceled",
"fincon_status" => "canceled",
"pm" => $payload['admin'],
"pm_comment" => $payload['comment'],
"pmDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
])
->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$withdraw = $this->withdrawRequestTable()
->where([
["amount", ">", IA_APPROVE*1],
["pm_status", "=", "pending"],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Pending Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["amount", ">", IA_APPROVE*1],
["pm_status", "=", "approved"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Approved Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["amount", ">", IA_APPROVE*1],
["pm_status", "=", "rejected"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Rejected Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$withdraw = $this->withdrawRequestTable()
->where([["amount", ">", IA_APPROVE*1],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == RICA)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["ia_status", "=", "approved"],
["rica_status", "=", "pending"],
// ["authorizer", "!=", null],
])
->orWhere([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
// ["authorizer", "!=", null],
])
->update([
"rica_status" => "approved",
"rica" => $payload['admin'],
"rica_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["ia_status", "=", "approved"],
["rica_status", "=", "pending"],
// ["authorizer", "!=", null],
])
->orWhere([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
// ["authorizer", "!=", null],
])
->update([
"rica_status" => "rejected",
"fincon_status" => "canceled",
"rica" => $payload['admin'],
"rica_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
])
->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ia_status", "=", "approved"],
["rica_status", "=", "pending"],
// ["authorizer", "!=", null],
])
->orWhere([
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
// ["authorizer", "!=", null],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Pending Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["rica_status", "=", "approved"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Approved Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["rica_status", "=", "rejected"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Rejected Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$withdraw = $this->withdrawRequestTable()->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == FINCON)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
// ["initiator", "!=", null],
])
->update([
"fincon_status" => "approved",
"status" => "approved",
"fincon" => $payload['admin'],
"fincon_comment" => $payload['comment'],
"finconDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
// ["initiator", "!=", null],
])
->update([
"fincon_status" => "rejected",
"status" => "rejected",
// "rica_status" => "canceled",
"fincon" => $payload['admin'],
"fincon_comment" => $payload['comment'],
"finconDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
])
->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$withdraw = $this->withdrawRequestTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Pending Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["fincon_status", "=", "approved"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Approved Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["fincon_status", "=", "rejected"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Rejected Withdrawal Application Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$withdraw = $this->withdrawRequestTable()->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == AUTOPAY)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["fincon_status", "=", "approved"],
["autopay_status", "=", "pending"],
])
->update([
"autopay_status" => "approved",
"autopay" => $payload['admin'],
"autopay_comment" => $payload['comment'],
'ipaddress' => $this->get_client_ip(),
"autopayDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Autopay Process Completed"] ?? [];
}else{
return ["code" => 400,"message" => "Autopay Process Failed or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["fincon_status", "=", "approved"],
["autopay_status", "=", "pending"],
])
->update([
"autopay_status" => "rejected",
"autopay" => $payload['admin'],
"autopay_comment" => $payload['comment'],
"autopayDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Autopay Process Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Autopay Process Failed or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
])
->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Autopay Process Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Autopay Process Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$withdraw = $this->withdrawRequestTable()
->where([
["autopay_status", "=", "pending"],
["fincon_status", "=", "approved"],
])
->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Autopay Process Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["autopay_status", "=", "approved"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Approved Autopay Process Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$withdraw = $this->withdrawRequestTable()
->where([
["autopay_status", "=", "rejected"],
])->get();
/* if(count($withdraw) > 0)
{ */
return ["code" => 200,"message" => "Rejected Autopay Process Requests Fetched", "data" => $withdraw, "total" => count($withdraw) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Application Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$withdraw = $this->withdrawRequestTable()->get();
/* if($withdraw > 0)
{ */
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
/* }else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
} */
}
}
}
public function processInvestmentRequests($payload)
{
//filter action
if(strtoupper($payload['role']) == PM)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump($roleLimit );
if(strtoupper($payload['action']) == "APPROVE")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
// ["product", "=", $payload['product']],
["pm_status", "=", "pending"],
])
->update([
"pm_status" => "approved",
"pm" => $payload['admin'],
"pm_comment" => $payload['comment'],
"pmDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Booking Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
// ["product", "=", $payload['product']],
["pm_status", "=", "pending"],
])
->update([
"pm_status" => "rejected",
"fincon_status" => "rejected",
"rica_status" => "rejected",
"pm" => $payload['admin'],
"pm_comment" => $payload['comment'],
"pmDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Booking Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
])->get();
/* if(count($invest) > 0)
{*/
return ["code" => 200,"message" => "Investment Booking Request Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "PENDING")
{
$invest = $this->CAMDealTable()
->where([
["pm_status", "=", "pending"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Pending Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$invest = $this->CAMDealTable()
->where([
["pm_status", "=", "approved"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Approved Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$invest = $this->CAMDealTable()
->where([
["pm_status", "=", "rejected"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Rejected Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$invest = $this->CAMDealTable()->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "All Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == FINCON)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump(PM_APPROVE*1);
if(strtoupper($payload['action']) == "APPROVE")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])
->first();
if(count($invest) > 0)
{
$payload += json_decode(json_encode($invest),true);
//execute booking
if(strtoupper($payload['productType']) == BONDS || strtoupper($payload['productType']) == BOND)
{
$book = formatIWRes(container('IWSRequest')->bookBondsInvestment($payload));
}elseif(strtoupper($payload['productType']) == TBILLS)
{
$book = formatIWRes(container('IWSRequest')->bookTbillsInvestment($payload));
}elseif(strtoupper($payload['productType']) == CP)
{
$payload['interestRate'] = $payload['rate'];
$book = formatIWRes(container('IWSRequest')->bookCAMInvestment($payload));
}
if($book["StatusID"] == 0)
{
$this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])
->update([
"fincon_status" => "approved",
"fincon" => $payload['admin'],
"fincon_comment" => $payload['comment'],
"finconDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
return ["code" => 200, "message" => "Investment Booking Request Approved and Investment Booked"] ?? [];
}else{
return ["code" => 400, "message" => "Investment Booking Request Approval Failed"] ?? [];
}
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])
->update([
"fincon_status" => "rejected",
"fincon" => $payload['admin'],
"fincon_comment" => $payload['comment'],
"finconDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Booking Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
])->get();
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Booking Request Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$invest = $this->CAMDealTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Pending Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$invest = $this->CAMDealTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "approved"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Approved Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$invest = $this->CAMDealTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "rejected"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Rejected Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$invest = $this->CAMDealTable()->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "All Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == RICA)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump(PM_APPROVE*1);
if(strtoupper($payload['action']) == "APPROVE")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->update([
"rica_status" => "approved",
"rica" => $payload['admin'],
"rica_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Booking Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->update([
"rica_status" => "rejected",
"fincon_status" => "rejected",
"rica" => $payload['admin'],
"rica_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Booking Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$invest = $this->CAMDealTable()
->where([
["ID", "=", $payload['ID']],
])->get();
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Booking Request Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
}else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$invest = $this->CAMDealTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Pending Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$invest = $this->CAMDealTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "approved"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Approved Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$invest = $this->CAMDealTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "rejected"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Rejected Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$invest = $this->CAMDealTable()->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "All Investment Booking Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Booking Request Not Found"] ?? [];
} */
}
}
}
public function processInvestmentLiquidation($payload)
{
//filter action
if(strtoupper($payload['role']) == PM)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump($roleLimit );
if(strtoupper($payload['action']) == "APPROVE")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["chgAmount", "=", $payload['chgAmount']],
// ["product", "=", $payload['product']],
["pm_status", "=", "pending"],
])
->update([
"pm_status" => "approved",
"pm" => $payload['admin'],
"pm_comment" => $payload['comment'],
"pmDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Liquidation Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["chgAmount", "=", $payload['chgAmount']],
// ["product", "=", $payload['product']],
["pm_status", "=", "pending"],
])
->update([
"pm_status" => "rejected",
"fincon_status" => "rejected",
"rica_status" => "rejected",
"pm" => $payload['admin'],
"pm_comment" => $payload['comment'],
"pmDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Liquidation Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
])->get();
/* if(count($invest) > 0)
{*/
return ["code" => 200,"message" => "Investment Liquidation Request Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "PENDING")
{
$invest = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "pending"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Pending Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$invest = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "approved"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Approved Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$invest = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "rejected"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Rejected Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$invest = $this->CAMDealBreakTable()->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "All Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == FINCON)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump(PM_APPROVE*1);
if(strtoupper($payload['action']) == "APPROVE")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["chgAmount", "=", $payload['chgAmount']],
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])
->first();
if(count($invest) > 0)
{
$payload += json_decode(json_encode($invest),true);
//execute booking
if(strtoupper($payload['productType']) == BONDS || strtoupper($payload['productType']) == BOND)
{
// $book = formatIWRes(container('IWSRequest')->bookBondsInvestment($payload));
}elseif(strtoupper($payload['productType']) == TBILLS)
{
// $book = formatIWRes(container('IWSRequest')->breakTBILLSInvestment($payload));
}elseif(strtoupper($payload['productType']) == "CAM-FI")
{
$payload['interestRate'] = $payload['rate'];
$book = formatIWRes(container('IWSRequest')->breakCAMInvestment($payload));
}elseif(strtoupper($payload['productType']) == "CAM-EIN")
{
$payload['interestRate'] = $payload['rate'];
$book = formatIWRes(container('IWSRequest')->breakCAMInvestment($payload));
}elseif(strtoupper($payload['productType']) == CP)
{
$payload['interestRate'] = $payload['rate'];
$book = formatIWRes(container('IWSRequest')->breakCAMInvestment($payload));
}
if($book["StatusID"] == 0)
{
$this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["chgAmount", "=", $payload['chgAmount']],
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])
->update([
"fincon_status" => "approved",
"fincon" => $payload['admin'],
"fincon_comment" => $payload['comment'],
"finconDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
return ["code" => 200, "message" => "Investment Liquidation Request Approved and Investment Booked"] ?? [];
}
}else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["chgAmount", "=", $payload['chgAmount']],
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])
->update([
"fincon_status" => "rejected",
"fincon" => $payload['admin'],
"fincon_comment" => $payload['comment'],
"finconDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Liquidation Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
])->get();
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Liquidation Request Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
}else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$invest = $this->CAMDealBreakTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Pending Liquidation Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$invest = $this->CAMDealBreakTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "approved"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Approved Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$invest = $this->CAMDealBreakTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "rejected"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Rejected Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$invest = $this->CAMDealBreakTable()->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "All Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}
}elseif(strtoupper($payload['role']) == RICA)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump(PM_APPROVE*1);
if(strtoupper($payload['action']) == "APPROVE")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["chgAmount", "=", $payload['chgAmount']],
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->update([
"rica_status" => "approved",
"rica" => $payload['admin'],
"rica_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Liquidation Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["chgAmount", "=", $payload['chgAmount']],
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->update([
"rica_status" => "rejected",
"fincon_status" => "rejected",
"rica" => $payload['admin'],
"rica_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Liquidation Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$invest = $this->CAMDealBreakTable()
->where([
["ID", "=", $payload['ID']],
])->get();
if(count($invest) > 0)
{
return ["code" => 200,"message" => "Investment Liquidation Request Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
}else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
$invest = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Pending Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "APPROVED")
{
$invest = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "approved"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Approved Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "REJECTED")
{
$invest = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "rejected"],
])->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "Rejected Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
$invest = $this->CAMDealBreakTable()->get();
/* if(count($invest) > 0)
{ */
return ["code" => 200,"message" => "All Investment Liquidation Requests Fetched", "data" => $invest, "total" => count($invest) ?? 0] ?? [];
/* }else{
return ["code" => 400,"message" => "Investment Liquidation Request Not Found"] ?? [];
} */
}
}
}
public function processMarginRequests($payload)
{
//filter action
if(strtoupper($payload['role']) == CSS)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["css_status", "=", "pending"],
])
->update([
"css_status" => "approved",
"css" => $payload['admin'],
"css_comment" => $payload['comment'],
"cssDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["css_status", "=", "pending"],
])
->update([
"css_status" => "rejected",
"amo_status" => "canceled",
"rica_status" => "canceled",
"partner_status" => "canceled",
"css" => $payload['admin'],
"css_comment" => $payload['comment'],
"amo_comment" => $payload['comment'],
"rica_comment" => $payload['comment'],
"partner_comment" => $payload['comment'],
"cssDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["margin_application.ID", "=", $payload['ID']],
])
->get();
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Requests Fetched", "data" => $margin] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found"] ?? [];
} */
$margin = $this->marginApplicationTable()->where([["ID","=",$payload['ID']]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
return ["code" => 200, 'message' => 'Margin Application Details Successfully fetched.' , 'data' => $margin] ?? [];
}else{
return ["code" => 400, 'message' => 'No Margin Application Found.', 'data' => $margin] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["css_status", "=", "pending"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["css_status", "=", "pending"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Pending Margin Application Requests Fetched", "data" => $margin] ?? [];
}elseif(strtoupper($payload['action']) == "APPROVED")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["css_status", "=", "approved"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["css_status", "=", "approved"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Approved Margin Application Requests Fetched", "data" => $margin, "total" => count($margin) ?? 0] ?? [];
}elseif(strtoupper($payload['action']) == "REJECTED")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["css_status", "=", "rejected"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["css_status", "=", "rejected"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Rejected Margin Application Requests Fetched", "data" => $margin, "total" => count($margin) ?? 0] ?? [];
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->get(); */
$margin = $this->marginApplicationTable()->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Margin Application Requests Fetched", "data" => $margin] ?? [];
}
}elseif(strtoupper($payload['role']) == RICA)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["css_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->update([
"rica_status" => "approved",
"rica" => $payload['admin'],
"rica_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["css_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->update([
"rica_status" => "rejected",
"amo_status" => "canceled",
"css_status" => "canceled",
"partner_status" => "canceled",
"rica" => $payload['admin'],
"css_comment" => $payload['comment'],
"amo_comment" => $payload['comment'],
"rica_comment" => $payload['comment'],
"partner_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["margin_application.ID", "=", $payload['ID']],
])
->get();
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Requests Fetched", "data" => $margin] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found"] ?? [];
} */
$margin = $this->marginApplicationTable()->where([["ID","=",$payload['ID']]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
return ["code" => 200, 'message' => 'Margin Application Details Successfully fetched.' , 'data' => $margin] ?? [];
}else{
return ["code" => 400, 'message' => 'No Margin Application Found.', 'data' => $margin] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["css_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([
["css_status", "=", "approved"],
["rica_status", "=", "pending"],
])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Pending Margin Application Requests Fetched", "data" => $margin] ?? [];
}elseif(strtoupper($payload['action']) == "APPROVED")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["rica_status", "=", "approved"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["rica_status", "=", "approved"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Approved Margin Application Requests Fetched", "data" => $margin, "total" => count($margin) ?? 0] ?? [];
}elseif(strtoupper($payload['action']) == "REJECTED")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["rica_status", "=", "rejected"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["rica_status", "=", "rejected"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Rejected Margin Application Requests Fetched", "data" => $margin, "total" => count($margin) ?? 0] ?? [];
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->get(); */
$margin = $this->marginApplicationTable()->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Margin Application Requests Fetched", "data" => $margin] ?? [];
}
}elseif(strtoupper($payload['role']) == PARTNER)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["rica_status", "=", "approved"],
["partner_status", "=", "pending"],
])
->update([
"partner_status" => "approved",
"partner" => $payload['admin'],
"partner_comment" => $payload['comment'],
"partnerDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["rica_status", "=", "approved"],
["partner_status", "=", "pending"],
])
->update([
"partner_status" => "rejected",
"amo_status" => "canceled",
"rica_status" => "canceled",
"css_status" => "canceled",
"partner" => $payload['admin'],
"css_comment" => $payload['comment'],
"amo_comment" => $payload['comment'],
"rica_comment" => $payload['comment'],
"partner_comment" => $payload['comment'],
"partnerDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["margin_application.ID", "=", $payload['ID']],
])
->get();
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Requests Fetched", "data" => $margin] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found"] ?? [];
} */
$margin = $this->marginApplicationTable()->where([["ID","=",$payload['ID']]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
return ["code" => 200, 'message' => 'Margin Application Details Successfully fetched.' , 'data' => $margin] ?? [];
}else{
return ["code" => 400, 'message' => 'No Margin Application Found.', 'data' => $margin] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["rica_status", "=", "approved"],
["partner_status", "=", "pending"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["rica_status", "=", "approved"],
["partner_status", "=", "pending"],
])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Pending Margin Application Requests Fetched", "data" => $margin] ?? [];
}elseif(strtoupper($payload['action']) == "APPROVED")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["partner_status", "=", "approved"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["partner_status", "=", "approved"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Approved Margin Application Requests Fetched", "data" => $margin, "total" => count($margin) ?? 0] ?? [];
}elseif(strtoupper($payload['action']) == "REJECTED")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["partner_status", "=", "rejected"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["partner_status", "=", "rejected"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Rejected Margin Application Requests Fetched", "data" => $margin, "total" => count($margin) ?? 0] ?? [];
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->get(); */
$margin = $this->marginApplicationTable()->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Margin Application Requests Fetched", "data" => $margin] ?? [];
}
}elseif(strtoupper($payload['role']) == AMO)
{
/* if(strtoupper($payload['action']) == "APPROVE")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["partner_status", "=", "approved"],
["amo_status", "=", "pending"],
])
->update([
"amo_status" => "approved",
"amo" => $payload['admin'],
"amo_comment" => $payload['comment'],
"amoDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
//check if margin records exist
$check = $this->marginClientTable()
->where([['CustID' ,"=", $payload['CustID']],
['SECID' ,"=", $payload['SECID']],
['loanType' ,"=", $payload['loanType']],
])
->get();
if(count($check) > 0)
{
$margin = $this->marginClientTable()
->where([['CustID' ,"=", $payload['CustID']],
['SECID' ,"=", $payload['SECID']],
['loanType' ,"=", $payload['loanType']],
])
->update([
"loanAmount" => $payload['loanAmount'],
"rate" => $payload['rate'],
]);
return ["code" => 200,"message" => "Margin Loan Facility Updated"];
}else{
//create margin involvement for client and set margin limit
$payload['businessInvolvement'] = STOCKBROKING_DB_NAME;
$payload['involvementType'] = MARGIN_INVOLVEMENT;
$payload['BIZID'] = $payload['SECID'];
$result = formatIWRes(container('IWSRequest')->createInvolvement($payload));
// $resultDecoded = json_decode(json_encode($result));
//var_dump("status id is ".$result["StatusID"]);
if($result["StatusID"] == 0)
{
$margin_ = $this->marginClientTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'SECID' => $payload['SECID'],
'fullName' => $payload['fullName'],
'emailAddress' => $payload['emailAddress'],
'marginID' => (strtoupper($payload['loanType']) == "STAFF") ? "MAS-".$payload['CustID'] : "MAC-".$payload['CustID'],
'rate' => $payload['rate'],
'loanAmount' => $payload['loanAmount'],
'loanType' => $payload['loanType'],
]);
if($margin_ > 0)
{
return ["code" => 200, "message" => "Margin Application Approved and Processed"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Approved, but Not Processed. Please Contact IT"] ?? [];
}
}
}
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
} */
if(strtoupper($payload['action']) == "APPROVE")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["partner_status", "=", "approved"],
["amo_status", "=", "pending"],
])
->update([
"amo_status" => "approved",
"amo" => $payload['admin'],
"amo_comment" => $payload['comment'],
"amoDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
//insert or update margin client
//check if margin client records exist
$check = $this->marginClientTable()
->where([['CustID' ,"=", $payload['CustID']],
['SECID' ,"=", $payload['SECID']],
['loanType' ,"=", $payload['loanType']],
])
->get();
$check = json_decode(json_encode($check),true);
if(count($check) > 0)
{
$margin = $this->marginClientTable()
->where([['CustID' ,"=", $payload['CustID']],
['SECID' ,"=", $payload['SECID']],
['loanType' ,"=", $payload['loanType']],
])
->update([
"loanAmount" => $check[0]['loanAmount']*1 + $payload['loanAmount']*1 ,
"rate" => $payload['rate'],
]);
//add margin client to SPA list
$this->addSPAClient($payload);
$message = "Margin Loan Facility Updated";
}else{
//create margin involvement for client and set margin limit
$payload['businessInvolvement'] = STOCKBROKING_DB_NAME;
$payload['involvementType'] = MARGIN_INVOLVEMENT;
$payload['BIZID'] = $payload['SECID'];
$result = formatIWRes(container('IWSRequest')->createInvolvement($payload));
// $resultDecoded = json_decode(json_encode($result));
//var_dump("status id is ".$result["StatusID"]);
if($result["StatusID"] == 0)
{
$margin_ = $this->marginClientTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'SECID' => $payload['SECID'],
'fullName' => $payload['fullName'],
'admin' => $payload['admin'],
'emailAddress' => $payload['emailAddress'],
'marginID' => (strtoupper($payload['loanType']) == "STAFF") ? "MAS-".$payload['CustID'] : "MAC-".$payload['CustID'],
'rate' => $payload['rate'],
'loanAmount' => $payload['loanAmount'],
'loanType' => $payload['loanType'],
]);
if($margin_ > 0)
{
//add margin client to SPA list
$this->addSPAClient($payload);
$message = "Margin Application Approved and Processed";
}else{
$message = "Margin Application Approved, but Not Processed. Please Contact IT";
}
}
}
//insert or update margin lien
$margin = $this->marginApplicationTable()->where([["ID","=",$payload['ID']]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
// var_dump($margin[0]['collateral']);
foreach($margin[0]['collateral'] as $col)
{
//check if margin client records exist
$check = $this->marginLienTable()
->where([['CustID' ,"=", $col->CustID],
['cashAccount' ,"=", $col->cashAccount],
['cashAccount' ,"=", $col->instrumentType],
['loanType' => $margin[0]['loanType']],
])
->get();
$check = json_decode(json_encode($check),true);
// var_dump($col);
if(count($check) > 0)
{
//append collaterals
$update = $this->marginLienTable()
->where([['CustID' ,"=", $col->CustID],
['cashAccount' ,"=", $col->cashAccount],
['instrumentType' ,"=", $col->instrumentType],
['loanType' => $margin[0]['loanType']],
])
->update([
"lienValue" => $check[0]['lienValue']*1 + $col->lienValue*1,
]);
$message_ = "Margin Lien Updated";
}else{
$insert = $this->marginLienTable()
->insertGetId([
'CustID' => $col->CustID,
'fullName' => $payload['fullName'],
'collateral' => $col->collateral,
'instrumentType' => $col->instrumentType,
'cashAccount' => $col->cashAccount,
'lienValue' => $col->collateralValue,
'loanType' => $margin[0]['loanType'],
]);
if($insert > 0)
{
$message_ = "Margin Lien Processed" ;
}else{
$message_ = "Margin Lien Process Failed. Please Contact IT";
}
}
}
return ["code" => 200,"message" => $message ." and " . $message_];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$margin = $this->marginApplicationTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["loanAmount", "=", $payload['loanAmount']],
["loanType", "=", $payload['loanType']],
["partner_status", "=", "approved"],
["amo_status", "=", "pending"],
])
->update([
"amo_status" => "rejected",
"css_status" => "canceled",
"rica_status" => "canceled",
"partner_status" => "canceled",
"amo" => $payload['admin'],
"css_comment" => $payload['comment'],
"amo_comment" => $payload['comment'],
"rica_comment" => $payload['comment'],
"partner_comment" => $payload['comment'],
"amoDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["margin_application.ID", "=", $payload['ID']],
])
->get();
if($margin > 0)
{
return ["code" => 200,"message" => "Margin Application Requests Fetched", "data" => $margin] ?? [];
}else{
return ["code" => 400,"message" => "Margin Application Request Not Found"] ?? [];
} */
$margin = $this->marginApplicationTable()->where([["ID","=",$payload['ID']]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
return ["code" => 200, 'message' => 'Margin Application Details Successfully fetched.' , 'data' => $margin] ?? [];
}else{
return ["code" => 400, 'message' => 'No Margin Application Found.', 'data' => $margin] ?? [];
}
}elseif(strtoupper($payload['action']) == "PENDING")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["partner_status", "=", "approved"],
["amo_status", "=", "pending"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["partner_status", "=", "approved"],
["amo_status", "=", "pending"],
])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Pending Margin Application Requests Fetched", "data" => $margin] ?? [];
}elseif(strtoupper($payload['action']) == "APPROVED")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["amo_status", "=", "approved"],
])
->get(); */
$margin = $this->marginApplicationTable()->where([["amo_status", "=", "approved"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Approved Margin Application Requests Fetched", "data" => $margin, "total" => count($margin) ?? 0] ?? [];
}elseif(strtoupper($payload['action']) == "REJECTED")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->where([
["amo_status", "=", "rejected"],
])
->get();
*/
$margin = $this->marginApplicationTable()->where([["amo_status", "=", "rejected"]])->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Rejected Margin Application Requests Fetched", "data" => $margin, "total" => count($margin) ?? 0] ?? [];
}elseif(strtoupper($payload['action']) == "FETCHALL")
{
/* $margin = $this->marginApplicationTable()
->leftJoin("margin_collateral", "margin_application.applicationID", "=", "margin_collateral.applicationID")
->select("margin_application.*", "margin_collateral.collateral", "margin_collateral.collateralValue")
->get(); */
$margin = $this->marginApplicationTable()->get();
$margin = json_decode(json_encode($margin),true);
//append collaterals
if(count($margin) > 0)
{
$i=0;
foreach($margin as $d)
{
$margin[$i]["collateral"] = $this->getMarginCollateral($d)['data'];
$i=$i+1;
}
}
return ["code" => 200,"message" => "Margin Application Requests Fetched", "data" => $margin] ?? [];
}
}
}
public function getInvestmentRequestSummary($payload)
{
if(strtoupper($payload['role']) == RICA)
{
$all = $this->CAMDealTable()->get();
$pending = $this->CAMDealTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])->get();
$approved = $this->CAMDealTable()
->where([
["rica_status", "=", "approved"],
])->get();
$rejected = $this->CAMDealTable()
->where([
["rica_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Investment Booking Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == FINCON)
{
$all = $this->CAMDealTable()->get();
$pending = $this->CAMDealTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])->get();
$approved = $this->CAMDealTable()
->where([
["fincon_status", "=", "approved"],
])->get();
$rejected = $this->CAMDealTable()
->where([
["fincon_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Investment Booking Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == PM)
{
$all = $this->CAMDealTable()->get();
$pending = $this->CAMDealTable()
->where([
["pm_status", "=", "pending"],
])->get();
$approved = $this->CAMDealTable()
->where([
["pm_status", "=", "approved"],
])->get();
$rejected = $this->CAMDealTable()
->where([
["pm_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Investment Booking Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}
}
public function getInvestmentLiquidationSummary($payload)
{
if(strtoupper($payload['role']) == RICA)
{
$all = $this->CAMDealBreakTable()->get();
$pending = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])->get();
$approved = $this->CAMDealBreakTable()
->where([
["rica_status", "=", "approved"],
])->get();
$rejected = $this->CAMDealBreakTable()
->where([
["rica_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Investment Liquidation Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == FINCON)
{
$all = $this->CAMDealBreakTable()->get();
$pending = $this->CAMDealBreakTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])->get();
$approved = $this->CAMDealBreakTable()
->where([
["fincon_status", "=", "approved"],
])->get();
$rejected = $this->CAMDealBreakTable()
->where([
["fincon_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Investment Liquidation Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == PM)
{
$all = $this->CAMDealBreakTable()->get();
$pending = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "pending"],
])->get();
$approved = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "approved"],
])->get();
$rejected = $this->CAMDealBreakTable()
->where([
["pm_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Investment Liquidation Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}
}
public function getMarginRequestSummary($payload)
{
if(strtoupper($payload['role']) == RICA)
{
$all = $this->marginApplicationTable()->get();
$pending = $this->marginApplicationTable()
->where([
["css_status", "=", "approved"],
["rica_status", "=", "pending"],
])->get();
$approved = $this->marginApplicationTable()
->where([
["rica_status", "=", "approved"],
])->get();
$rejected = $this->marginApplicationTable()
->where([
["rica_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Margin Application Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == PARTNER)
{
$all = $this->marginApplicationTable()->get();
$pending = $this->marginApplicationTable()
->where([
["rica_status", "=", "approved"],
["partner_status", "=", "pending"],
])->get();
$approved = $this->marginApplicationTable()
->where([
["partner_status", "=", "approved"],
])->get();
$rejected = $this->marginApplicationTable()
->where([
["partner_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Margin Application Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == AMO)
{
$all = $this->marginApplicationTable()->get();
$pending = $this->marginApplicationTable()
->where([
["rica_status", "=", "approved"],
["amo_status", "=", "pending"],
])->get();
$approved = $this->marginApplicationTable()
->where([
["amo_status", "=", "approved"],
])->get();
$rejected = $this->marginApplicationTable()
->where([
["amo_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Margin Application Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == CSS)
{
$all = $this->marginApplicationTable()->get();
$pending = $this->marginApplicationTable()
->where([
["css_status", "=", "pending"],
])->get();
$approved = $this->marginApplicationTable()
->where([
["css_status", "=", "approved"],
])->get();
$rejected = $this->marginApplicationTable()
->where([
["css_status", "=", "rejected"],
])->get();
return ["code" => 200,"message" => "Margin Application Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0] ?? [];
}
}
public function getWithdrawalRequestSummary($payload)
{
if(strtoupper($payload['role']) == RICA)
{
$all = $this->withdrawRequestTable()->get();
$pending = $this->withdrawRequestTable()
->where([
["pm_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->orWhere([
["ia_status", "=", "approved"],
["rica_status", "=", "pending"],
])
->get();
$approved = $this->withdrawRequestTable()
->where([
["rica_status", "=", "approved"],
])->get();
$rejected = $this->withdrawRequestTable()
->where([
["rica_status", "=", "rejected"],
])->get();
$unattended = $this->withdrawRequestTable()
->where([
["rica_status", "=", "processed_by_client"],
])->get();
return ["code" => 200,"message" => "Withdrawal Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0, "unattended" => count($unattended) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == FINCON)
{
$all = $this->withdrawRequestTable()->get();
$pending = $this->withdrawRequestTable()
->where([
["rica_status", "=", "approved"],
["fincon_status", "=", "pending"],
])->get();
$approved = $this->withdrawRequestTable()
->where([
["fincon_status", "=", "approved"],
])->get();
$rejected = $this->withdrawRequestTable()
->where([
["fincon_status", "=", "rejected"],
])->get();
$unattended = $this->withdrawRequestTable()
->where([
["fincon_status", "=", "processed_by_client"],
])->get();
return ["code" => 200,"message" => "Withdrawal Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0, "unattended" => count($unattended) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == AUTOPAY)
{
$all = $this->withdrawRequestTable()->get();
$pending = $this->withdrawRequestTable()
->where([
["fincon_status", "=", "approved"],
["autopay_status", "=", "pending"],
])->get();
$approved = $this->withdrawRequestTable()
->where([
["autopay_status", "=", "approved"],
])->get();
$rejected = $this->withdrawRequestTable()
->where([
["autopay_status", "=", "rejected"],
])->get();
$unattended = $this->withdrawRequestTable()
->where([
["autopay_status", "=", "processed_by_client"],
])->get();
return ["code" => 200,"message" => "Withdrawal Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0, "unattended" => count($unattended) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == PM)
{
$all = $this->withdrawRequestTable()
->where([["amount", ">", IA_APPROVE*1],
])->get();
$pending = $this->withdrawRequestTable()
->where([
["pm_status", "=", "pending"],
["amount", ">", IA_APPROVE*1],
])->get();
$approved = $this->withdrawRequestTable()
->where([
["pm_status", "=", "approved"],
["amount", ">", IA_APPROVE*1],
])->get();
$rejected = $this->withdrawRequestTable()
->where([
["pm_status", "=", "rejected"],
["amount", ">", IA_APPROVE*1],
])->get();
$unattended = $this->withdrawRequestTable()
->where([
["pm_status", "=", "processed_by_client"],
])->get();
return ["code" => 200,"message" => "Withdrawal Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0, "unattended" => count($unattended) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == IA)
{
$all = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])->get();
$pending = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["ia_status", "=", "pending"],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])->get();
$approved = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["ia_status", "=", "approved"],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])->get();
$rejected = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["ia_status", "=", "rejected"],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])->get();
$unattended = $this->withdrawRequestTable()
->where([
["ia_status", "=", "processed_by_client"],
])->get();
return ["code" => 200,"message" => "Withdrawal Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0, "unattended" => count($unattended) ?? 0] ?? [];
}elseif(strtoupper($payload['role']) == IALEAD)
{
$all = $this->withdrawRequestTable()
->where([
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])->get();
$pending = $this->withdrawRequestTable()
->where([
["ia_status", "=", "pending"],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])->get();
$approved = $this->withdrawRequestTable()
->where([
["ia_status", "=", "approved"],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])->get();
$rejected = $this->withdrawRequestTable()
->where([
["ia_status", "=", "rejected"],
["amount", ">", SELF_APPROVE*1],
["amount", "<=", IA_APPROVE*1],
])->get();
$unattended = $this->withdrawRequestTable()
->where([
["ia_status", "=", "processed_by_client"],
])->get();
return ["code" => 200,"message" => "Withdrawal Requests Summary Fetched", "all" => count($all) ?? 0, "pending" => count($pending) ?? 0, "approved" => count($approved) ?? 0, "rejected" => count($rejected) ?? 0, "unattended" => count($unattended) ?? 0] ?? [];
}
}
//for liquidation portal
/* public function processPaymentRequests($payload)
{
//filter action
if(strtoupper($payload['role']) == IA)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump($roleLimit );
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", "<=", IA_APPROVE*1],
["status", "=", "pending"],
])
->update([
"status" => "approved",
"initiator" => $payload['admin'],
"initiatorDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", "<=", IA_APPROVE*1],
["status", "=", "pending"],
])
->update([
"status" => "rejected",
"authorizer_status" => "canceled",
"rica_status" => "canceled",
"initiator" => $payload['admin'],
"comment" => $payload['comment'],
"initiatorDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()
->where([["accountOfficerEmail", "=", $payload['accountOfficerEmail']],
["amount", "<=", IA_APPROVE*1],
])
->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}
}elseif(strtoupper($payload['role']) == PM)
{
// $roleLimit = $this->withdrawRoleLimitTable()->select("limit")->where([["role","=",strtoupper($payload['role'])]])->first()->limit;
// var_dump(PM_APPROVE*1);
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", ">", PM_APPROVE*1],
["status", "=", "pending"],
])
->update([
"status" => "approved",
"initiator" => $payload['admin'],
"initiatorDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["amount", ">", PM_APPROVE*1],
["status", "=", "pending"],
])
->update([
"status" => "rejected",
"authorizer_status" => "canceled",
"rica_status" => "canceled",
"initiator" => $payload['admin'],
"comment" => $payload['comment'],
"initiatorDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()
->where([["amount", ">", PM_APPROVE*1],
])
->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}
}elseif(strtoupper($payload['role']) == FINCON)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["status", "=", "approved"],
["authorizer_status", "=", "pending"],
["initiator", "!=", null],
])
->update([
"authorizer_status" => "approved",
"authorizer" => $payload['admin'],
"authorizerDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["status", "=", "approved"],
["authorizer_status", "=", "pending"],
["initiator", "!=", null],
])
->update([
"authorizer_status" => "rejected",
"rica_status" => "canceled",
"authorizer" => $payload['admin'],
"authorizer_comment" => $payload['comment'],
"authorizerDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}
}elseif(strtoupper($payload['role']) == RICA)
{
if(strtoupper($payload['action']) == "APPROVE")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["status", "=", "approved"],
["authorizer_status", "=", "approved"],
["rica_status", "=", "pending"],
["authorizer", "!=", null],
])
->update([
"rica_status" => "approved",
"rica" => $payload['admin'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Approved"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "REJECT")
{
$withdraw = $this->withdrawRequestTable()
->where([
["ID", "=", $payload['ID']],
["CustID", "=", $payload['CustID']],
["amount", "=", $payload['amount']],
["status", "=", "approved"],
["authorizer_status", "=", "approved"],
["rica_status", "=", "pending"],
["authorizer", "!=", null],
])
->update([
"rica_status" => "rejected",
"rica" => $payload['admin'],
"rica_comment" => $payload['comment'],
"ricaDate" => Carbon::now()->format('Y-m-d H:i:s'),
]);
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Request Rejected"] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found or Action Not Allowed"] ?? [];
}
}elseif(strtoupper($payload['action']) == "FETCH")
{
$withdraw = $this->withdrawRequestTable()->get();
if($withdraw > 0)
{
return ["code" => 200,"message" => "Withdrawal Requests Fetched", "data" => $withdraw] ?? [];
}else{
return ["code" => 400,"message" => "Withdrawal Request Not Found"] ?? [];
}
}
}
} */
//process FINCON approved wallet withdraw request for final payout
public function bulkWithdrawFromWallet()
{
$payout = $this->getPendingBulkWithdrawFromWallet()['data'];
$totalRequest = count($payout);
$paid = 0;
$failed = 0;
$unprocessed = [];
foreach($payout as $payload)
{
// var_dump($payload);
/* //get customer details and recipient code from transfer client table
$customer = $this->transferTable()
->where([
["product", "=", "CSWALLET" ],
["CustID", "=", $payload['CustID'] ],
["recipientCode", "=", $payload['recipientCode'] ],
])->get()[0];
$payload_1 = json_decode(json_encode($customer),true); */
// var_dump($payload_1);
// die();
/* //fetch request from withdrawal request table
$fetch = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["status", "=", "pending"],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])->get();
if(count($fetch) == 0)
{
$unprocessed[$failed]['fullName'] = $payload['fullName'];
$unprocessed[$failed]['amount'] = $payload['amount'];
$unprocessed[$failed]['reason'] = "Withdrawal Request not found";
$failed = $failed +1;
continue;
} */
//check wallet balance
$balance = container('mutualFundModel')->getWalletBalance($payload);
if($balance['balance'] < $payload['amount'] )
{
$unprocessed[$failed]['fullName'] = $payload['fullName'] ;
$unprocessed[$failed]['amount'] = $payload['amount'] ;
$unprocessed[$failed]['reason'] = "Insufficient Balance" ;
$failed = $failed +1;
//update status field for client in withdrawal request table
$updateRequest = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])
->update([
"status" => "insufficent-balance",
]);
continue;
}
/* //check that recipient code is set
if(is_null($payload['recipientCode']) || empty($payload['recipientCode']) || $payload['recipientCode'] == "")
{
$unprocessed[$failed]['fullName'] = $payload['fullName'] ;
$unprocessed[$failed]['amount'] = $payload['amount'] ;
$unprocessed[$failed]['reason'] = "No valid Transfer Code. Contact IT" ;
$failed = $failed +1;
//update status field for client in withdrawal request table
$updateRequest = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])
->update([
"status" => "no-transfer-code",
]);
continue;
} */
//double check CAMID
if(!isset($payload['CAMID']) ||is_null($payload['CAMID']) || empty($payload['CAMID']) || $payload['CAMID'] == "")
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $customerId, MIDDLEWARE_DB_NAME))['data'];
$payload['CAMID'] = $customerz[0]['CAMID'];
}
//post wallet transaction for debit
$payload['transactionType'] = "DEBIT";
$payload['transactionAmount'] = $payload['amount'];
$payload['cash_account_id'] = CSWALLET_DEBIT_ACCOUNT;
$payload['productType'] = "BANK";
$payload["client_id"] = $payload["CAMID"];
$payload["reference"] = "CWD". container('mutualFundModel')->generateWalletTransactionId();
$payload["narration"] = "Being debit from ". $payload["fullName"]."'s wallet to credit Bank"; //for wallet withdrawal to customer's bank
$post = container('PaystackGatewayModel')->createTransactionOnInfowareForWalletWithdrawal($payload);
if($post["code"] == 200)
{
$payload['valueDate'] = $post["date_"] ;
$payload["transactionRef"] = $payload["reference"];
$payload["fundCode"] = CSWALLET_INVOLVEMENT;
//process cash transfer on paystack
$withdraw = container('PaystackRequest')->withdrawFromWallet($payload);
if($withdraw["status"] == true)
{
//create wallet spent
$this->createDailyWalletSpent($payload);
}else{
$unprocessed[$failed]['fullName'] = $payload['fullName'] ;
$unprocessed[$failed]['amount'] = $payload['amount'] ;
$unprocessed[$failed]['reason'] = "Payout from Paystack Failed (".$withdraw["message"] ."), but debit posted to Infoware" ;
$failed = $failed +1;
//update status field for client in withdrawal request table
$updateRequest = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])
->update([
"status" => "paystack-payout-failed-however-infoware-gl-posted-and-wallet-debited",
]);
continue;
}
}else{
$unprocessed[$failed]['fullName'] = $payload['fullName'] ;
$unprocessed[$failed]['amount'] = $payload['amount'] ;
$unprocessed[$failed]['reason'] = "Unablet to post debit to Infoware" ;
$failed = $failed +1;
//update status field for client in withdrawal request table
$updateRequest = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])
->update([
"status" => "infoware-GL-posting-failure-wallet-not-debited",
]);
continue;
}
//Post debit to client's wallet in local table
$wallet = container('mutualFundModel')->debitWallet($payload);
if($wallet["code"] == 200)
{
//notify FINCON and RICA
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"transactionType" => $payload["transactionType"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => CSWALLET_CASHACCOUNT,
"business" => "CAM",
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Successful Wallet Transaction")
->usingView('wallet_transaction_notification', $record)
->send();
//increase number of succesful transfer by 1
$paid = $paid + 1;
//update status field for client in withdrawal request table
$updateRequest = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])
->update([
"status" => "approved",
]);
}else
{
$unprocessed[$failed]['fullName'] = $payload['fullName'] ;
$unprocessed[$failed]['amount'] = $payload['amount'] ;
$unprocessed[$failed]['reason'] = "Unablet to post debit to Wallet Local. Please contact IT" ;
$failed = $failed +1;
//update status field for client in withdrawal request table
$updateRequest = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])
->update([
"status" => "partial-localdb-posting-failure",
]);
continue;
}
}
return ["code"=>200, "message"=>"Transfers To Bank Successful", "Total Request"=> $totalRequest, "Total Processed"=> $paid, "Unprocessed"=> $unprocessed] ?? [];
}
public function declineBulkWithdrawFromWallet($payout)
{
$totalRequest = count($payout);
$paid = 0;
$failed = 0;
$unprocessed = [];
foreach($payout as $payload)
{
//get customer details and recipient code from transfer client table
$customer = $this->transferTable()
->where([
["product", "=", "CSWALLET" ],
["CustID", "=", $payload['CustID'] ],
["recipientCode", "=", $payload['recipientCode'] ],
])->get()[0];
$payload += json_decode(json_encode($customer),true);
//fetch request from withdrawal request table
$fetch = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["status", "=", "pending"],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])->get();
if(count($fetch) == 0)
{
$unprocessed[$failed]['fullName'] = $payload['fullName'];
$unprocessed[$failed]['amount'] = $payload['amount'];
$unprocessed[$failed]['reason'] = "Withdrawal Request not found";
$failed = $failed +1;
continue;
}
//update status field for client in withdrawal request table
$updateRequest = $this->withdrawRequestTable()
->where([
["recipientCode", "=", $payload['recipientCode']],
["amount", "=", $payload['amount']],
["CustID", "=", $payload['CustID']],
])
->update([
"status" => "declined",
]);
// $failed = $failed + 1;
}
return ["code"=>200, "message"=>"Withrawal Requests Rejected", "Total Request"=> $totalRequest, "Unprocessed" => $unprocessed] ?? [];
}
//fetch requests to be processed by FINCON for autopay
public function getBulkWithdrawFromWallet()
{
$withdrawRequest = $this->withdrawRequestTable()->get();
$withdrawRequest = json_decode(json_encode($withdrawRequest),true);
$i=0;
foreach($withdrawRequest as $withdraw)
{
$balance = container('mutualFundModel')->getWalletBalance($withdraw);
$withdrawRequest[$i]['balance'] = $balance['balance'];
$i=$i+1;
}
return ["code"=>200, "message"=>"All withdrawal requests successfully fetched", "data"=> $withdrawRequest];
}
public function getPendingBulkWithdrawFromWallet()
{
$pendingWithdrawRequest = $this->withdrawRequestTable()-> where([['status', "=","pending"],['recipientCode', "!=",null]])->get();
$pendingWithdrawRequest = json_decode(json_encode($pendingWithdrawRequest),true);
$i=0;
foreach($pendingWithdrawRequest as $withdraw)
{
$balance = container('mutualFundModel')->getWalletBalance($withdraw);
$pendingWithdrawRequest[$i]['balance'] = $balance['balance'];
$i=$i+1;
}
return ["code"=>200, "message"=>"All pending withdrawal requests successfully fetched", "data"=> $pendingWithdrawRequest];
}
public function getLedgerType($payload)
{
$get = ["NGN" => "NGN","GBP" => "GBP","USD" => "USD"];
return $get ?? [];
}
/* public function getClientActiveCAMLedger($payload)
{
$ledgers = [];
$i = 0;
$payload["ledgerType"] = "NGN";
$get = formatIWRes(container('IWSRequest')->getActiveCAMInvestment($payload))['data'];
if(!is_null($get) && !empty($get) && $get != "")
{
$ledgers[$i]= "NGN";
$i = $i + 1;
}
$payload["ledgerType"] = "GBP";
$get = formatIWRes(container('IWSRequest')->getActiveCAMInvestment($payload))['data'];
if(!is_null($get) && !empty($get) && $get != "")
{
$ledgers[$i] = "GBP";
$i = $i + 1;
}
$payload["ledgerType"] = "USD";
$get = formatIWRes(container('IWSRequest')->getActiveCAMInvestment($payload))['data'];
if(!is_null($get) && !empty($get) && $get != "")
{
$ledgers[$i] = "USD";
$i = $i + 1;
}
return $ledgers ?? [];
} */
public function getClientActiveCAMLedger($payload)
{
$ledgers = [];
$i = 0;
$payload["businessInvolvement"] = CAM_DB_NAME;
$get = formatIWRes(container('IWSRequest')->getClientProductInvolvements($payload))['data'];
// var_dump($get);
foreach($get as $g)
{
if(strtoupper($g["Type"]) == "FI-CAM")
{
$ledgers[$i] = "NGN";
$i = $i + 1;
}elseif(strtoupper($g["Type"]) == "EINUSD-CAM")
{
$ledgers[$i] = "USD";
$i = $i + 1;
}elseif(strtoupper($g["Type"]) == "EINGBP-CAM")
{
$ledgers[$i] = "GBP";
$i = $i + 1;
}
}
/* foreach($get as $g)
{
if(strtoupper($g["Type"]) == "EINUSD-CAM")
{
$ledgers[$i] = "USD";
$i = $i + 1;
}
} */
return $ledgers ?? [];
}
public function getClientActiveCSSLedger($payload)
{
$ledgers = [];
$i = 0;
$payload["businessInvolvement"] = STOCKBROKING_DB_NAME;
$get = formatIWRes(container('IWSRequest')->getClientProductInvolvements($payload))['data'];
// var_dump($get);
foreach($get as $g)
{
if(strtoupper($g["Type"]) == "STK")
{
$ledgers[$i] = "NGN";
$i = $i + 1;
}elseif(strtoupper($g["Type"]) == "TROVE")
{
$ledgers[$i] = "USD";
$i = $i + 1;
}
}
/* foreach($get as $g)
{
if(strtoupper($g["Type"]) == "TROVE")
{
$ledgers[$i] = "USD";
$i = $i + 1;
}
} */
return $ledgers ?? [];
}
public function getClientActiveMFLedger($payload)
{
$ledgers = [];
$i = 0;
$payload["businessInvolvement"] = CAM_DB_NAME;
$get = formatIWRes(container('IWSRequest')->getClientProductInvolvements($payload))['data'];
// var_dump($get);
foreach($get as $g)
{
if(strtoupper($g["Type"]) == "CSPFI")
{
$ledgers[$i] = "NGN";
$i = $i + 1;
}elseif(strtoupper($g["Type"]) == "CSPFI2")
{
$ledgers[$i] = "USD";
$i = $i + 1;
}
}
/* foreach($get as $g)
{
if(strtoupper($g["Type"]) == "CSPFI2")
{
$ledgers[$i] = "USD";
$i = $i + 1;
}
} */
return $ledgers ?? [];
}
public function getClientActiveSMALedger($payload)
{
$ledgers = [];
$i = 0;
$payload["businessInvolvement"] = CAM_DB_NAME;
$get = formatIWRes(container('IWSRequest')->getClientProductInvolvements($payload))['data'];
// var_dump($get);
foreach($get as $g)
{
if(strtoupper($g["Type"]) == "SMA-CAM")
{
$ledgers[$i] = "NGN";
$i = $i + 1;
}
}
/* foreach($get as $g)
{
if(strtoupper($g["Type"]) == "CSPFI2")
{
$ledgers[$i] = "USD";
$i = $i + 1;
}
} */
return $ledgers ?? [];
}
public function getCashBalanceByLedgerType($payload)
{
$get = formatIWRes(container('IWSRequest')->getCashBalanceByLedgerType($payload))['data'];
return $get ?? [];
}
public function getOustandingBalance($payload)
{
$response = formatIWRes(container('IWSRequest')->getOutstandingBalance($payload))['data'];
return $response;
}
public function getCTRAccounttDetails($payload)
{
$response = formatIWRes(container('IWSRequest')->getCTRAcctDetails($payload))['data'];
return $response;
}
public function getCTRTransactionsDetails($payload)
{
$response = formatIWRes(container('IWSRequest')->getCTRTransDetails($payload))['data'];
return $response;
}
public function getCTRSignatoryInfo($payload)
{
$response = formatIWRes(container('IWSRequest')->getCTRSignatoryInfo($payload))['data'];
return $response;
}
/* public function getTotalCashBalanceByLedgerType($payload)
{
$result = formatIWRes(container('IWSRequest')->getCashBalanceByLedgerType($payload))['data'];
$margin = $this->marginClientTable()
->selectRaw('SUM(loanAmount) as margin')
->where([
["CustID", "=", $payload["CustID"]],
])
->get()[0]->margin;
$grandTotal = $marginSpent = 0;
$i = 0;
$grandTotal = array_sum(array_column($result, 'Balance')) ?? 0;
$unclearedBalance = array_sum(array_column($result, 'Uncleared Balance')) ?? 0;
if($grandTotal < 0 && strtoupper($payload['involvementType']) == "STK")
{
$marginSpent = $grandTotal * -1;
$default = (($marginSpent * -1) >= ($margin * 60/100)) ? true : false;
$margin = $margin + $grandTotal;
$grandTotal = 0;
}
if(strtoupper($payload['involvementType']) == "STK")
{
// return ["ledgerType" => $payload['ledgerType'] , "involvementType" => $payload['involvementType'] , "balance" => $grandTotal ?? "0" , "margin" => $margin ?? "0", "marginSpent" => $marginSpent, "default" => $default ?? "No"] ?? [];
return ["ledgerType" => $payload['ledgerType'] , "involvementType" => $payload['involvementType'] , "balance" => $grandTotal ?? "0" , "unclearedBalance" => $unclearedBalance ?? "0" , "margin" => $margin ?? "0", "marginSpent" => $marginSpent, "default" => $default ?? "No"] ?? [];
}else{
// $lien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $payload["cashAccount"]],['instrumentType' ,"=", $payload["instrumentType"]]])->first();
// $lien = json_decode(json_encode($lien),true);
// $lienValue = $lien["lienValue"] ?? 0;
// $margin = $this->marginClientTable()->selectRaw('SUM(loanAmount) as margin')->where([["CustID", "=", $payload["CustID"]],])->get()[0]->margin;
$lienValue = $this->marginLienTable()->selectRaw('SUM(lienValue) as lienValue')->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $payload["cashAccount"]]])->first()->lienValue ?? 0;
// return ["ledgerType" => $payload['ledgerType'] , "involvementType" => $payload['involvementType'] , "lienValue" => $lienValue, "balance" => ($grandTotal - $lienValue) ?? "0" ] ?? [];
return ["ledgerType" => $payload['ledgerType'] , "involvementType" => $payload['involvementType'] , "lienValue" => $lienValue, "balance" => $grandTotal ?? "0" ] ?? [];
}
} */
public function getTotalCashBalanceByLedgerType($payload)
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['CAMID'] = $customerz[0]['CAMID'];
$payload['SECID'] = $customerz[0]['SECID'];
$result = formatIWRes(container('IWSRequest')->getCashBalanceByLedgerType($payload))['data'];
$margin = $this->marginClientTable()
->selectRaw('SUM(loanAmount) as margin')
->where([
["CustID", "=", $payload["CustID"]],
])
->get()[0]->margin;
$collateral = $this->marginCollateralTable()
->selectRaw('SUM(lienValue) as lienValue')
->where([
["CustID", "=", $payload["CustID"]],
["status", "=", "active"],
])
->get()[0]->lienValue;
$grandTotal = $marginSpent = 0;
$i = 0;
$grandTotal_ = end($result);
$grandTotal = $grandTotal_['Balance']*1 ?? 0.00;
$unclearedBalance = $grandTotal_['Uncleared Balance']*1 ?? 0;
if($grandTotal < 0 && strtoupper($payload['involvementType']) == "STK")
{
$marginSpent = $grandTotal * -1;
$stockValue = $this->getAllTotalSecurityHolding($payload)['totalMarketValue'];
$breach = ($stockValue + $collateral)/$marginSpent;
$default = ($breach <= 1.4) ? true : false;
$margin = $margin + $grandTotal;
$grandTotal = 0.00;
}
$balanceToWithdraw = $grandTotal - $unclearedBalance;
if(strtoupper($payload['involvementType']) == "STK")
{
// return ["ledgerType" => $payload['ledgerType'] , "involvementType" => $payload['involvementType'] , "balance" => $grandTotal ?? 0 , "unclearedBalance" => $unclearedBalance ?? "0" , "margin" => $margin ?? "0", "marginSpent" => $marginSpent, "default" => $default ?? "No"] ?? [];
return ["ledgerType" => $payload['ledgerType'] , "involvementType" => $payload['involvementType'] , "balance" => $grandTotal ?? 0 , "unclearedBalance" => $unclearedBalance ?? "0" , "margin" => $margin ?? "0", "marginSpent" => $marginSpent, "maintenance" => strval($breach) ?? "N/A", "default" => $default ?? "No", "availableBalanceForWithdrawal" => $balanceToWithdraw] ?? [];
}else{
$lienValue = $this->marginLienTable()->selectRaw('SUM(lienValue) as lienValue')->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $payload["cashAccount"]]])->first()->lienValue ?? 0;
return ["ledgerType" => $payload['ledgerType'] , "involvementType" => $payload['involvementType'] , "lienValue" => $lienValue,"balance" => $grandTotal ?? "0", "availableBalanceForWithdrawal" => $balanceToWithdraw ] ?? [];
}
}
public function getSpecificStockHolding($payload)
{
$get = formatIWRes(container('IWSRequest')->getSpecificStockHolding($payload))['data'];
return $get ?? [];
}
public function getInvestmentType($payload)
{
$get = formatIWRes(container('IWSRequest')->getInvestmentType($payload))['data'];
return $get ?? [];
}
public function getCreateInvestmentType($payload)
{
$get = formatIWRes(container('IWSRequest')->getCreateInvestmentType($payload))['data'];
return $get ?? [];
}
public function getClientInvestmentType($payload)
{
$get = formatIWRes(container('IWSRequest')->getClientInvestmentType($payload))['data'];
return $get ?? [];
}
/**
* Get Holding for Specified Investment Type
*/
public function getHoldingByInvestmentType($payload) //create new fund
{
$customerz = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload['CustID'], MIDDLEWARE_DB_NAME))['data'];
$payload['stockbrokingID'] = $customerz[0]['SECID'];
$payload['assetMgmtID'] = $customerz[0]['ASSETID'];
$payload['CAMID'] = $customerz[0]['CAMID'];
$get = formatIWRes(container('IWSRequest')->getHoldingByInvestmentType($payload))['data'];
$i = 0;
foreach($get as $active)
{
//update interest key
$get[$i]['INTEREST'] = $active['CURRENTVALUE']*1 - $active['PRINCIPAL']*1;
//upadate lien value
$lien = $this->marginLienTable()
->where([['CustID' ,"=", $payload["CustID"]],
['instrumentType' ,"=", $active['INSTRUMENTTYPE']],
])
->first();
$lien = json_decode(json_encode($lien),true);
$get[$i]['existingLien'] = $lien["lienValue"] ?? 0;
//update book type
$book = $this->CAMProductTable()
->where([["instrumentType", "=", $active['INSTRUMENTTYPE']]])
->get();
if(count($book) == 0)
{
$book = $this->cpTable()
->where([["instrumentType", "=", $active['INSTRUMENTTYPE']]])
->get();
if(count($book) == 0)
{
$book = $this->tbillsTable()
->where([["instrumentType", "=", $active['INSTRUMENTTYPE']]])
->get();
}
}
$get[$i]['bookingType'] = $book[0]->bookingType;
$get[$i]['productType'] = $book[0]->productType;
$get[$i]['investmentType'] = $book[0]->investmentType;
//cater for CSP-ASSET management left over investments
if(strtoupper($active['INSTRUMENTTYPE']) == "MMI" || strtoupper($active['INSTRUMENTTYPE']) == "FI-FI" || strtoupper($active['INSTRUMENTTYPE']) == "MMI-GBP" || strtoupper($active['INSTRUMENTTYPE']) == "EIN")
{
$get[$i]['bookingType'] = "book";
}elseif(strtoupper($active['INSTRUMENTTYPE']) == "EUR-BOND" || strtoupper($active['INSTRUMENTTYPE']) == "FGN-BOND")
{
$get[$i]['bookingType'] = "request";
}
$i=$i+1;
}
return $get ?? [];
}
/**
* Get Total Holding for Specified Investment Type
*/
public function getTotalHoldingByInvestmentType($payload) //create new fund
{
$result = formatIWRes(container('IWSRequest')->getHoldingByInvestmentType($payload))['data'];
$grandTotal = 0;
$i = 0;
/* foreach($result as $res)
{
$grandTotal = $grandTotal + $res['CURRENTVALUE']*1;
} */
$grandTotal = array_sum(array_column($result, 'CURRENTVALUE')) ?? 0;
return ["Investment Type" => $payload['investmentType'], "Portfolio Value" => $grandTotal] ?? [];
}
/**
* Get Holding for All Investment Types
*/
public function getAllHoldingByLedgerType($payload) //create new fund
{
$result = formatIWRes(container('IWSRequest')->getAllHoldingByLedgerType($payload))['data'];
return $result ?? [];
}
/**
* Get CAM Holding for All Investment Types
*/
// public function getAllCAMHoldingByLedgerType($payload) //create new fund
// {
// $result = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
// return $result ?? [];
// }
public function getAllCAMHoldingByLedgerType($payload) {
if($payload['ledgerType'] === 'USD')
{
$results = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
$i = 0;
foreach($results as $result)
{
if($result['INSTRUMENTTYPE'] == "CAM-EIN" || $result['INSTRUMENTTYPE'] == "EIN")
{
$payload['investmentDate'] = $result['EFFECTIVEDATE'];
$payload['principal'] = $result['PRINCIPAL'];
$payload['rate'] = $result['INTERESTRATE'];
$res = container('customerModel')->EINValuationReport($payload);
// var_dump($res);
$results[$i]['INTERESTRATE'] = (string) $res['rate'];
$results[$i]['CURRENTVALUE'] = (string) ($res['accruedCoupon'] + $result['PRINCIPAL']);
$results[$i]['ACCRUEDCOUPON'] = (string) ($res['accruedCoupon']);
}
elseif($result['INSTRUMENTTYPE'] == "CAMEURBOND" || $result['INSTRUMENTTYPE'] == "CAMFGNBOND"){
$payload['investmentDate'] = $result['Last Coupon Date'] ?? $result['EFFECTIVEDATE'];
$payload['principal'] = $result['Face Value'];
$payload['rate'] = $result['INTERESTRATE'];
$res = container('customerModel')->BondValuationReport($payload);
$results[$i]['ACCRUEDCOUPON'] = (string) $res['accruedCoupon'];
$results[$i]['CURRENTVALUE'] = (string) ($res['accruedCoupon'] + $result['PRINCIPAL']);
}
$i=$i+1;
}
return $results;
}
elseif($payload['ledgerType'] === 'NGN')
{
$results = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
$i = 0;
foreach($results as $result)
{
if($result['INSTRUMENTTYPE'] == "CAMFGNBOND"){
$payload['investmentDate'] = $result['Last Coupon Date'] ?? $result['EFFECTIVEDATE'];
$payload['principal'] = $result['Face Value'];
$payload['rate'] = $result['INTERESTRATE'];
$res = container('customerModel')->BondValuationReport($payload);
$results[$i]['ACCRUEDCOUPON'] = (string) $res['accruedCoupon'];
$results[$i]['CURRENTVALUE'] = (string) ($res['accruedCoupon'] + $result['PRINCIPAL']);
}
$i=$i+1;
}
return $results;
}
else{
$results = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
return $results ?? [];
}
}
/**
* Get Client Middleware Data
*/
public function getUserDetailsFromMiddleware($payload) //create new fund
{
$result = formatIWRes(container('IWSRequest')->getUserDetailsFromMiddleware(MIDDLEWARE_DB_NAME, $payload['CustID']))['data'][0];
$result["bankAcctName"] = $result["Bank_Acct_Name"];
$result["bankAcctNumber"] = $result["Bank_Acct_No"];
$result["bankName"] = $result["Bank_Name"];
$result["bankCode"] = $result["bankCode"];
$result["BVNNumber"] = $result['BVN'];
$result['companyName'] = str_replace(",","",$result['Name']);
$result['fullName'] = str_replace(",","",$result['Name']);
$result = json_decode(json_encode($result),true);
// var_dump($result);
return $result ?? [];
}
/**
* Return Lagos time
*/
public function tradeTime() //create new fund
{
date_default_timezone_set("Africa/Lagos");
//echo date("h:i:s a");
return date("h:i:s a");
}
/**
* Return New York time
*/
public function us_tradeTime() //create new fund
{
date_default_timezone_set("America/New_York");
//echo date("h:i:s a");
return date("h:i:s a");
}
/**
* strip plus sign and url encode payload
*/
public function stripVariable($payload) //create new fund
{
// var_dump($payload);
$payload = urlencode($payload);
$payload = str_replace("+"," ",$payload);
return $payload;
}
/**
* Return countries
*/
public function getCountry() //create new fund
{
return $this->countryTable()->get();
}
/**
* Return states
*/
public function getState($payload) //create new fund
{
return $this->stateTable()
->where([['countryID','=',$payload['countryID']]])
->get();
}
/**
* Return cities
*/
public function getCity($payload) //create new fund
{
return $this->cityTable()
->where([['stateID','=',$payload['stateID']]])
->get();
}
/**
* Return lga
*/
public function getLGA($payload) //create new fund
{
return $this->lgaTable()
->where([['stateID','=',$payload['stateID']]])
->get();
}
/**
* Return true or false if Market is open or closed
*/
public function isMarketOpen() //create new fund
{
// $currDate = Carbon::now()->addDays(6)->format('Y-m-d');
$currDate = Carbon::now()->format('Y-m-d');
$currDate2 = Carbon::now()->format('Y-m-d');
$breakCurrDate =(explode("-",$currDate));
$lastDay = $day = $breakCurrDate[2];
$month = $breakCurrDate[1];
$year = $breakCurrDate[0];
$lastDayNumber = date("N", mktime(0,0,0,$month,$day,$year));
$lastDayName = date("l", mktime(0,0,0,$month,$day,$year));
//check if today falls on a weekend
$weekend = $this->checkIfWeekend($lastDayNumber);
if($weekend == true)
{
return ["message" => "Successfully Fetched NG Stock Market Status", "data" => false];
}elseif($weekend == false)
{
//check if today is a holiday
$holiday = $this->checkIfHoliday($currDate);
if($holiday == true)
{
return ["message" => "Successfully Fetched NG Stock Market Status", "data" => false];
}elseif($holiday == false)
{
//check if current time is withing trading hours
$currTime = $this->tradeTime();
$breakCurrTime =(explode(":",$currTime));
$hour = $breakCurrTime[0];
$min = $breakCurrTime[1];
$ampm_ = (explode(" ",$breakCurrTime[2]));
$ampm = $ampm_[1];
// if(($hour >= "10" && $hour <= "11" && $ampm == "am") || (($hour == "12" || $hour == "01") && $ampm == "pm") || ($hour == "02" && $min <= "25" && $ampm == "pm"))
if(($hour >= "10" && $hour <= "11" && $ampm == "am") || (($hour == "12" || $hour == "01") && $ampm == "pm") || ($hour == "02" && $min <= "25" && $ampm == "pm"))
{
return ["message" => "Successfully Fetched NG Stock Market Status", "data" => true];
}else{
return ["message" => "Successfully Fetched NG Stock Market Status", "data" => false];
}
}
}
}
/**
* Return true or false if US Stock Market is open or closed
*/
public function isUSMarketOpen() //create new fund
{
// $currDate = Carbon::now()->addDays(6)->format('Y-m-d');
// $currDate = Carbon::now()->subHours(6)->format('Y-m-d');
$currDate = Carbon::now()->format('Y-m-d');
// $currDate2 = Carbon::now()->subHours(6)->format('Y-m-d');
$currDate2 = Carbon::now()->format('Y-m-d');
$breakCurrDate =(explode("-",$currDate));
$lastDay = $day = $breakCurrDate[2];
$month = $breakCurrDate[1];
$year = $breakCurrDate[0];
$lastDayNumber = date("N", mktime(0,0,0,$month,$day,$year));
$lastDayName = date("l", mktime(0,0,0,$month,$day,$year));
//check if today falls on a weekend
$weekend = $this->checkIfWeekend($lastDayNumber);
if($weekend == true)
{
return ["message" => "Successfully Fetched US Stock Market Status", "data" => false];
}elseif($weekend == false)
{
//check if today is a holiday
$holiday = $this->checkIfHoliday_US($currDate);
if($holiday == true)
{
return ["message" => "Successfully Fetched US Stock Market Status", "data" => false];
}elseif($holiday == false)
{
//check if current time is withing trading hours
$currTime = $this->us_tradeTime();
$breakCurrTime =(explode(":",$currTime));
$hour = $breakCurrTime[0];
$min = $breakCurrTime[1];
$ampm_ = (explode(" ",$breakCurrTime[2]));
$ampm = $ampm_[1];
// if(($hour >= "10" && $hour <= "11" && $ampm == "am") || (($hour == "12" || $hour == "01") && $ampm == "pm") || ($hour == "02" && $min <= "25" && $ampm == "pm"))
// if((($hour >= "9" && $min >= "30" && $hour <= "10" && $ampm == "am")) || ($hour == "10" && $hour == "11" && $ampm == "am") || (($hour == "12" || ($hour >= "01" && $hour <= "04")) && $ampm == "pm"))
if((($hour == "8" && $min >= "30" && $ampm == "am")) || (($hour == "9" ||$hour == "10" || $hour == "11") && $ampm == "am") || (($hour == "12" || ($hour >= "01" && $hour < "03")) && $ampm == "pm" ) || ($hour == "03" && $min <= "30"))
{
return ["message" => "Successfully Fetched US Stock Market Status", "data" => true];
}else{
return ["message" => "Successfully Fetched US Stock Market Status", "data" => false];
}
}
}
}
/**
* Get Client Stock Holding for CSS per CSCS Number
*/
public function getClientStockHolding($CustID, $CSCSNumber, $queryDate) //create new fund
{
$i = $totalMarketValue = $totalCost = $totalGainLoss = $totalGainLossPercent = 0;
$result = formatIWRes(container('IWSRequest')->getClientStockHolding($CustID, $CSCSNumber, $queryDate))['data'];
// foreach($result as $res)
// {
// $totalMarketValue = $totalMarketValue + $res['MarketValue']*1;
$totalMarketValue = array_sum(array_column($result, 'MarketValue')) ?? 0;
// $totalCost = $totalCost + $res['Total Cost']*1;
$totalCost = array_sum(array_column($result, 'Total Cost')) ?? 0;
// $totalGainLoss = $totalGainLoss + $res['Gain/Loss']*1;
$totalGainLoss = array_sum(array_column($result, 'Gain/Loss')) ?? 0;
// $totalGainLossPercent = $totalGainLossPercent + $res['Gain/Loss%']*1;
// $totalGainLossPercent = array_sum(array_column($result, 'Gain/Loss%')) ?? 0;
$totalGainLossPercent = ($totalCost != 0) ? ($totalGainLoss*100)/$totalCost : 0;
// }
foreach($result as $res)
{
$result[$i]['totalMarketValue'] = $totalMarketValue;
$result[$i]['totalCost'] = $totalCost;
$result[$i]['totalGainLoss'] = $totalGainLoss;
$result[$i]['totalGainLossPercent'] = $totalGainLossPercent;
$i = $i + 1;
}
return $result ?? [];
}
/**
* Get Total Holding for All Investment Types
*/
public function getAllTotalHoldingByInvestmentType($payload) //create new fund
{
//get CAM Investments (individual Investments)
$result = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
//get SMA Investments (total SMA Value)
$smaTotal = $this->getSMAInvestmentTotal($payload);
$smaLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", SMA_CASHACCOUNT],['instrumentType' ,"=", SMA_INSTRUMENTTYPE]])->first();
$smaLien = json_decode(json_encode($smaLien),true);
$smaExistingLien = $smaLien["lienValue"]*1 ?? 0;
//get MF Investments (individual mutual funds)
$mutualFund = $this->getAllMFInvestments($payload);
$mf = $this->getMFInvestmentTotal($payload);
$mfTotal = $mf;
$FIGrandTotal = $FIGrandPTotal = 0;
$BondGrandTotal = $BondGrandPTotal = 0;
$MAGrandTotal = $MAGrandPTotal = 0;
$TBGrandTotal = $TBGrandPTotal = 0;
$OGrandTotal = $OGrandPTotal = 0;
foreach($result as $res)
{
if(strtoupper($res['INVESTMENT TYPE']) == "FIXED INCOME")
{
$FIGrandTotal = $FIGrandTotal + $res['CURRENTVALUE']*1;
$FIGrandPTotal = $FIGrandPTotal + $res['PRINCIPAL']*1;
$FICashAccount = $res['cashAccount'];
$FIInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}elseif(strtoupper($res['INVESTMENT TYPE']) == "BONDS")
{
$BondGrandTotal = $BondGrandTotal + $res['CURRENTVALUE']*1;
$BondGrandPTotal = $BondGrandPTotal + $res['PRINCIPAL']*1;
$BondCashAccount = $res['cashAccount'];
$BondInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}elseif(strtoupper($res['INVESTMENT TYPE']) == "TREASURY BILL")
{
$TBGrandTotal = $TBGrandTotal + $res['CURRENTVALUE']*1;
$TBGrandPTotal = $TBGrandPTotal + $res['PRINCIPAL']*1;
$TBCashAccount = $res['cashAccount'];
$TBInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}elseif(strtoupper($res['INVESTMENT TYPE']) == "OTHERS")
{
$OGrandTotal = $OGrandTotal + $res['CURRENTVALUE']*1;
$OGrandPTotal = $OGrandPTotal + $res['PRINCIPAL']*1;
}
}
$FILienValue = $BondLienValue = $TBLienValue = $MFLienValue = $SMALienValue = 0;
$FILien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $FICashAccount],['instrumentType' ,"=", $FIInstrumentType]])->first();
$FILien = json_decode(json_encode($FILien),true);
$FILienValue = $FILien["lienValue"] ?? 0;
// $FILienValue = $FIGrandTotal*1 - $FILienValue;
$BondLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $BondCashAccount],['instrumentType' ,"=", $BondInstrumentType]])->first();
$BondLien = json_decode(json_encode($BondLien),true);
$BondLienValue = $BondLien["lienValue"] ?? 0;
// $BondLienValue = $BondGrandTotal*1 - $BondLienValue;
$TBLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $TBCashAccount],['instrumentType' ,"=", $TBInstrumentType]])->first();
$TBLien = json_decode(json_encode($TBLien),true);
$TBLienValue = $TBLien["lienValue"] ?? 0;
// $TBLienValue = $TBGrandTotal*1 - $TBLienValue;
$grandTotal = $FIGrandTotal + $BondGrandTotal + $MAGrandTotal + $TBGrandTotal + $OGrandTotal + $smaTotal + $mfTotal;
$data_1 = [];
foreach($mutualFund as $mf)
{
$data_1 = array_merge($data_1 , ["investmentType" => $mf["FundName"],"instrumentType" => $mf["FundCode"], "principal" => 0, "existingLien" => $mf["existingLien"], "marketValue" => $mf["TotalAssetValue"]*1,"Gain/Loss" => 0,"Percentage" => ($grandTotal != 0) ? ($mf["TotalAssetValue"]*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal, "cashAccount"=>$mf["cashAccount"]]);
}
return [$data_1, ["investmentType" => "Fixed Income","instrumentType" => $FIInstrumentType ?? "N/A", "principal" => $FIGrandPTotal, "existingLien" => $FILienValue, "marketValue" => $FIGrandTotal, "Gain/Loss" => $FIGrandTotal-$FIGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($FIGrandTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$FICashAccount ?? "0"],
["investmentType" => "Bonds","instrumentType" => $BondInstrumentType ?? "N/A", "principal" => $BondGrandPTotal, "existingLien" => $BondLienValue, "marketValue" => $BondGrandTotal, "Gain/Loss" => $BondGrandTotal-$BondGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($BondGrandTotal*100)/$grandTotal :0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$BondCashAccount ?? "0"],
["investmentType" => "Treasury Bill","instrumentType" => $TBInstrumentType ?? "N/A", "principal" => $TBGrandPTotal, "existingLien" => $TBLienValue,"marketValue" => $TBGrandTotal,"Gain/Loss" => $TBGrandTotal-$TBGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($TBGrandTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$TBCashAccount ?? "0"],
["investmentType" => "Managed Account","instrumentType" => SMA_INSTRUMENTTYPE, "principal" => 0, "existingLien" => $smaExistingLien, "marketValue" => $smaTotal, "Gain/Loss" => 0,"Percentage" => ($grandTotal != 0) ? ($smaTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal,"cashAccount"=>SMA_CASHACCOUNT],
// ["investmentType" => "Others", "principal" => $OGrandPTotal,"marketValue" => $OGrandTotal,"Gain/Loss" => $OGrandTotal-$OGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($OGrandTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal],
];
}
/**
* Get CAM Portfolio Value
*/
public function getCAMPortfolioValue($payload) //create new fund
{
$result = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
$portfolioValue = array_sum(array_column($result, 'CURRENTVALUE')) ?? 0;
return["Portfolio Value"=>$portfolioValue] ?? [];
}
public function loadUSDEurobond ($customerId) {
$USDEurobond = formatIWRes(
// $this->IWSRequest->PGetData2('P_00112', "0711")
container('IWSRequest')->PGetData2ForCAM('P_00112', "{$customerId}",CAM_DB_NAME)
)['data'] ?? [];
$USDEurobondRunning = [];
for ($i = 0; $i < count($USDEurobond); ++$i) {
if ($USDEurobond[$i]['Status'] === 'Running') {
array_push($USDEurobondRunning, $USDEurobond[$i]);
}
}
$i = 0;
foreach($USDEurobondRunning as $run)
{
if($run['InstrumentType'] == "CAMEURBOND" || $run['InstrumentType'] == "CAMFGBOND")
{
$payload['investmentDate'] = $run['LastCouponDate'] ?? $run['EffectiveDate'];
$payload['principal'] = $run['FaceValue'];
$payload['rate'] = $run['Rate'];
$res = container('customerModel')->BondValuationReport($payload);
$USDEurobondRunning[$i]['Interest'] = (string) $res['accruedCoupon'];
$USDEurobondRunning[$i]['AccruedCoupon'] = (string) $res['accruedCoupon'];
$USDEurobondRunning[$i]['MarketValue'] = (string) ($res['accruedCoupon'] + $run['Principal Amount']);
}
$i=$i+1;
}
return compact('USDEurobondRunning');
}
public function computeValuationReport($customerId) {
$USDFiRunning = formatIWRes(
container('IWSRequest')->PGetData2ForCAM('P_00095', "{$customerId}|USD",CAM_DB_NAME)
)['data'] ?? [];
$i = 0;
foreach($USDFiRunning as $run)
{
if($run['InstrumentType'] == "CAM-EIN" || $run['InstrumentType'] == "EIN")
{
$payload['investmentDate'] = $run['EffectiveDate'];
$payload['principal'] = $run['Principal Amount'];
$payload['rate'] = $run['Rate'];
$res = container('customerModel')->EINValuationReport($payload);
// var_dump($res);
$USDFiRunning[$i]['Interest'] = (string) $res['accruedCoupon'];
$USDFiRunning[$i]['MarketValue'] = (string) ($res['accruedCoupon'] + $run['Principal Amount']);
$USDFiRunning[$i]['FaceValue'] = (string) ($res['accruedCoupon']);
$USDFiRunning[$i]['Rate2'] = (string) ($res['accruedCoupon']);
}
$i=$i+1;
}
extract($this->loadUSDEurobond ($customerId));
$USDFiRunning = array_merge($USDEurobondRunning, $USDFiRunning);
$USDFiTotal = array_sum(array_column($USDFiRunning,'MarketValue')) ?? 0;
$USDFiPrincipal = array_sum(array_column($USDFiRunning, 'Principal Amount')) ?? 0;
$USDFiDiff = $USDFiTotal - $USDFiPrincipal;
if (count($USDFiRunning) >= 1) {
$USDFiRunning = array_map(function ($USDFi_Running) {
return array_merge(
$USDFi_Running,
[
// 'InterestAmount' => $USDFi_Running['InterestAmt'] ?? @$USDFi_Running['Maturity Amount'] - @$USDFi_Running['Principal'] ?? null,
'ActualMaturityDate' => $USDFi_Running['MaturityDate'] ?? null
]
);
}, $USDFiRunning);
}
return compact('USDFiRunning','USDFiTotal', 'USDFiPrincipal', 'USDFiDiff');
}
/**
* Get Total Holding for CAM Investment Types
*/
public function getAllCAMTotalHoldingByInvestmentType($payload) //create new fund
{
$result = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
$FIGrandTotal = $FIGrandPTotal = 0;
$BondGrandTotal = $BondGrandPTotal = 0;
$MAGrandTotal = $MAGrandPTotal = 0;
$TBGrandTotal = $TBGrandPTotal = 0;
$OGrandTotal = $OGrandPTotal = 0;
$CPGrandTotal = $CPGrandPTotal = 0;
$i = 0;
foreach($result as $res)
{
if(strtoupper($res['INVESTMENT TYPE']) == "FIXED INCOME")
{
if($payload['ledgerType'] === 'NGN'){
$FIGrandTotal = $FIGrandTotal + $res['CURRENTVALUE']*1;
$FICashAccount = $res['cashAccount'] ?? 0;
$FIInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}
elseif($payload['ledgerType'] === 'USD'){
$payload['investmentDate'] = $res['EFFECTIVEDATE'];
$payload['principal'] = $res['PRINCIPAL'];
$payload['rate'] = $res['INTERESTRATE'];
$report = container('customerModel')->EINValuationReport($payload);
$currentValue = (string) ($report['accruedCoupon'] + $res['PRINCIPAL']);
$FIGrandTotal = $FIGrandTotal + $currentValue;
$FIGrandPTotal = $FIGrandPTotal + $res['PRINCIPAL']*1;
$FICashAccount = $res['cashAccount'] ?? 0;
}
}elseif(strtoupper($res['INVESTMENT TYPE']) == "BONDS")
{
if($res['INSTRUMENTTYPE'] === "CAMFGNBOND")
{
$payload['investmentDate'] = $res['Last Coupon Date'] ?? $res['EFFECTIVEDATE'];
$payload['principal'] = $res['Face Value'];
$payload['rate'] = $res['INTERESTRATE'];
$report = container('customerModel')->BondValuationReport($payload);
$BondGrandTotal = $BondGrandTotal + ($report['accruedCoupon'] + $res['PRINCIPAL']);
$BondGrandPTotal = $BondGrandPTotal + $res['PRINCIPAL']*1;
$BondCashAccount = $res['cashAccount'] ?? 0;
$BondInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}
elseif($res['INSTRUMENTTYPE'] === "CAMEURBOND")
{
$payload['investmentDate'] = $res['Last Coupon Date'] ?? $res['EFFECTIVEDATE'];
$payload['principal'] = $res['Face Value'];
$payload['rate'] = $res['INTERESTRATE'];
$report = container('customerModel')->BondValuationReport($payload);
$BondGrandTotal = $BondGrandTotal + ($report['accruedCoupon'] + $res['PRINCIPAL']);
$BondGrandPTotal = $BondGrandPTotal + $res['PRINCIPAL']*1;
$BondCashAccount = $res['cashAccount'] ?? 0;
$BondInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}
}elseif(strtoupper($res['INVESTMENT TYPE']) == "TREASURY BILL")
{
$TBGrandTotal = $TBGrandTotal + $res['CURRENTVALUE']*1;
$TBGrandPTotal = $TBGrandPTotal + $res['PRINCIPAL']*1;
$TBCashAccount = $res['cashAccount'] ?? 0;
$TBInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}elseif(strtoupper($res['INVESTMENT TYPE']) == "COMMERCIAL PAPER")
{
$CPGrandTotal = $CPGrandTotal + $res['CURRENTVALUE']*1;
$CPGrandPTotal = $CPGrandPTotal + $res['PRINCIPAL']*1;
$CPCashAccount = $res['cashAccount'] ?? 0;
$CPInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}
}
$FILienValue = $BondLienValue = $TBLienValue = $MFLienValue = $SMALienValue = $CPLienValue = 0;
$FILien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $FICashAccount],['instrumentType' ,"=", $FIInstrumentType]])->first();
$FILien = json_decode(json_encode($FILien),true);
$FILienValue = $FILien["lienValue"] ?? 0;
// $FILienValue = $FIGrandTotal*1 - $FILienValue;
$CPLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $CPCashAccount],['instrumentType' ,"=", $CPInstrumentType]])->first();
$CPLien = json_decode(json_encode($CPLien),true);
$CPLienValue = $CPLien["lienValue"] ?? 0;
// $FILienValue = $FIGrandTotal*1 - $FILienValue;
$BondLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $BondCashAccount],['instrumentType' ,"=", $BondInstrumentType]])->first();
$BondLien = json_decode(json_encode($BondLien),true);
$BondLienValue = $BondLien["lienValue"] ?? 0;
// $BondLienValue = $BondGrandTotal*1 - $BondLienValue;
$TBLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $TBCashAccount],['instrumentType' ,"=", $TBInstrumentType]])->first();
$TBLien = json_decode(json_encode($TBLien),true);
$TBLienValue = $TBLien["lienValue"] ?? 0;
// $TBLienValue = $TBGrandTotal*1 - $TBLienValue;
$grandTotal = $FIGrandTotal + $BondGrandTotal + $TBGrandTotal + $CPGrandTotal;
return[
["investmentType" => "Fixed Income","instrumentType" => $FIInstrumentType ?? "N/A", "principal" => $FIGrandPTotal, "existingLien" => $FILienValue, "marketValue" => $FIGrandTotal, "Gain/Loss" => $FIGrandTotal-$FIGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($FIGrandTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$FICashAccount ?? "0"],
["investmentType" => "Commercial Papers","instrumentType" => $CPInstrumentType ?? "N/A", "principal" => $CPGrandPTotal, "existingLien" => $CPLienValue, "marketValue" => $CPGrandTotal, "Gain/Loss" => $CPGrandTotal-$CPGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($CPGrandTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$CPCashAccount ?? "0"],
["investmentType" => "Bonds","instrumentType" => $BondInstrumentType ?? "N/A", "principal" => $BondGrandPTotal, "existingLien" => $BondLienValue, "marketValue" => $BondGrandTotal, "Gain/Loss" => $BondGrandTotal-$BondGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($BondGrandTotal*100)/$grandTotal :0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$BondCashAccount ?? "0"],
["investmentType" => "Treasury Bill","instrumentType" => $TBInstrumentType ?? "N/A", "principal" => $TBGrandPTotal, "existingLien" => $TBLienValue,"marketValue" => $TBGrandTotal,"Gain/Loss" => $TBGrandTotal-$TBGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($TBGrandTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$TBCashAccount ?? "0"]] ?? [];
}
/* public function getAllCAMTotalHoldingByInvestmentType($payload) //create new fund
{
$result = formatIWRes(container('IWSRequest')->getAllCAMHoldingByLedgerType($payload))['data'];
$FIGrandTotal = $FIGrandPTotal = 0;
$BondGrandTotal = $BondGrandPTotal = 0;
$MAGrandTotal = $MAGrandPTotal = 0;
$TBGrandTotal = $TBGrandPTotal = 0;
$OGrandTotal = $OGrandPTotal = 0;
foreach($result as $res)
{
if(strtoupper($res['INVESTMENT TYPE']) == "FIXED INCOME")
{
$FIGrandTotal = $FIGrandTotal + $res['CURRENTVALUE']*1;
$FIGrandPTotal = $FIGrandPTotal + $res['PRINCIPAL']*1;
$FICashAccount = $res['cashAccount'] ?? 0;
$FIInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}elseif(strtoupper($res['INVESTMENT TYPE']) == "BONDS")
{
$BondGrandTotal = $BondGrandTotal + $res['CURRENTVALUE']*1;
$BondGrandPTotal = $BondGrandPTotal + $res['PRINCIPAL']*1;
$BondCashAccount = $res['cashAccount'] ?? 0;
$BondInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}elseif(strtoupper($res['INVESTMENT TYPE']) == "TREASURY BILL")
{
$TBGrandTotal = $TBGrandTotal + $res['CURRENTVALUE']*1;
$TBGrandPTotal = $TBGrandPTotal + $res['PRINCIPAL']*1;
$TBCashAccount = $res['cashAccount'] ?? 0;
$TBInstrumentType = $res['INSTRUMENTTYPE'] ?? "N/A";
}
}
$FILienValue = $BondLienValue = $TBLienValue = $MFLienValue = $SMALienValue = 0;
$FILien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $FICashAccount],['instrumentType' ,"=", $FIInstrumentType]])->first();
$FILien = json_decode(json_encode($FILien),true);
$FILienValue = $FILien["lienValue"] ?? 0;
// $FILienValue = $FIGrandTotal*1 - $FILienValue;
$BondLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $BondCashAccount],['instrumentType' ,"=", $BondInstrumentType]])->first();
$BondLien = json_decode(json_encode($BondLien),true);
$BondLienValue = $BondLien["lienValue"] ?? 0;
// $BondLienValue = $BondGrandTotal*1 - $BondLienValue;
$TBLien = $this->marginLienTable()->where([['CustID' ,"=", $payload["CustID"]],['cashAccount' ,"=", $TBCashAccount],['instrumentType' ,"=", $TBInstrumentType]])->first();
$TBLien = json_decode(json_encode($TBLien),true);
$TBLienValue = $TBLien["lienValue"] ?? 0;
// $TBLienValue = $TBGrandTotal*1 - $TBLienValue;
$grandTotal = $FIGrandTotal + $BondGrandTotal + $TBGrandTotal;
return[
["investmentType" => "Fixed Income","instrumentType" => $FIInstrumentType ?? "N/A", "principal" => $FIGrandPTotal, "existingLien" => $FILienValue, "marketValue" => $FIGrandTotal, "Gain/Loss" => $FIGrandTotal-$FIGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($FIGrandTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$FICashAccount ?? "0"],
["investmentType" => "Bonds","instrumentType" => $BondInstrumentType ?? "N/A", "principal" => $BondGrandPTotal, "existingLien" => $BondLienValue, "marketValue" => $BondGrandTotal, "Gain/Loss" => $BondGrandTotal-$BondGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($BondGrandTotal*100)/$grandTotal :0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$BondCashAccount ?? "0"],
["investmentType" => "Treasury Bill","instrumentType" => $TBInstrumentType ?? "N/A", "principal" => $TBGrandPTotal, "existingLien" => $TBLienValue,"marketValue" => $TBGrandTotal,"Gain/Loss" => $TBGrandTotal-$TBGrandPTotal,"Percentage" => ($grandTotal != 0) ? ($TBGrandTotal*100)/$grandTotal : 0,"Portfolio Value"=>$grandTotal,"cashAccount"=>$TBCashAccount ?? "0"]] ?? [];
} */
// public function purchaseVoucher($payload){
// $this->chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
// $this->length = 13;
// $voucherCode = "";
// $charArray = str_split($this->chars);
// for ($i = 0; $i < $this->length; $i++) {
// $index = array_rand($charArray);
// $voucherCode .= $charArray[$index];
// }
// // var_dump($payload["senderPhoneNumber"]);
// // var_dump($payload["senderEmailAddress"]);
// // var_dump($voucherCode);
// // var_dump($this->chars);
// // die();
// $this->id = $this->voucherTable()
// ->insertGetId([
// 'recipientFullName' => $payload["recipientFullName"],
// 'recipientEmailAddress' => $payload["recipientEmailAddress"],
// 'recipientPhoneNumber' => $payload["recipientPhoneNumber"],
// 'senderFullName' => $payload["senderFullName"],
// 'senderCustID' => $payload["CustID"],
// 'senderPhoneNumber' => $payload["senderPhoneNumber"],
// 'senderEmailAddress' => $payload["senderEmailAddress"],
// 'voucherCode' => $payload["CustID"]."-".$voucherCode,
// 'voucherValue' => $payload["voucherValue"],
// 'transactionID' => $payload["transactionID"],
// 'voucherCashAccount' => (strtoupper($payload["companyName"]) == "CSS") ? VOUCHER_CSS : VOUCHER_CAM,
// ]);
// if(count($this->id) > 0 && strtolower($payload["channel"]) == "cswallet")
// {
// //send email to recipient
// $result = [
// 'recipientFullName' => $payload["recipientFullName"],
// 'recipientEmailAddress' => $payload["recipientEmailAddress"],
// 'recipientPhoneNumber' => $payload["recipientPhoneNumber"],
// 'senderFullName' => $payload["senderFullName"],
// 'senderCustID' => $payload["CustID"],
// 'senderPhoneNumber' => $payload["senderPhoneNumber"],
// 'senderEmailAddress' => $payload["senderEmailAddress"],
// 'voucherCode' => $payload["CustID"]."-".$voucherCode,
// 'voucherValue' => $payload["voucherValue"],
// ];
// if(ENVIRONMENT === 'testing'){
// (new Mailer())
// ->to(DEFUALT_EMAIL)
// // ->bcc($payload["accountOfficerEmail"])
// ->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
// ->subject("Gift Voucher Notification")
// ->usingView('gift_voucher', $result)
// ->send();
// }else{
// (new Mailer())
// ->to($payload["recipientEmailAddress"])
// // ->bcc($payload["accountOfficerEmail"])
// ->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
// ->subject("Gift Voucher Notification")
// ->usingView('gift_voucher', $result)
// ->send();
// }
// }
// if(count($this->id) > 0)
// {
// return["code" => 200, "message" => "Voucher successfully created."];
// }else{
// return["code" => 400, "message" => "Voucher creation failed."];
// }
// }
// public function verifyVoucher($payload){
// //get voucher details
// $voucher = $this->voucherTable()
// ->where([['voucherCode','=',$payload['voucherCode']],
// ['status','=',null],
// ])
// ->first();
// if(count($voucher) > 0)
// {
// $voucher = json_decode(json_encode($voucher),true);
// return["code" => 200, "message" => "Voucher successfully verified.", "voucherValue" => $voucher["voucherValue"]];
// }else{
// return["code" => 400, "message" => "Voucher not found."];
// }
// }
/* public function redeemVoucher($payload) //use gift voucher
{
//get voucher details
$voucher = $this->voucherTable()
->where([['voucherCode','=',$payload['voucherCode']],
['status','=',null],
])
->first();
if(count($voucher) > 0)
{
$voucher = json_decode(json_encode($voucher),true);
// $payload["client_id"] = $payload["CAMID"];
$payload["voucherCode"] = $voucher["voucherCode"];
$payload["voucherValue"] = $voucher["voucherValue"];
$payload["recipientEmailAddress"] = $voucher["recipientEmailAddress"];
$payload["recipientPhoneNumber"] = $voucher["recipientPhoneNumber"];
$payload["reference"] = $voucher["transactionID"];
$payload["transactionID"] = $voucher["transactionID"];
$payload["voucherCashAccount"] = $voucher["voucherCashAccount"];
$payload["transactionAmount"] = $voucher["voucherValue"];
$payload["productType"] = $payload["voucherProduct"];
$payload['ledgerType'] = "NGN";
// $payload['businessInvolvement'] = ($payload['cash_account_id'] == STOCKBROKING_BUSINESS_ACC_ID || $payload['cash_account_id'] == TROVE) ? STOCKBROKING_DB_NAME : CAM_DB_NAME;
if($payload['cash_account_id'] == STOCKBROKING_BUSINESS_ACC_ID || $payload['cash_account_id'] == TROVE)
{
$payload['businessInvolvement'] = STOCKBROKING_DB_NAME;
}else{
$payload['businessInvolvement'] = CAM_DB_NAME;
}
$payload["narration"] = "Being debit from CardinalStone Gift Voucher to credit ". $payload["productType"] . " for ". $payload["fullName"]; //for gift voucher
$payload["narration_1"] = "Being credit to ". $payload["productType"]." for " . $payload["fullName"] ." from CardinalStone Gift Voucher"; // for business
$post = container('PaystackGatewayModel')->redeemVoucher($payload);
$payload['valueDate'] = $post["date_"] ;
$payload["transactionRef"] = $payload["reference"];
if($post["code"] == 200)
{
//update voucher status to used
$voucher = $this->voucherTable()
->where([
["voucherCode", "=", $payload["voucherCode"] ],
["voucherValue", "=", $payload["voucherValue"] ],
["status", "=", null ] ,
["transactionID", "=", $payload["reference"] ]
])->update([
"status" => "redeemed",
"recipientCustID" => $payload["CustID"],
"recipientSECID" => $payload["SECID"],
"recipientCAMID" => $payload["CAMID"],
"recipientASSETID" => $payload["ASSETID"],
"recipientVoucherProduct" => $payload["voucherProduct"],
"recipientCashAccount" => $payload["cash_account_id"],
]);
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => $payload["voucherCashAccount"],
"business" => $payload["companyName"],
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Successful Voucher Redemption")
->usingView('voucher_redemption_notification', $record)
->send();
//log to interbank (wallet) table
$this->id = $this->walletTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'walletID' => $payload['CAMID'],
'fundCode' => $payload['voucherCashAccount'],
'emailAddress' => $payload['recipientEmailAddress'],
'fullName' => str_replace(",","",$payload['fullName']),
'phoneNumber' => $payload['recipientPhoneNumber'],
'transactionAmount' => $payload['transactionAmount'],
'absoluteAmount' => $payload['transactionAmount'],
'sourceAccount' => $payload['cash_account_id'] ?? "NA",
'senderName' => $payload['senderName'] ?? "NA",
'senderAccount' => $payload['senderAccount'] ?? "NA",
'senderBank' => $payload['senderBank'] ?? "NA",
'transactionType' => "DEBIT",
'valueDate' => $payload['valueDate'],
'transactionID' => $payload['reference'],
'narration' => $payload['narration'],
'admin' => $payload['admin'] ?? str_replace(",","",$payload['fullName'])
]);
return ["code" => 200,"message" => "Gift Voucher Successfully Redeemed.", "transactionRef" => $payload["reference"], "amount" => $payload["transactionAmount"]];
}else{ //Notify RICA of transaction failure
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => $payload["voucherCashAccount"],
"business" => $payload["companyName"],
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Failed Voucher Redemption - GL posting failure on Infoware")
->usingView('failed_voucher_redemption_notification', $record)
->send();
return ["code" => 400,"message" => "Gift Voucher Redemption Failed."];
}
}else{
return ["code" => 400,"message" => "Invalid Gift Voucher."];
}
} */
public function redeemVoucher($payload) //use gift voucher
{
//get voucher details
$voucher = $this->voucherTable()
->where([['voucherCode','=',$payload['voucherCode']],
['status','=',null],
])
->first();
if(count($voucher) > 0)
{
$voucher = json_decode(json_encode($voucher),true);
// $payload["client_id"] = $payload["CAMID"];
$payload["voucherCode"] = $voucher["voucherCode"];
$payload["voucherValue"] = $voucher["voucherValue"];
$payload["recipientEmailAddress"] = $voucher["recipientEmailAddress"];
$payload["recipientPhoneNumber"] = $voucher["recipientPhoneNumber"];
$payload["transactionID"] = $voucher["transactionID"];
$payload["reference"] = (substr($payload["transactionID"],0,3) == "CSS") ? "CSSVOUWAL" . $voucher["transactionID"] : "CAMVOUWAL" . $voucher["transactionID"];
$payload["voucherCashAccount"] = $voucher["voucherCashAccount"];
$payload["transactionAmount"] = $voucher["voucherValue"];
$payload["productType"] = $payload["voucherProduct"];
$payload['ledgerType'] = "NGN";
// $payload['businessInvolvement'] = ($payload['cash_account_id'] == STOCKBROKING_BUSINESS_ACC_ID || $payload['cash_account_id'] == TROVE) ? STOCKBROKING_DB_NAME : CAM_DB_NAME;
if($payload['cash_account_id'] == STOCKBROKING_BUSINESS_ACC_ID || $payload['cash_account_id'] == TROVE)
{
$payload['businessInvolvement'] = STOCKBROKING_DB_NAME;
}else{
$payload['businessInvolvement'] = CAM_DB_NAME;
}
$payload["narration"] = "Being debit from CardinalStone Gift Voucher to credit ". $payload["productType"] . " for ". $payload["fullName"]; //for gift voucher
$payload["narration_1"] = "Being credit to ". $payload["productType"]." for " . $payload["fullName"] ." from CardinalStone Gift Voucher"; // for business
$post = container('PaystackGatewayModel')->redeemVoucher($payload);
$payload['valueDate'] = $post["date_"] ;
$payload["transactionRef"] = $payload["transactionID"];
if($post["code"] == 200)
{
//update voucher status to used
$voucher = $this->voucherTable()
->where([
["voucherCode", "=", $payload["voucherCode"] ],
["voucherValue", "=", $payload["voucherValue"] ],
["status", "=", null ] ,
["transactionID", "=", $payload["transactionID"] ]
])->update([
"status" => "redeemed",
"recipientCustID" => $payload["CustID"],
"recipientSECID" => $payload["SECID"],
"recipientCAMID" => $payload["CAMID"],
"recipientASSETID" => $payload["ASSETID"],
"recipientVoucherProduct" => $payload["voucherProduct"],
"recipientCashAccount" => $payload["cash_account_id"],
]);
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => $payload["voucherCashAccount"],
"business" => $payload["companyName"],
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["transactionID"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Successful Voucher Redemption")
->usingView('voucher_redemption_notification', $record)
->send();
//log to interbank (wallet) table
$this->id = $this->walletTable()
->insertGetId([
'CustID' => $payload['CustID'],
'CAMID' => $payload['CAMID'],
'walletID' => $payload['CAMID'],
'fundCode' => $payload['voucherCashAccount'],
'emailAddress' => $payload['recipientEmailAddress'],
'fullName' => str_replace(",","",$payload['fullName']),
'phoneNumber' => $payload['recipientPhoneNumber'],
'transactionAmount' => $payload['transactionAmount'],
'absoluteAmount' => $payload['transactionAmount'],
'sourceAccount' => $payload['cash_account_id'] ?? "NA",
'senderName' => $payload['senderName'] ?? "NA",
'senderAccount' => $payload['senderAccount'] ?? "NA",
'senderBank' => $payload['senderBank'] ?? "NA",
'transactionType' => "DEBIT",
'valueDate' => $payload['valueDate'],
'transactionID' => $payload['transactionID'],
'narration' => $payload['narration'],
'admin' => $payload['admin'] ?? str_replace(",","",$payload['fullName'])
]);
return ["code" => 200,"message" => "Gift Voucher Successfully Redeemed.", "transactionRef" => $payload["transactionID"], "amount" => $payload["transactionAmount"]];
}else{ //Notify RICA of transaction failure
$record = [
"fullName" => $payload["fullName"],
"amount" => $payload["transactionAmount"],
"CustID" => $payload["CustID"],
"credit" => $payload["cash_account_id"],
"debit" => $payload["voucherCashAccount"],
"business" => $payload["companyName"],
"valueDate" => $payload['valueDate'],
"transactionRef" => $payload["reference"]
];
(new Mailer())
->to(\getenv("FINCON-EMAIL"))
->cc(\getenv("RICA-EMAIL"))
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Failed Voucher Redemption - GL posting failure on Infoware")
->usingView('failed_voucher_redemption_notification', $record)
->send();
return ["code" => 400,"message" => "Gift Voucher Redemption Failed."];
}
}else{
return ["code" => 400,"message" => "Invalid Gift Voucher."];
}
}
public function banks(){
return $this->bankCodeTable()
->get();
}
public function getTbillsInvestmentDetails()
{
$result = formatIWRes(container('IWSRequest')->getTbillsInvestmentDetails());
return $result;
}
public function createNubanCustomer_($payload) //create new fund
{
//check if customer has product involvement
$payload['CAMID'] = $payload['BIZID'];
$load["CustID"] = $payload["CustID"];
$BIZID = $payload["CAMID"];
$load["businessInvolvement"] = $DB = CAM_DB_NAME;
//get Involvement Type and company
$nubanProduct = $this->getNubanProduct(strtoupper($payload["product"]));
$payload['company'] = $nubanProduct->company;
$load["involvementType"] = $INVOLVEMENT = $nubanProduct->involvementType;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) != "TRUE")
{
$create = $this->createInvolvement($load);
if(!isset($payload["CAMID"]) || empty($payload["CAMID"]) || is_null($payload["CAMID"]) || $payload["CAMID"] == "")
{
$payload["CAMID"] = $create["BIZID"];
}
}
//get other middleware info
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $payload["CustID"], MIDDLEWARE_DB_NAME))['data'];
$payload['BVNMiddleName'] = str_replace(",","",$customers[0]['BVNMiddleName']);
$payload['BVNFirstName'] = str_replace(","," ",trim($customers[0]['BVNFirstName']));
$payload['BVNLastName'] = str_replace(","," ",trim($customers[0]['BVNLastName']));
$payload['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
$payload['fullName'] = str_replace(",","",$customers[0]['Name']);
$payload['firstName'] = str_replace(","," ",trim($customers[0]['FirstName']));
$payload['lastName'] = str_replace(","," ",trim($customers[0]['LastName']));
$payload['middleName'] = str_replace(","," ",trim($customers[0]['MiddleName']));
$payload['SECID'] = $customers[0]['SECID'];
$payload['ASSETID'] = $customers[0]['ASSETID'];
$payload['CAMID'] = $customers[0]['CAMID'];
$payload['emailAddress'] = $customers[0]['Email1'];
$payload['phoneNumber'] = $customers[0]['Phone1'];
//get BVN from bank details
$bank = $this->getCustomerBankDetails($payload["CustID"])[0];
if(count($bank) > 0)
{
$payload['accountNumber'] = $bank['AcctNumber'];
$payload['bankCode'] = $bank['SortCode'];
if(is_null($payload['bankCode']) || empty($payload['bankCode']) || $payload['bankCode'] == "")
{
$icode = $this->bankCode($bank['BankName']);
$payload['bankCode'] = $icode->iCode;
}
$payload['bankName'] = $bank['BankName'];
$payload['BVN'] = (isset($payload['BVN']) && !is_null($payload['BVN']) && !empty($payload['BVN']) && $payload['BVN'] != "") ? $payload['BVN'] : $bank['BVN'];
$payload['idType'] = "bvn";
$payload['idValue'] = $payload['BVN'];
}else{
return [
"message" => "Bank details must be provided to proceed",
"code" => 400,
];
}
$result = $this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["fundCode", "=", $payload['fundCode'] ],
["CustID", "=", $payload['CustID'] ],
])->get();
if(!empty($result) && count($result) != 0 && !is_null($result[0]->accountName) && !is_null($result[0]->accountNumber))
{
$responseData = "Virtal account already exists";
return [
"message" => $responseData,
"code" => 200,
"data" => $result ?? []
];
}elseif(!empty($result) && count($result) != 0 && (is_null($result[0]->accountName) || is_null($result[0]->accountNumber)))
{
$this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["fundCode", "=", $payload['fundCode'] ],
["CustID", "=", $payload['CustID'] ],
])->update([
'description' => $payload['description'],
'idType' => "bvn",
'idValue' => $payload['BVN'] ?? 0,
]);
$payload['customerCode'] = $result[0]->customerCode;
$responseData = "Virtual Account Creation in Progress";
}else{
$res = container('PaystackRequest')->createNubanCustomer($payload, $payload['product']);
if($res['status'] == true)
{
$this->id = $this->nubanTable()
->insertGetId([
'CustID' => $payload['CustID'],
'SECID' => $payload['SECID'],
'CAMID' => $payload['CAMID'],
'ASSETID' => $payload['ASSETID'],
'firstName' => $payload['firstName'],
'middleName' => $payload['middleName'],
'lastName' => $payload['lastName'],
'fullName' => $payload['fullName'],
'BVNFirstName' => $payload['BVNFirstName'],
'BVNLastName' => $payload['BVNLastName'],
'BVNMiddleName' => $payload['BVNMiddleName'],
'customerCode' => $res['data']['customer_code'],
'emailAddress' => $payload['emailAddress'],
'phoneNumber' => $payload['phoneNumber'],
'product' => $payload['fundCode'],
'description' => $payload['description'],
'fundCode' => $payload['fundCode'],
'company' => $payload['company'],
'idType' => "bvn",
'idValue' => $payload['BVN'],
'paystackCustomerID' => $res['data']['id'],
'riskAction' => $res['data']['risk_action'],
'integration' => $res['data']['integration'],
]);
$payload['customerCode'] = $res['data']['customer_code'];
}
$responseData = $res['message'];
}
//trigger customer validation
$this->validateNubanCustomer($payload);
//attempt to create nuban account
$this->createNubanAccount($payload);
$result = $this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["fundCode", "=", $payload['fundCode'] ],
["CustID", "=", $payload['CustID'] ],
])->get();
return [
"message" => $responseData,
"code" => 200,
"data" => $result ?? []
];
}
public function completeCustomerProfile($payload)
{
$updateMiddleware = formatIWRes(container('IWSRequest')->updateProfile($payload));
$updateCAMProfile = formatIWRes(container('IWSRequest')->updateCAMProfile($payload));
$updateBankDetails = formatIWRes(container('IWSRequest')->updateBankDetails($payload));
if($updateCAMProfile['StatusID'] === 0 && $updateBankDetails['StatusID'] === 0 && $updateMiddleware['StatusID'] === 0)
{
//create wallet
// $payload["fullName"] = str_replace(",","",$decodedApprove['lastName']. " " .$decodedApprove['firstName']);
$payload["fundCode"] = "CSWALLET";
$payload["company"] = "GROUP";
$payload["description"] = "CARDINALSTONE WALLET";
$payload["product"] = "CSWALLET";
$result = $this->nubanTable()
->where([
["product", "=", $payload['product'] ],
["fundCode", "=", $payload['fundCode'] ],
["CustID", "=", $payload['CustID'] ],
])->get();
if(empty($result) || count($result) == 0 || is_null($result[0]->accountName) || is_null($result[0]->accountNumber))
{
$this->createNubanCustomer_($payload);
}
$this->updateEmailVerificationTable($CustID);
return ["code" => 200, "message" => "Profile update successful"];
}else{
return ["code" => 400, "message" => "Profile update not successful"];
}
}
public function getBondsInvestmentDetails()
{
$result = formatIWRes(container('IWSRequest')->getBondsInvestmentDetails());
return $result;
}
public function BondValuationReport($payload)
{
$carbonDate = Carbon::parse($payload['investmentDate']);
$investmentDate = $carbonDate->format('Y-m-d');
$rate = $payload['rate']*1;
$idate = explode("-",$investmentDate);
$iyear = $idate[0]*1;
$imonth = $idate[1]*1;
$iday = $idate[2]*1;
$currentDate = Carbon::now()->format('Y-m-d');
$cdate = explode("-",$currentDate);
$cyear = $cdate[0]*1;
$nyear = $cdate[0] + 1;
$pyear = $cdate[0] - 1;
$cmonth = $cdate[1]*1;
$pmonth = $cdate[1] - 1;
$cday = $cdate[2]*1;
$principal = $payload['principal']*1;
$date_diff = $this->dateDiff360($iday, $imonth, $iyear,$cday, $cmonth, $cyear,false);
$accruedCoupon = $rate/100*($date_diff)/360*$principal;
return ['principal' => $principal, 'lastCouponDate' => $investmentDate, 'nextCouponDate' => $nextCouponDate, 'accruedCoupon' => $accruedCoupon, 'rate' => $rate, 'currentDate' => $currentDate, 'dateDifference' => $date_diff];
}
public function EINValuationReport($payload)
{
$investmentDate = $payload['investmentDate'];
$rate = $payload['rate']*1;
$idate = explode("-",$investmentDate);
$iyear = $idate[0]*1;
$imonth = $idate[1]*1;
$iday = $idate[2]*1;
$currentDate = Carbon::now()->format('Y-m-d');
$cdate = explode("-",$currentDate);
$cyear = $cdate[0]*1;
$nyear = $cdate[0] + 1;
$pyear = $cdate[0] - 1;
$cmonth = $cdate[1]*1;
$pmonth = $cdate[1] - 1;
$cday = $cdate[2]*1;
$principal = $payload['principal']*1;
//compute last coupoun date
$investmentDate = $payload['investmentDate'];
$investmentDate_ = date_create($payload['investmentDate']);
$investmentDate = date_format($investmentDate_,"Y-m-d");
$currentDate = Carbon::now()->format('Y-m-d');
$currentDate_ = date_create($currentDate);
$currentMarch = $cyear."-03-31";
$currentMarch_= date_create($currentMarch);
$currentSept = $cyear."-09-30";
$currentSept_ = date_create($currentSept);
$previousMarch = $pyear."-03-31";
$previousMarch_ = date_create($previousMarch);
$previousSept = $pyear."-09-30";
$previousSept_ = date_create($previousSept);
$nextMarch = $nyear."-03-31";
$nextMarch_ = date_create($nextMarch);
$nextSept = $nyear."-09-30";
$nextSept_ = date_create($nextSept);
$date_diff_id_ps = date_diff($investmentDate_,$previousSept_);
$date_diff_id_ps_ = $date_diff_id_ps->format("%R%a");
$date_diff_id_cm = date_diff($investmentDate_,$currentMarch_);
$date_diff_id_cm_ = $date_diff_id_cm->format("%R%a");
$date_diff_id_cs = date_diff($investmentDate_,$currentSept_);
$date_diff_id_cs_ = $date_diff_id_cs->format("%R%a");
$date_diff_cd_ps = date_diff($currentDate_,$previousSept_);
$date_diff_cd_ps_ = $date_diff_cd_ps->format("%R%a");
$date_diff_cd_cm = date_diff($currentDate_,$currentMarch_);
$date_diff_cd_cm_ = $date_diff_cd_cm->format("%R%a");
$date_diff_cd_cs = date_diff($currentDate_,$currentSept_);
$date_diff_cd_cs_ = $date_diff_cd_cs->format("%R%a");
if($date_diff_id_ps_ < 0 && $date_diff_id_cm_ > 0 && $date_diff_cd_cm_ > 0)
{
// var_dump(date_diff_id_ps_);
// var_dump(date_diff_id_cm_);
// var_dump('1');
$lastCouponDate = $investmentDate;
}elseif($date_diff_id_cm_ < 0 && $date_diff_id_cs_ > 0 && $date_diff_cd_cs_ > 0)
{
// var_dump(date_diff_id_cm_);
// var_dump(date_diff_id_cs_);
// var_dump('2');
$lastCouponDate = $investmentDate;
}elseif($date_diff_id_cs_ < 0 && $date_diff_cd_cs_ < 0)
{
// var_dump(date_diff_id_cm_);
// var_dump(date_diff_id_cs_);
// var_dump('2');
$lastCouponDate = $investmentDate;
}elseif($date_diff_id_ps_ > 0 && $date_diff_cd_cm_ > 0)
{
// var_dump(date_diff_id_ps_);
// var_dump(date_diff_cd_cm_);
// var_dump('3');
$lastCouponDate = $pyear."-09-30";
}elseif($date_diff_id_cs_ > 0 && $date_diff_cd_cs_ < 0)
{
// var_dump(date_diff_id_cs_);
// var_dump(date_diff_cd_cs_);
// var_dump('4');
$lastCouponDate = $cyear."-09-30";
}elseif($date_diff_id_cm_ > 0 && $date_diff_cd_cs_ > 0)
{
// var_dump(date_diff_id_cm_);
// var_dump(date_diff_cd_cs_);
// var_dump('5');
$lastCouponDate = $cyear."-03-31";
}else{
$lastCouponDate = $investmentDate;
}
//compute next coupoun date
if($date_diff_cd_cm_ < 0 && $date_diff_cd_cs_ > 0)
{
$nextCouponDate = $cyear."-09-30";
}elseif($date_diff_cd_cm_ > 0)
{
$nextCouponDate = $cyear."-03-31";
}elseif($date_diff_cd_cs_ < 0)
{
$nextCouponDate = $nyear ."-03-31";
}
//compute accruedCoupon
$lastCouponDate_ = date_create($lastCouponDate);
$date_diff_lc_cd = date_diff($lastCouponDate_,$currentDate_);
$date_diff_lc_cd_ = $date_diff_lc_cd->format("%R%a");
$lcdate = explode("-",$lastCouponDate);
$lcyear = $lcdate[0];
$lcmonth = $lcdate[1];
$lcday = $lcdate[2];
$date_diff_lc_cd_ = $this->dateDiff360($lcday, $lcmonth, $lcyear,$cday, $cmonth, $cyear,false);
$accruedCoupon = $rate/100*($date_diff_lc_cd_)/360*$principal;
return ['principal' => $principal, 'lastCouponDate' => $lastCouponDate, 'nextCouponDate' => $nextCouponDate, 'accruedCoupon' => $accruedCoupon, 'rate' => $rate, 'currentDate' => $currentDate, 'dateDifference' => $date_diff_lc_cd_];
}
/**
* Identify if a year is a leap year or not
*
* @param integer $year The year to test
* @return boolean TRUE if the year is a leap year, otherwise FALSE
*/
public function isLeapYear($year)
{
return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0));
}
/**
* Return the number of days between two dates based on a 360 day calendar
*
* @param integer $startDay Day of month of the start date
* @param integer $startMonth Month of the start date
* @param integer $startYear Year of the start date
* @param integer $endDay Day of month of the start date
* @param integer $endMonth Month of the start date
* @param integer $endYear Year of the start date
* @param boolean $methodUS Whether to use the US method or the European method of calculation
* @return integer Number of days between the start date and the end date
*/
public function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS)
{
if ($startDay == 31) {
--$startDay;
} elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::isLeapYear($startYear))))) {
$startDay = 30;
}
if ($endDay == 31) {
if ($methodUS && $startDay != 30) {
$endDay = 1;
if ($endMonth == 12) {
++$endYear;
$endMonth = 1;
} else {
++$endMonth;
}
} else {
$endDay = 30;
}
}
return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
}
public function valuationReport($payload)
{
//upload report to server
$transactionID = $payload["transactionID"] = Carbon::now()->format('Y-m-d') ."-" . $this->randomCode();
$directory = dirname(__DIR__, 2) . "/public_view/files/valuation_report/";
$i = 0;
foreach($payload['files'] as $file)
{
$i = $i + 1;
$transactionID = $payload["transactionID"] . "_" . $i;
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile_valuation($transactionID, $directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
$payload["report".$i] = env('IMAGE_URL')."valuation_report/" . $filename;
}
$payload["count"] = $i;
// if(strtolower($payload["channel"]) == "cswallet")
// {
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Valuation Statement Notification")
->usingView('valuation_report', $payload)
->send();
}else{
(new Mailer())
->to($payload['emailAddress'])
->bcc(["[email protected]","[email protected]"])
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("Valuation Statement Notification")
->usingView('valuation_report', $payload)
->send();
}
// }
/* $mailer = new Mailer();
try {
$mailer->ClearAttachments();
$mailer->set('Subject',"Provisional Offer Letter");
$mailer->AddAddress($loanDetails['Email']);
$mailer->AddEmbeddedImage('/var/www/html/infolink/embeded_images/top_cs_welcome.jpg', 'image1');
$mailer->msgHTML($template);
$mailer->AddAttachment($result);
if($records['Attach_Form']=='1'){
$mailer->AddAttachment('/var/www/html/infolink/src/form.pdf');
}
echo "stil here <br/>";
if($mailer->Send()) {
$offer->insert_data(sprintf("Update OfferLetterLogs set Status=1 where Status=0 and ID=%s",$loanDetails['ID']));
echo "Gone";
}
}catch (Exception $ex) {
echo 'Error Sending email ...';
} */
// var_dump($payload);
return ["code" => 200, "message" => "Report Request is being Processed"];
}
public function storeProfileImage($payload)
{
//check if image(s) exist for client and delete
$directory = dirname(__DIR__, 2) . "/public_view/files/profile_image/";
$filename1 = $payload["CustID"].".jpg";
$filename1a = $payload["CustID"].".JPG";
$filename2 = $payload["CustID"].".jpeg";
$filename2a = $payload["CustID"].".JPEG";
$filename3 = $payload["CustID"].".png";
$filename3a = $payload["CustID"].".PNG";
$file_pointer1 = $directory."{$filename1}";
$file_pointer1a = $directory."{$filename1a}";
$file_pointer2 = $directory."{$filename2}";
$file_pointer2a = $directory."{$filename2a}";
$file_pointer3 = $directory."{$filename3}";
$file_pointer3a = $directory."{$filename3a}";
if (file_exists($file_pointer1) || file_exists($file_pointer1a) || file_exists($file_pointer2) || file_exists($file_pointer2a) || file_exists($file_pointer3) || file_exists($file_pointer3a))
{
unlink($file_pointer1);
unlink($file_pointer1a);
unlink($file_pointer2);
unlink($file_pointer2a);
unlink($file_pointer3);
unlink($file_pointer3a);
}
//upload report to server
$name = $payload["CustID"];
$directory = dirname(__DIR__, 2) . "/public_view/files/profile_image/";
foreach($payload['files'] as $file)
{
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile_valuation($name, $directory, $uploadedFile);
// $filename = $this->moveUploadedFile($directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
// $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
}
// $report_encoded = base64_encode(file_get_contents($report));
// $email->addAttachment($report_encoded, "application/pdf", $report, "attachment");
$imageUrl = env('IMAGE_URL')."profile_image/" . $filename;
return ["code" => 200, "message" => "Profile Image Succefully Stored", "url" => $imageUrl ];
}
public function fetchProfileImage($payload)
{
$directory = dirname(__DIR__, 2) . "/public_view/files/profile_image/";
$filename1 = $payload["CustID"].".jpg";
$filename2 = $payload["CustID"].".jpeg";
$filename3 = $payload["CustID"].".png";
$file_pointer1 = $directory."{$filename1}";
$file_pointer2 = $directory."{$filename2}";
$file_pointer3 = $directory."{$filename3}";
// var_dump($file_pointer1);
// var_dump($file_pointer2);
// var_dump($file_pointer3);
if (file_exists($file_pointer1))
{
$imageUrl = env('IMAGE_URL')."profile_image/{$filename1}";
return ["code" => 200, "message" => "Profile Image Succefully Fetched", "url" => $imageUrl ];
}elseif (file_exists($file_pointer2))
{
$imageUrl = env('IMAGE_URL')."profile_image/{$filename2}";
return ["code" => 200, "message" => "Profile Image Succefully Fetched", "url" => $imageUrl ];
}elseif (file_exists($file_pointer3))
{
$imageUrl = env('IMAGE_URL')."profile_image/{$filename3}";
return ["code" => 200, "message" => "Profile Image Succefully Fetched", "url" => $imageUrl ];
}
$imageUrl = ($payload["gender"] == 1) ? env('IMAGE_URL')."profile_image/male.jpg" : env('IMAGE_URL')."profile_image/female.png";
return ["code" => 200, "message" => "Profile Image Not Found", "url" => $imageUrl ];
}
public function storeCompanyLogo($payload)
{
//check if image(s) exist for client and delete
$directory = dirname(__DIR__, 2) . "/public_view/files/company_logo/";
$filename1 = $payload["companyName"].".jpg";
$filename1a = $payload["companyName"].".JPG";
$filename2 = $payload["companyName"].".jpeg";
$filename2a = $payload["companyName"].".JPEG";
$filename3 = $payload["companyName"].".png";
$filename3a = $payload["companyName"].".PNG";
$file_pointer1 = $directory."{$filename1}";
$file_pointer1a = $directory."{$filename1a}";
$file_pointer2 = $directory."{$filename2}";
$file_pointer2a = $directory."{$filename2a}";
$file_pointer3 = $directory."{$filename3}";
$file_pointer3a = $directory."{$filename3a}";
if (file_exists($file_pointer1) || file_exists($file_pointer1a) || file_exists($file_pointer2) || file_exists($file_pointer2a) || file_exists($file_pointer3) || file_exists($file_pointer3a))
{
unlink($file_pointer1);
unlink($file_pointer1a);
unlink($file_pointer2);
unlink($file_pointer2a);
unlink($file_pointer3);
unlink($file_pointer3a);
}
//upload report to server
$name = $payload["companyName"];
$directory = dirname(__DIR__, 2) . "/public_view/files/company_logo/";
foreach($payload['files'] as $file)
{
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile_valuation($name, $directory, $uploadedFile);
// $filename = $this->moveUploadedFile($directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
// $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
}
// $report_encoded = base64_encode(file_get_contents($report));
// $email->addAttachment($report_encoded, "application/pdf", $report, "attachment");
$imageUrl = env('IMAGE_URL')."company_logo/" . $filename;
return ["code" => 200, "message" => "Company Logo Succefully Stored", "url" => $imageUrl ];
}
public function fetchCompanyLogo($payload)
{
$directory = dirname(__DIR__, 2) . "/public_view/files/company_logo/";
$filename1 = $payload["companyName"].".jpg";
$filename2 = $payload["companyName"].".jpeg";
$filename3 = $payload["companyName"].".png";
$file_pointer1 = $directory."{$filename1}";
$file_pointer2 = $directory."{$filename2}";
$file_pointer3 = $directory."{$filename3}";
// var_dump($file_pointer1);
// var_dump($file_pointer2);
// var_dump($file_pointer3);
if (file_exists($file_pointer1))
{
$imageUrl = env('IMAGE_URL')."company_logo/{$filename1}";
return ["code" => 200, "message" => "Company Logo Succefully Fetched", "url" => $imageUrl ];
}elseif (file_exists($file_pointer2))
{
$imageUrl = env('IMAGE_URL')."company_logo/{$filename2}";
return ["code" => 200, "message" => "Company Logo Fetched", "url" => $imageUrl ];
}elseif (file_exists($file_pointer3))
{
$imageUrl = env('IMAGE_URL')."company_logo/{$filename3}";
return ["code" => 200, "message" => "Company Logo Succefully Fetched", "url" => $imageUrl ];
}
return ["code" => 200, "message" => "Company Logo Not Found", "url" => $imageUrl ];
}
public function storeCRMRequest($payload)
{
//upload report to server
$name = $payload["CustID"];
$directory = dirname(__DIR__, 2) . "/public_view/files/crm_request/";
foreach($payload['files'] as $file)
{
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
// $filename = $this->moveUploadedFile_valuation($name, $directory, $uploadedFile);
$filename = $this->moveUploadedFile($directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
// $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
}
// $report_encoded = base64_encode(file_get_contents($report));
// $email->addAttachment($report_encoded, "application/pdf", $report, "attachment");
$imageUrl = env('IMAGE_URL')."crm_request/" . $filename;
return ["code" => 200, "message" => "CRM Image Request Succefully Stored", "url" => $imageUrl ];
}
public function storeRequest($payload)
{
//upload report to server
// $name = $payload["CustID"];
$directory = dirname(__DIR__, 2) . "/public_view/files/request/";
foreach($payload['files'] as $file)
{
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
// $filename = $this->moveUploadedFile_valuation($name, $directory, $uploadedFile);
$filename = $this->moveUploadedFile($directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
// $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
}
// $report_encoded = base64_encode(file_get_contents($report));
// $email->addAttachment($report_encoded, "application/pdf", $report, "attachment");
$imageUrl = env('IMAGE_URL')."request/" . $filename;
return ["code" => 200, "message" => "Request Image Succefully Stored", "url" => $imageUrl ];
}
public function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
/* Use it for json_encode some corrupt UTF-8 chars
* useful for = malformed utf-8 characters possibly incorrectly encoded by json_encode
*/
public function utf8ize( $mixed ) {
if (is_array($mixed)) {
// var_dump("Array");
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} elseif (is_string($mixed)) {
// var_dump("String");
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}else{
// var_dump("Others");
foreach ($mixed as $key => $value) {
// $mixed[$key] = mb_convert_encoding($value, "UTF-8", "UTF-8");
// var_dump($value);
}
}
return $mixed;
}
public function addBankAccount($payload){
//{$CustID}|{$bankAcctName}|{$bankCode}|{$bankAcctNumber}|{$sortCode}|{$BVNNumber}
// $bankInfo = $this->bankCode($res['data']['bank']['name']);
// $payload['bankAcctName'] = $res['data']['account_name'];
// $payload['bankCode'] = $bankInfo->bankCode;
// $payload['bankAcctNumber'] = $res['data']['account_number'];
// $payload['sortCode'] = $bankInfo->iCode;
// $payload['BVNNumber'] = $result[0]->idValue;
// $addBank = container('IWSRequest')->addBankAccount($payload);
$addBank = formatIWRes(container('IWSRequest')->addBankAccount($payload))["data"];
return["code" => 200, "message" => "Bank Details successfully Added"];
}
public function getInterBankReport(){
$data = $this->walletTable()
->where([["senderBank","=","NA"]])->get();
return["code" => 200, "message" => "Interbank Report successfully Generated", "data" => $data ?? []];
}
public function updateInterBankReport($payload){
foreach ($payload as $load)
{
$updateInterBankReport = $this->walletTable()
->where([
["id", "=", $load['id']],
["isPaid", "=", 0],
])
->update([
"isPaid" => 1,
"isPaidDate" => Carbon::now()->format('Y-m-d H:i:s')
]);
}
$data = [
"message" => "Processed Interbank Records successfully Updated.",
"status" => "success",
"code" => 200
];
return $data;
}
public function adUserDetails($username){
$data = $this->adUserTable()
->where([["userName","=",strtolower($username)]])->first()->group;
$data = json_decode(json_encode($data),true);
if(count($data) > 0)
{
return["code" => 200, "message" => "User AD Details Successfully Fetched", "data" => $data ?? []];
}else{
return["code" => 400, "message" => "User AD Details Not Found", "data" => []];
}
}
public function adUsers(){
$data = $this->adUserTable()->get();
$data = json_decode(json_encode($data),true);
if(count($data) > 0)
{
return["code" => 200, "message" => "User AD Details Successfully Fetched", "data" => $data ?? []];
}else{
return["code" => 400, "message" => "User AD Details Not Found", "data" => []];
}
}
public function adUserInfo($username){
$data = $this->adUserTable()
->where([["userName","=",strtolower($username)]])->first();
$data = json_decode(json_encode($data),true);
if(count($data) > 0)
{
return["code" => 200, "message" => "User AD Details Successfully Fetched", "data" => $data ?? []];
}else{
return["code" => 400, "message" => "User AD Details Not Found", "data" => []];
}
}
public function adUserInsert($payload){
$data = $this->adUserTable()
->insertGetId([
'userName' => $payload["username"],
'group' => $payload["group"],
]);
if(count($data) > 0)
{
return["code" => 200, "message" => "User AD Details Successfully Inserted",];
}else{
return["code" => 400, "message" => "User AD Details Insert Failed",];
}
}
public function updatePassword($payload){
$data = $this->adUserTable()
->insertGetId([
'userName' => $payload["username"],
'password' => $payload["password"],
]);
if(count($data) > 0)
{
return["code" => 200, "message" => "User AD Details Successfully Inserted",];
}else{
return["code" => 400, "message" => "User AD Details Insert Failed",];
}
}
public function adUserUpdateEmail($payload){
$data = $this->adUserTable()
->where([['userName', "=", $payload["username"]]])
->update(['email' => $payload["email"]]);
if(count($data) > 0)
{
return["code" => 200, "message" => "User AD Details Successfully Updated",];
}else{
return["code" => 400, "message" => "User AD Details Update Failed",];
}
}
public function adUserUpdate($payload){
$data = $this->adUserTable()
->where([['userName', "=", $payload["username"]]])
->update(['password' => $payload["password"]]);
if(count($data) > 0)
{
return["code" => 200, "message" => "User AD Details Successfully Updated",];
}else{
return["code" => 400, "message" => "User AD Details Update Failed",];
}
}
public function expiredKYC(){
$aboutToExpire = formatIWRes(container('IWSRequest')->aboutToExpire())['data'];
if(count($aboutToExpire) > 0)
{
// var_dump("*****************************************About To Expire*****************************************************");
// var_dump($aboutToExpire);
/* foreach($aboutToExpire as $payload)
{
//send Expire Means of ID Notification via email
$result = [
"fullName" => str_replace(",","",$payload['Name']),
"emailAddress" => $payload['Email1'],
"meansOfIdentification" => $payload['Means of ID'],
"idNumber" => $payload['ID Number'],
"expiryDate" => $payload['Means of ID Expiration Date'],
"url" => "https://kyc.cardinalstone.com",
];
(new Mailer())
// ->to($result['emailAddress'])
->to("[email protected]")
// ->bcc("[email protected]")
// ->bcc("[email protected]")
// ->bcc("[email protected]")
// ->bcc("[email protected]")
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Status Notification")
->usingView('about_to_expire_kyc_notification', $result)
->send();
} */
}
$expired = formatIWRes(container('IWSRequest')->expired())['data'];
if(count($expired) > 0)
{
// var_dump("**********************************************Expired********************************************************");
// var_dump($expired);
/* foreach($expired as $payload)
{
//send Expire Means of ID Notification via email
$result = [
"fullName" => str_replace(",","",$payload['Name']),
"emailAddress" => $payload['Email1'],
"meansOfIdentification" => $payload['Means of ID'],
"idNumber" => $payload['ID Number'],
"expiryDate" => $payload['Means of ID Expiration Date'],
"url" => "https://kyc.cardinalstone.com",
];
(new Mailer())
// ->to($result['emailAddress'])
->to("[email protected]")
// ->bcc("[email protected]")
// ->bcc("[email protected]")
// ->bcc("[email protected]")
// ->bcc("[email protected]")
->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
->subject("KYC Status Notification")
->usingView('expired_kyc_notification', $result)
->send();
} */
}
return["code" => 200, "message" => "KYC Expiry Notification Sent"];
}
public function getMarginInterestRate(){
$data = $this->marginInterestRateTable()->get();
$data = json_decode(json_encode($data),true);
if(count($data) > 0)
{
return["code" => 200, "message" => "Margin Interest Rates successfully Fetched", "data" => $data ?? []];
}else{
return["code" => 400, "message" => "No Margin Interest Rate Found", "data" => []];
}
}
public function updateMarginInterestRate($payload){
$data = $this->marginInterestRateTable()
->update([
"staff" => $payload["staff"],
"commercial" => $payload["commercial"],
"admin" => $payload["admin"],
]);
if(count($data) > 0)
{
return["code" => 200, "message" => "Margin Interest Rates successfully Updated"];
}else{
return["code" => 400, "message" => "Margin Interest Rate Update Failed"];
}
}
public function getCAMAUMProducts(){
$data = formatIWRes(container('IWSRequest')->getCAMAUMProducts())['data'];
return["code" => 200, "message" => "CAM AUM Products Fetched", "data" => $data ?? []];
}
public function getCAMAUM($payload){
$data = formatIWRes(container('IWSRequest')->getCAMAUM($payload))['data'];
return["code" => 200, "message" => "CAM AUM Fetched", "data" => $data ?? []];
}
public function getSMAEQAUM($payload){
$data = formatIWRes(container('IWSRequest')->getSMAEQAUM($payload))['data'];
return["code" => 200, "message" => "SMA Equities Fetched", "data" => $data ?? []];
}
public function getSECAUM($payload){
$data = formatIWRes(container('IWSRequest')->getSECAUM($payload))['data'];
return["code" => 200, "message" => "SEC AUM Products Fetched", "data" => $data ?? []];
}
public function retrieveTransactionDetails()
{
return container('capsule')
->table('paystack_payment_transactions')
->where('status', '=', 'initialized')
->orWhere('status', '=', 'ongoing')
->orWhere([['status', '=', 'purged'],['comment', '=', null]])
->get();
}
public function retrieveTransactionDetails_1()
{
return container('capsule')
->table('paystack_payment_transactions')
->where([['status', '=', 'success'],
["createdDate", 'like', Carbon::now()->format('Y-m-d') . '%'],
])
->get();
}
public function addSPAClient($payload)
{
//check if client is already in SPA table, if Yes, call updateSPA instead.
$payload['loanAmount'] = $this->marginClientTable()->selectRaw('SUM(loanAmount) as margin')->where([["CustID", "=", $payload["CustID"]],])->get()[0]->margin;
$payload['SECID'] = $this->marginClientTable()->where([["CustID", "=", $payload["CustID"]],])->get()[0]->SECID;
//get cscs number(s)
$cscs = formatIWRes(container('IWSRequest')->getCSCSNumber($payload))['data'];
foreach($cscs as $cscsNo)
{
$payload['CSCSNumber'] = $cscsNo['CsCsAcct#'];
$getSPAClient = formatIWRes(container('IWSRequest')->getSPAClient($payload['CSCSNumber']))['data'];
// $getSPAClient = $this->getSPAClient($payload['CSCSNumber']);
// if($getSPAClient["code"] == 200)
if(count($getSPAClient) > 0)
{
$data = formatIWRes(container('IWSRequest')->updateSPAClient($payload))['data'];
}else{
$data = formatIWRes(container('IWSRequest')->addSPAClient($payload))['data'];
}
}
return["code" => 200, "message" => "SPA Client Successfuly Added"];
}
public function updateSPAClient($payload)
{
$payload['loanAmount'] = $this->marginClientTable()->selectRaw('SUM(loanAmount) as margin')->where([["CustID", "=", $payload["CustID"]],])->get()[0]->margin;
//get cscs number(s)
$cscs = formatIWRes(container('IWSRequest')->getCSCSNumber($payload))['data'];
foreach($cscs as $cscsNo)
{
$payload['CSCSNumber'] = $cscsNo['CsCsAcct#'];
$data = formatIWRes(container('IWSRequest')->updateSPAClient($payload))['data'];
}
return["code" => 200, "message" => "SPA Client Successfuly Updated"];
}
public function removeSPAClient($payload)
{
$payload['loanAmount'] = $this->marginClientTable()->selectRaw('SUM(loanAmount) as margin')->where([["CustID", "=", $payload["CustID"]],])->get()[0]->margin;
//get cscs number(s)
$cscs = formatIWRes(container('IWSRequest')->getCSCSNumber($payload))['data'];
foreach($cscs as $cscsNo)
{
$payload['CSCSNumber'] = $cscsNo['CsCsAcct#'];
$data = formatIWRes(container('IWSRequest')->removeSPAClient($payload))['data'];
}
return["code" => 200, "message" => "SPA Client Successfuly Removed"];
}
public function getCSCSDetails($payload)
{
//get cscs number(s)
$cscs = formatIWRes(container('IWSRequest')->getCSCSNumber($payload))['data'];
return["code" => 200, "message" => "Details retrieved", "data" => $cscs];
}
public function getSPAClient($cscsNo)
{
$data = formatIWRes(container('IWSRequest')->getSPAClients())['data'];
$spa = array_search($cscsNo, array_column($data, 'CSCSAcctNum'));
if($spa > 0)
{
// return["code" => 200, "message" => "SPA Client Successfuly Fetched", "data" => $data ?? [], "count" => count($data)];
return["code" => 200, "message" => "SPA Client Successfuly Fetched"];
}else{
return["code" => 400, "message" => "SPA Client Not Found"];
}
}
public function getSPAClients()
{
$data = formatIWRes(container('IWSRequest')->getSPAClients())['data'];
return["code" => 200, "message" => "SPA Clients Successfuly Fetched", "data" => $data ?? []];
}
public function investmentCalculator($payload)
{
$rate = ($payload["rate"]*1)/100;
$frequency = $payload["frequency"]*1;
$tenor = $payload["tenor"]*1;
$pv = $payload["capital"]* -1;
$pmt = $payload["additional"]* -1;
$nrate = $rate/$frequency;
$nper = $tenor * $frequency;
/* var_dump($rate);
var_dump($nrate);
var_dump($frequency);
var_dump($tenor);
var_dump($pv);
var_dump($pmt);
var_dump($nper); */
$fv = $this->fv($nrate, $nper,0, $pv);
$fv_minus_addtional = $this->fv($nrate, $nper,$pmt, $pv) + $pmt;
$fv_plus_addtional = $this->fv($nrate, $nper,$pmt, $pv);
$data = ["future_value" => round($fv,2), "future_value_minus_addtional" => round($fv_minus_addtional,2), "future_value_plus_addtional" => round($fv_plus_addtional,2)];
return["code" => 200, "message" => "Investment Computation Complete", "data" => $data ?? []];
}
/**
* Future value for a loan or annuity with compound interest.
*
* Same as the =FV() function in most spreadsheet software.
*
* The basic future-value formula derivation:
* https://en.wikipedia.org/wiki/Future_value
*
* PMT*((1+r)ᴺ - 1)
* FV = -PV*(1+r)ᴺ - ----------------
* r
*
* The (1+r*when) factor adjusts the payment to the beginning or end
* of the period. In the common case of a payment at the end of a period,
* the factor is 1 and reduces to the formula above. Setting when=1 computes
* an "annuity due" with an immediate payment.
*
* Examples:
* The future value in 5 years on a 30-year fixed mortgage note of $265000
* at 3.5% interest paid at the end of every month. This is how much loan
* principle would be outstanding:
* fv(0.035/12, 5*12, 1189.97, -265000, false)
*
* The present_value is negative indicating money borrowed for the mortgage,
* whereas payment is positive, indicating money that will be paid to the
* mortgage.
*
* @param float $rate
* @param int $periods
* @param float $payment
* @param float $present_value
* @param bool $beginning adjust the payment to the beginning or end of the period
*
* @return float
*/
public function fv(float $rate, int $periods, float $payment, float $present_value, bool $beginning = false)
{
$when = $beginning ? 1 : 0;
if ($rate == 0) {
$fv = -($present_value + ($payment * $periods));
return $fv;
}
$initial = 1 + ($rate * $when);
$compound = pow(1 + $rate, $periods);
$fv = -(($present_value * $compound) + (($payment * $initial * ($compound - 1)) / $rate));
return $fv;
}
/**
* Extracted from the PEAR package Math_Finance by Alejandro Pedraza
* http://pear.php.net/package/Math_Finance
*
* Returns the Present Value of a cash flow with constant payments and interest rate (annuities)
* Excel equivalent: PV
*
* TVM functions solve for a term in the following formula:
* pv(1+r)^n + pmt(1+r.type)((1+r)^n - 1)/r) +fv = 0
*
*
* @param float Interest rate per period
* @param int Number of periods
* @param float Periodic payment (annuity)
* @param float Future Value
* @param int Payment type:
FINANCE_PAY_END (default): at the end of each period
FINANCE_PAY_BEGIN: at the beginning of each period
* @return float
* @static
* @access public
*/
public function presentValue($rate, $nper, $pmt, $fv = 0, $type = 0)
{
if ($nper < 0) {
return PEAR::raiseError('Number of periods must be positive');
}
if ($type != FINANCE_PAY_END && $type != FINANCE_PAY_BEGIN) {
return PEAR::raiseError('Payment type must be FINANCE_PAY_END or FINANCE_PAY_BEGIN');
}
if ($rate) {
$pv = (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
} else {
$pv = -$fv - $pmt * $nper;
}
return $pv;
}
public function updateBusinessFlags()
{
/********************fetch records where SOF is 0 or null or empty string********************************************/
$BIZ = "SOF";
$getFlag = formatIWRes(container('IWSRequest')->getFlag($BIZ))["data"];
//check records where CSS is 0 or null or empty string and update accordingly
$count = 0;
foreach($getFlag as $flag)
{
if(isset($flag["ASSETID"]) && !is_null($flag["ASSETID"]) && !empty($flag["ASSETID"]) && $flag["ASSETID"] != "")
{
$BIZID = $flag["ASSETID"];
$INVOLVEMENT = SOF_INVOLVEMENT;
$DB = ASSETMGMT_DB_NAME;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
// var_dump(strtoupper($verify["data"]));
if(strtoupper($verify["data"]) == "TRUE")
{
//update business flag to 1
$customerInfo = $this->getCustomerDetails($flag['CustID']);
if($customerInfo[$BIZ] === "0" || $customerInfo[$BIZ] === "" || $customerInfo[$BIZ] === null){
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag["CustID"], $BIZ));
$count = $count + 1;
}
}
}
}
// var_dump("Records updated: " . $count);
// var_dump("Total Records: " . count($getFlag));
/********************fetch records where CSS is 0 or null or empty string********************************************/
$BIZ = "CSS";
$getFlag = formatIWRes(container('IWSRequest')->getFlag($BIZ))["data"];
// var_dump($getFlag);
// die();
//check records where CSS is 0 or null or empty string and update accordingly
$count = 0;
foreach($getFlag as $flag)
{
if(isset($flag["SECID"]) && !is_null($flag["SECID"]) && !empty($flag["SECID"]) && $flag["SECID"] != "")
{
$BIZID = $flag["SECID"];
$INVOLVEMENT = STOCKBROKING_INVOLVEMENT;
$DB = STOCKBROKING_DB_NAME;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) == "TRUE")
{
//update business flag to 1
$customerInfo = $this->getCustomerDetails($flag['CustID']);
if($customerInfo[$BIZ] === "0" || $customerInfo[$BIZ] === "" || $customerInfo[$BIZ] === null){
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag["CustID"], $BIZ));
$count = $count + 1;
}
}
}
}
// var_dump("Records updated: " . $count);
// die();
/********************fetch records where TROVE is 0 or null or empty string********************************************/
$BIZ = "TROVE";
$getFlag = formatIWRes(container('IWSRequest')->getFlag($BIZ))["data"];
//check records where CSS is 0 or null or empty string and update accordingly
foreach($getFlag as $flag)
{
if(isset($flag["SECID"]) && !is_null($flag["SECID"]) && !empty($flag["SECID"]) && $flag["SECID"] != "")
{
$BIZID = $flag["SECID"];
$INVOLVEMENT = TROVE_INVOLVEMENT;
$DB = STOCKBROKING_DB_NAME;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) == "TRUE")
{
//update business flag to 1
$customerInfo = $this->getCustomerDetails($flag['CustID']);
if($customerInfo[$BIZ] === "0" || $customerInfo[$BIZ] === "" || $customerInfo[$BIZ] === null){
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag["CustID"], $BIZ));
$count = $count + 1;
}
}
}
}
/********************fetch records where CAM is 0 or null or empty string********************************************/
$BIZ = "CAM1";
$getFlag = formatIWRes(container('IWSRequest')->getFlag($BIZ))["data"];
//check records where CSS is 0 or null or empty string and update accordingly
foreach($getFlag as $flag)
{
if(isset($flag["CAMID"]) && !is_null($flag["CAMID"]) && !empty($flag["CAMID"]) && $flag["CAMID"] != "")
{
// $BIZID = $flag["CAMID"];
// $INVOLVEMENT = FI_INVOLVEMENT;
// $DB = CAM_DB_NAME;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
// if(strtoupper($verify["data"]) == "TRUE")
// {
//update business flag to 1
// $BIZ = "CAM1";
// $updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag[CustID], $BIZ));
// }
if(strtoupper($verify["data"]) == "TRUE")
{
//update business flag to 1
$customerInfo = $this->getCustomerDetails($flag['CustID']);
if($customerInfo[$BIZ] != 1){
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag["CustID"], $BIZ));
$count = $count + 1;
}
}
}
}
/********************fetch records where SMA is 0 or null or empty string********************************************/
$BIZ = "SMA";
$getFlag = formatIWRes(container('IWSRequest')->getFlag($BIZ))["data"];
//check records where CSS is 0 or null or empty string and update accordingly
foreach($getFlag as $flag)
{
if(isset($flag["CAMID"]) && !is_null($flag["CAMID"]) && !empty($flag["CAMID"]) && $flag["CAMID"] != "")
{
$BIZID = $flag["CAMID"];
$INVOLVEMENT = SMA_INVOLVEMENT;
$DB = CAM_DB_NAME;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) == "TRUE")
{
//update business flag to 1
$customerInfo = $this->getCustomerDetails($flag['CustID']);
if($customerInfo[$BIZ] === "0" || $customerInfo[$BIZ] === "" || $customerInfo[$BIZ] === null){
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag["CustID"], $BIZ));
$count = $count + 1;
}
}
}
}
/********************fetch records where MF is 0 or null or empty string********************************************/
$BIZ = "MF";
$getFlag = formatIWRes(container('IWSRequest')->getFlag($BIZ))["data"];
//check records where CSS is 0 or null or empty string and update accordingly
foreach($getFlag as $flag)
{
if(isset($flag["CAMID"]) && !is_null($flag["CAMID"]) && !empty($flag["CAMID"]) && $flag["CAMID"] != "")
{
$BIZID = $flag["CAMID"];
$INVOLVEMENT = MF_INVOLVEMENT;
$DB = CAM_DB_NAME;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) == "TRUE")
{
//update business flag to 1
$customerInfo = $this->getCustomerDetails($flag['CustID']);
if($customerInfo[$BIZ] === "0" || $customerInfo[$BIZ] === "" || $customerInfo[$BIZ] === null){
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag["CustID"], $BIZ));
$count = $count + 1;
}
}
}
}
/********************fetch records where CSP is 0 or null or empty string********************************************/
$BIZ = "CSP";
$getFlag = formatIWRes(container('IWSRequest')->getFlag($BIZ))["data"];
//check records where CSS is 0 or null or empty string and update accordingly
foreach($getFlag as $flag)
{
if(isset($flag["ASSETID"]) && !is_null($flag["ASSETID"]) && !empty($flag["ASSETID"]) && $flag["ASSETID"] != "")
{
// $BIZID = $flag["ASSETID"];
// $INVOLVEMENT = FI_INVOLVEMENT;
// $DB = ASSETMGMT_DB_NAME;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
// if(strtoupper($verify["data"]) == "TRUE")
// {
//update business flag to 1
// $updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag[CustID], $BIZ));
// }
if(strtoupper($verify["data"]) == "TRUE")
{
//update business flag to 1
$customerInfo = $this->getCustomerDetails($flag['CustID']);
if($customerInfo[$BIZ] === "0" || $customerInfo[$BIZ] === "" || $customerInfo[$BIZ] === null){
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag["CustID"], $BIZ));
$count = $count + 1;
}
}
}
}
/********************fetch records where CSS is 0 or null or empty string********************************************
$BIZ = "CSRL";
$getFlag = formatIWRes(container('IWSRequest')->getFlag($BIZ))["data"];
//check records where CSS is 0 or null or empty string and update accordingly
foreach($getFlag as $flag)
{
if(isset($flag["SECID"]) && !is_null($flag["SECID"]) && !empty($flag["SECID"]) && $flag["SECID"] != "")
{
$BIZID = $flag["SECID"];
$INVOLVEMENT = STOCKBROKING_INVOLVEMENT;
$DB = STOCKBROKING_DB_NAME;
$verify = $this->verifyProductInvolvement($BIZID, $INVOLVEMENT, $DB);
if(strtoupper($verify["data"]) == "TRUE")
{
//update business flag to 1
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($flag[CustID], $BIZ));
}
}
}
/*************************************************************************************************************************/
return["code"=> 200, "message" => "Business Flags Successfully Updated"];
}
public function checkNameExist($payload)
{
$data = $this->stockRecommendationTable()->where([["company","=",$payload["company"]]])->get();
$data = json_decode(json_encode($data),true);
if($data){
return $data;
}
}
public function getStockRecommendation()
{
$data = $this->stockRecommendationTable()->get();
$data = json_decode(json_encode($data),true);
return["code"=> 200, "message" => "Stock Recommendations Successfully Fetched", "data" =>$data ?? []];
}
public function stockRecommendation($payload)
{
if(strtolower($payload["category"]) == "add")
{
$data = $this->stockRecommendationTable()
->insertGetId([
'company' => $payload['company'],
'recommendation' => $payload['recommendation'],
'targetPrice' => $payload['targetPrice'],
'dividendYield' => $payload['dividendYield'],
'pCapital' => $payload['pCapital'],
'aReturnOnEquity' => $payload['aReturnOnEquity'],
]);
return["code"=> 200, "message" => "Stock Recommendations Successfully Added"];
}
elseif(strtolower($payload["category"]) == "edit")
{
$data = $this->stockRecommendationTable()
->where('id', $payload['id'])
->update([
'company' => $payload['company'],
'recommendation' => $payload['recommendation'],
'targetPrice' => $payload['targetPrice'],
'dividendYield' => $payload['dividendYield'],
'pCapital' => $payload['pCapital'],
'aReturnOnEquity' => $payload['aReturnOnEquity'],
]);
return["code"=> 200, "message" => "Stock Recommendations Successfully Editted"];
}
elseif(strtolower($payload["category"]) == "remove")
{
$data = $this->stockRecommendationTable()->where([["id","=",$payload["id"]]])->delete();
// $data = json_decode(json_encode($data),true);
return["code"=> 200, "message" => "Stock Recommendation Successfully Deleted"];
}
}
public function getInvestmentNotification()
{
$data = $this->investmentNotificationTable()->where([["type","=", "investment"]])->get();
$data = json_decode(json_encode($data),true);
return["code"=> 200, "message" => "Investment Notifications Successfully Fetched", "data" =>$data ?? []];
}
public function investmentNotification($payload)
{
if(strtolower($payload["category"]) == "add")
{
//upload notification to server
$transactionID = "";
$directory = dirname(__DIR__, 2) . "/public_view/files/notification/";
foreach($payload['files'] as $file)
{
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
// $filename = $this->moveUploadedFile_valuation($transactionID, $directory, $uploadedFile);
$filename = $this->moveUploadedFile($directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
$extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
$report= env('IMAGE_URL')."notification/{$filename}";
}
$data = $this->investmentNotificationTable()
->insertGetId([
'title' => $payload['title'],
'type' => "investment",
'details' => $report,
'admin' => $payload['admin'],
]);
return["code"=> 200, "message" => "Investment Notifications Successfully Added"];
}
elseif(strtolower($payload["category"]) == "remove")
{
$data = $this->investmentNotificationTable()->where([["id","=",$payload["id"]]])->delete();
// $data = json_decode(json_encode($data),true);
return["code"=> 200, "message" => "Investment Notification Successfully Deleted"];
}
}
public function dailyWalletSpent($payload)
{
$dailySpent = $this->walletLimitTable()
->where([
['CustID', $payload['CustID']],
//['createDate','like','%' . $payload['transactionDate'] . '%']
['createDate','like', Carbon::now()->format('Y-m-d') . '%']
])
->get('amount');
for ($i = 0 ; $i < count($dailySpent); $i++)
{
$spent = $spent + $dailySpent[$i]->amount;
}
$dailyBalance = (WALLET_DAILY_LIMIT *1) - $spent;
$dailyBalance = ($dailyBalance >= 0 ) ? $dailyBalance : 0;
return ["dailyLimit" => (WALLET_DAILY_LIMIT *1), "dailyBalance" => $dailyBalance ?? 0];
}
public function createDailyWalletSpent($payload)
{
$dailySpent = $this->walletLimitTable()
->insertGetId([
'CustID' => $payload['CustID'],
'fullName' => str_replace(",","",$payload['fullName']),
'amount' => $payload['transactionAmount'],
]);
return;
}
public function debitBalance($payload)
{
//to return client cash balance as at now
// $marginBalance = $this->getTotalCashBalanceByLedgerType($client)['margin'];
// $date = Carbon::now()->format('Y-m-d');
$date = (isset($payload["date"]) && !is_null($payload["date"]) && !empty($payload["date"]) && $payload["date"] != "") ? $payload["date"] : Carbon::now()->format('Y-m-d');
//to return client cash balance (excluding stock purchase transactions) where value date is equal to today
$debitBalance_ = formatIWRes(container('IWSRequest')->PGetData2('csp_0036', "{$date}|{$payload['SECID']}|" . STOCKBROKING_MARGIN_ACC_ID . "|NGN", STOCKBROKING_DB_NAME))['data'] ?? [];
$debitBalance = array_sum(array_column($debitBalance_, 'Balance')) ?? 0;
/************ fetch stock purchase records from T-3 ***********************/
$date_check_ = date_create($date);
// $date_check = date_format(date_sub($date_check_, date_interval_create_from_date_string("1 days")), "Y-m-d");
//check if $date_check is not weekend and not holiday to get trade 3 business days before reference date
$ik = $j = 0;
while ($j < 3) {
// var_dump($j);
$date_check = date_format(date_sub($date_check_, date_interval_create_from_date_string("1 days")), "Y-m-d");
if((container('customerModel')->checkIfHoliday($date_check) == false) && (container('customerModel')->checkIfWeekend_2($date_check) == false))
{
// var_dump($date_check);
$j = $j + 1;
}
$ik = $ik + 1;
/* $date_check = Carbon::now()->subDays($ik)->format('Y-m-d'); */
}
/* while((container('customerModel')->checkIfHoliday($date_check) == true) || (container('customerModel')->checkIfWeekend_2($date_check) == true))
{
$ik = $ik + 1;
$date_check = Carbon::now()->subDays($ik)->format('Y-m-d');
} */
//to return client cash balance (excluding stock purchase transactions) where value date is equal to today
$debitStockBalance_ = formatIWRes(container('IWSRequest')->PGetData2('csp_0037', "{$date_check}|{$payload['SECID']}|" . STOCKBROKING_MARGIN_ACC_ID . "|NGN", STOCKBROKING_DB_NAME))['data'] ?? [];
$debitStockBalance = array_sum(array_column($debitStockBalance_, 'Debit')) ?? 0;
//get margin balance
$marginBalance = $debitBalance + $debitStockBalance;
return ["code"=>200, "debitBalance_"=>$debitBalance_, "debitBalance"=>$debitBalance, "date_check"=>$date_check, "debitStockBalance_"=>$debitStockBalance_, "debitStockBalance"=>$debitStockBalance, "marginBalance"=>$marginBalance];
}
public function verifyBusinessCode($payload)
{
$value = $payload["company"];
$decoded_data = formatIWRes(container('IWSRequest')->getUserDetailsFromMiddleware(MIDDLEWARE_DB_NAME, $payload['CustID']))['data'][0];
if($decoded_data["{$value}"] == 1)
{
return ["code"=>200, "message" => "User has ".$value." Involvement" , "data"=> true];
}else{
return ["code"=>200, "message" => "User does not have ".$value." Involvement", "data"=> false];
}
}
public function updateBizFlags($payload)
{
$updateFlag = formatIWRes(container('IWSRequest')->updateFlag($payload["CustID"], $payload['BIZ']));
if($updateFlag["StatusID"] == 0)
{
return ["code"=>200, "message" => "Business Flag Successfully Updated"];
}else{
return ["code"=>400, "message" => "Business Flag Update Failed"];
}
}
public function disableBizFlags($payload)
{
$updateFlag = formatIWRes(container('IWSRequest')->disableFlag($payload["CustID"], $payload['BIZ']));
if($updateFlag["StatusID"] == 0)
{
return ["code"=>200, "message" => "Business Flag Successfully Disabled"];
}else{
return ["code"=>400, "message" => "Business Flag Disabling Failed"];
}
}
public function deleteKYC($payload)
{
$kyc = $this->KYCTable()
->where([["id","=", $payload['ID']]])
->first();
if(count($kyc) > 0)
{
$message1 = "Client ID: " . $kyc->CustID;
$message2 = "Client Name: " . $kyc->firstName . ' ' . $kyc->lastName;
$message3 = "Client KYC has been deleted";
$message4 = "Client kyc record deleted by " .$payload['userName'];
$message5 = "Local DB record update";
$this->KYCTable()
->where([["id","=", $payload['ID']]])
->delete();
container('mutualFundModel')->activity_log($message1,$message2,$message3,$message4,$message5);
return ['code' => 200, 'message' => 'KYC successfully deleted.'];
}
return ['code' => 404, 'message' => 'KYC not found.'];
}
public function findCRMID($payload)
{
$this->customerData['UserID'] = $payload['CustID'];
$customerId = $payload['CustID'];
//fetch additional information
$customers = formatIWRes(container('IWSRequest')->PGetData2('CP_0004', $customerId, MIDDLEWARE_DB_NAME))['data'];
return $this->customerData['CRMID'] = $customers[0]['CRM ID'];
}
public function updateCRMID($payload)
{
$updateCRMID = formatIWRes(container('IWSRequest')->updateCRMID($payload["CustID"], $payload['CRMID']));
if($updateCRMID["StatusID"] == 0)
{
return [
"message" => "CRM ID updated successfully",
"CustID" => $payload['CustID'],
"code" => 200
];
}else{
return ["code"=>400, "message" => "CRM ID Update Failed"];
}
}
public function fetchModifiedData()
{
$data = formatIWRes(container('IWSRequest')->retrieveModifiedContentData());
return $data;
}
public function investmentMaturity()
{
/* return (row[3] == "MASS_AFF" && (row[16] == "" || row[16].toUpperCase() == "NO") && row[6]
!= "[email protected]" && row[14] != "GBP" && row[15] != "BOND INVESTMENTS (SMA)" && row[15]
!= "FIXED INCOME INVESTMENT NOTE (CAM-SMA)" && (row[15].search("SMA") < 0 || row[15].search("SMA") == -1
|| row[15].search("SMA") == "-1") && row[22] != "CAM722" && row[22] != "521" && maturityDateMonthFromTheArr == repMonthNo_
&& getmaturityYearFromgetmaturityMonthToArr == repYear)
*/
$repDate = Carbon::now()->addDays(14)->format('Y-m-d');
$date = date_create($repDate);
$repDate_month_year = date_format($date, "F") . " " .date_format($date, "Y");
$repDate_day_month_year = date_format($date, "F") . " " .date_format($date, "j") . ", " .date_format($date, "Y");
$investmentMaturity = formatIWRes(container('IWSRequest')->investmentMaturity($repDate));
if($investmentMaturity["StatusID"] == 0 && !is_null($investmentMaturity["data"]) && count($investmentMaturity["data"]) > 0)
{
foreach($investmentMaturity["data"] as $data)
{
$clientInvestmentMaturityNGN = formatIWRes(container('IWSRequest')->clientInvestmentMaturity($data["CUSTOMER ID"], $repDate, "NGN"));
$clientInvestmentMaturityUSD = formatIWRes(container('IWSRequest')->clientInvestmentMaturity($data["CUSTOMER ID"], $repDate, "USD"));
$clientInvestmentMaturityGBP = formatIWRes(container('IWSRequest')->clientInvestmentMaturity($data["CUSTOMER ID"], $repDate, "GBP"));
//send email notificaiton
$result = [
"clientInvestmentMaturityNGN" => $clientInvestmentMaturityNGN["data"],
"clientInvestmentMaturityUSD" => $clientInvestmentMaturityUSD["data"],
"clientInvestmentMaturityGBP" => $clientInvestmentMaturityGBP["data"],
"NGN" => count($clientInvestmentMaturityNGN["data"]),
"USD" => count($clientInvestmentMaturityUSD["data"]),
"GBP" => count($clientInvestmentMaturityGBP["data"]),
"fullName" => $data["CUSTOMER NAME"],
"repDate_day_month_year" => $repDate_day_month_year,
"repDate_month_year" => $repDate_month_year,
];
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
// ->to("[email protected]")
->bcc("[email protected]")
->bcc("[email protected]")
// ->bcc("[email protected]")
->from("[email protected]", 'CardinalStone')
->subject("UPCOMING INVESTMENT MATURITY ✔✔")
->usingView('investment_maturity_notification', $result)
// ->usingView('csrl_welcome_email_template', $result)
->send();
}else{
(new Mailer())
->to($data["EMAIL ADDRESS"])
// ->to("[email protected]")
->bcc("[email protected]")
->bcc("[email protected]")
// ->bcc("[email protected]")
->from("[email protected]", 'CardinalStone')
->subject("UPCOMING INVESTMENT MATURITY ✔✔")
->usingView('investment_maturity_notification', $result)
// ->usingView('csrl_welcome_email_template', $result)
->send();
}
// return ["code"=>200, "data" => $investmentMaturity["data"], "NGN" => count($clientInvestmentMaturityNGN["data"]), "USD" => count($clientInvestmentMaturityUSD["data"]), "GBP" => count($clientInvestmentMaturityGBP["data"])];
// return ["code"=>200, $clientInvestmentMaturity];
}
return ["code"=>200, "message" => "Maturity Notification(s) Sent"];
}else{
return ["code"=>200, "message" => "No Maturity Notification"];
// return ["code"=>200, $investmentMaturity];
}
}
public function zenithTransfer____($payload)
{
//upfload instruction file
$directory = dirname(__DIR__, 2) . "/public_view/files/zenith/";
$i = 0;
foreach($payload['files'] as $file)
{
$i = $i + 1;
$name = "EFTrequest-" . Carbon::now()->format('Y-m-d') . "-" . mt_rand(100, 999999);
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile_zenith($name, $directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
// $payload["path"] = $directory;
$payload["path"] = dirname(__DIR__, 2) . "/public_view/files/zenith/";
$payload["filename"] = $filename;
}
$zenithTransfer = container('IWSRequest')->zenithTransfer($payload);
return ["code"=>200,"message" => "Zenith transfer instruction successfully sent", "data" => $zenithTransfer];
}
public function zenithBuyInstrument____($payload)
{
//upfload instruction file
$directory = dirname(__DIR__, 2) . "/public_view/files/zenith/";
$i = 0;
foreach($payload['files'] as $file)
{
$i = $i + 1;
$name = "BUYrequest-" . Carbon::now()->format('Y-m-d') . "-" . mt_rand(100, 999999);
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile_zenith($name, $directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
// $payload["path"] = $directory;
$payload["path"] = dirname(__DIR__, 2) . "/public_view/files/zenith/";
$payload["filename"] = $filename;
}
$zenithBuyInstrument = container('IWSRequest')->zenithBuyInstrument($payload);
return ["code"=>200,"message" => "Zenith buy instruction successfully sent", "data" => $zenithBuyInstrument];
}
public function zenithSellInstrument____($payload)
{
//upfload instruction file
$directory = dirname(__DIR__, 2) . "/public_view/files/zenith/";
$i = 0;
foreach($payload['files'] as $file)
{
$i = $i + 1;
$name = "SELLrequest-" . Carbon::now()->format('Y-m-d') . "-" . mt_rand(100, 999999);
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile_zenith($name, $directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
// $payload["path"] = $directory;
$payload["path"] = dirname(__DIR__, 2) . "/public_view/files/zenith/";
$payload["filename"] = $filename;
}
$zenithSellInstrument = container('IWSRequest')->zenithSellInstrument($payload);
return ["code"=>200,"message" => "Zenith sell instruction successfully sent", "data" => $zenithSellInstrument];
}
public function zenithEncrypt____($payload)
{
$zenithEncrypt = container('IWSRequest')->zenithEncrypt($payload);
return ["code"=>200,"message" => "Zenith data successfully encrypted", "data" => $zenithEncrypt];
}
public function zenithDecrypt____($payload)
{
$zenithDecrypt = container('IWSRequest')->zenithDecrypt($payload);
return ["code"=>200,"message" => "Zenith data successfully decrypted", "data" => $zenithDecrypt];
}
public function zenithResetAPI____($payload)
{
$zenithResetAPI = container('IWSRequest')->zenithResetAPI($payload);
return ["code"=>200,"message" => "Zenith API successfully reset", "data" => $zenithResetAPI];
}
public function investmentTypes()
{
$investmentTypes = formatIWRes(container('IWSRequest')->investmentTypes()) ?? [];
return ["code"=>200,"message" => "Investment types successfully fetched", "data" => $investmentTypes];
}
public function fetchInstrumentTypes($payload)
{
$fetchInstrumentTypes = formatIWRes(container('IWSRequest')->fetchInstrumentTypes($payload)) ?? [];
return ["code"=>200,"message" => "Instrument types successfully fetched", "data" => $fetchInstrumentTypes];
}
public function IAPerformance($payload)
{
$IAPerformance = formatIWRes(container('IWSRequest')->IAPerformance($payload)) ?? [];
return ["code"=>200,"message" => "IA performance successfully fetched", "data" => $IAPerformance];
}
public function incomeStatement($payload)
{
$incomeStatement_ = formatIWRes(container('IWSRequest')->incomeStatement($payload))['data'] ?? [];
if(strtoupper($payload["businessInvolvement"]) == STOCKBROKING_DB_NAME)
{
$incomeStatement = $this->formatReport_css($incomeStatement_);
}else{
$incomeStatement = $this->formatReport_cam($incomeStatement_);
}
return ["code"=>200,"message" => "Income statement successfully fetched", "data" => $incomeStatement];
}
public function financialPosition($payload)
{
$financialPosition_ = formatIWRes(container('IWSRequest')->financialPosition($payload))['data'] ?? [];
if(strtoupper($payload["businessInvolvement"]) == STOCKBROKING_DB_NAME)
{
$financialPosition = $this->formatReport_css($financialPosition_);
}else{
$financialPosition = $this->formatReport_cam($financialPosition_);
}
return ["code"=>200,"message" => "Financial postions successfully fetched", "data" => $financialPosition];
}
public function accountsOpened($payload)
{
$accountsOpened = formatIWRes(container('IWSRequest')->accountsOpened($payload)) ?? [];
return ["code"=>200,"message" => "Accounts opened successfully fetched", "data" => $accountsOpened];
}
/* public function formatReport_css_($data)
{
// if (is_null($data)) return [];
if (count($data) === 0) return [];
$reports = $data;
// $customers = formatIWRes(container('IWSRequest')->PGetData('CP_0016', MIDDLEWARE_DB_NAME))['data'];
// var_dump($customers);
// $customers = array_map(function ($customer) {
// return array_merge($customer, [
// 'customerId' => $customer['CustAID'],
// 'assetMgmtID' => $customer['CSPCustAID'],
// 'stockbrokingID' => $customer['CSSCustAID'],
// 'CAMCustomerId' => $customer['CAMCustAID '] ?? null,
// ]);
// }, $customers);
// $customers = array_values($customers);
$reports = array_map(function ($report) {
return array_merge($report, [
'cMonth' => isset($report['PeriodAmount']) ? number_format($report['PeriodAmount'], 3) : null,
'actualYTD' => isset($report['YrToDateAmount']) ? number_format($report['YrToDateAmount'], 3) : null,
]);
}, $reports);
// var_dump($reports);
// die();
// $reports = ->groupBy(function ($report) {
// return !strpos($report['NOTES'], '.') ||
// $report['FinstatGroupName'] === 'Total Operating Expenses' ||
// $report['FinstatGroupName'] === 'Profit AfterTaxation' ||
// $report['FinstatGroupName'] === 'Profit Before Taxation';
// });
$firstReport = $reports->first()->toArray()[0];
if (strpos($firstReport['NOTES'], '.') !== false) {
$reports = $reports->reverse()->values();
}
$data['data'] = $reports->first()->groupBy('NOTES')->toArray();
$data['nestedData'] = $reports
->last()
->filter(function ($report) {
return strpos(strtolower($report['FinstatGroupName']), strtolower('Profit')) >= 0;
})
->groupBy(function ($report) {
return explode('.', $report['NOTES'])[0];
})
->toArray();
return $data;
} */
public function formatReport_css($data_)
{
if (count($data_) === 0) return [];
$reports = collect($data_)
->map(function ($report) {
return array_merge($report, [
'cMonth' => isset($report['PeriodAmount']) ? number_format($report['PeriodAmount'], 3) : null,
'actualYTD' => isset($report['YrToDateAmount']) ? number_format($report['YrToDateAmount'], 3) : null,
]);
})
->groupBy(function ($report) {
return !strpos($report['NOTES'], '.') ||
$report['FinstatGroupName'] === 'Total Operating Expenses' ||
$report['FinstatGroupName'] === 'Profit AfterTaxation' ||
$report['FinstatGroupName'] === 'Profit Before Taxation';
});
$firstReport = $reports->first()->toArray()[0];
if (strpos($firstReport['NOTES'], '.') !== false) {
$reports = $reports->reverse()->values();
}
$data['data'] = $reports->first()->groupBy('NOTES')->toArray();
$data['nestedData'] = $reports
->last()
->filter(function ($report) {
return strpos(strtolower($report['FinstatGroupName']), strtolower('Profit')) >= 0;
})
->groupBy(function ($report) {
return explode('.', $report['NOTES'])[0];
})
->toArray();
return $data;
}
public function formatReport_cam($data_)
{
// if (is_null($data)) return [];
if (count($data_) === 0) return [];
$reports = collect($data_)
->map(function ($report) {
return array_merge($report, [
'cMonth' => isset($report['PeriodAmount']) ? number_format($report['PeriodAmount'], 3) : null,
'actualYTD' => isset($report['YrToDateAmount']) ? number_format($report['YrToDateAmount'], 3) : null,
]);
})
->groupBy(function ($report) {
return !strpos($report['NOTES'], '.') ||
$report['FinstatGroupName'] === 'Total Operating Expenses' ||
$report['FinstatGroupName'] === 'Profit Before PPI' ||
$report['FinstatGroupName'] === 'Profit AfterTaxation' ||
$report['FinstatGroupName'] === 'Profit Before Taxation';
});
$firstReport = $reports->first()->toArray()[0];
if (strpos($firstReport['NOTES'], '.') !== false) {
$reports = $reports->reverse()->values();
}
$data['data'] = $reports->first()->groupBy('NOTES')->toArray();
$data['nestedData'] = $reports
->last()
->filter(function ($report) {
return strpos(strtolower($report['FinstatGroupName']), strtolower('Profit')) >= 0;
})->groupBy(function ($report) {
return explode('.', $report['NOTES'])[0];
})
->toArray();
return $data;
}
public function totalAccountsOpened($payload)
{
$totalAccountsOpened = formatIWRes(container('IWSRequest')->totalAccountsOpened($payload)) ?? [];
return ["code"=>200,"message" => "Total accounts opened successfully fetched", "data" => $totalAccountsOpened];
}
public function IOPerCategory($payload)
{
$IOPerCategory = formatIWRes(container('IWSRequest')->IOPerCategory($payload)) ?? [];
return ["code"=>200, "message" => "Inflow/Outflow per category successfully fetched", "data" => $IOPerCategory];
}
public function IOPerIA($payload)
{
$IOPerIA = formatIWRes(container('IWSRequest')->IOPerIA($payload)) ?? [];
return ["code"=>200, "message" => "Inflow/Outflow per IA successfully fetched", "data" => $IOPerIA];
}
public function createGlobalBudget($payload)
{
$createGlobalBudget = $this->globalBudgetTable()
->insertGetId([
'budget' => $payload['budget'],
'year' => $payload['year'],
'admin' => $payload['admin'],
'HNILAGOS' => $payload['HNILAGOS'],
'HNIABUJA' => $payload['HNIABUJA'],
'MASSLAGOS' => $payload['MASSLAGOS'],
'MASSABUJA' => $payload['MASSABUJA'],
]);
return ["code"=>200, "message" => "Global budget successfully created"];
}
public function editGlobalBudget($payload)
{
$editGlobalBudget = $this->globalBudgetTable()
->where([["ID", "=", $payload['ID']]])
->update([
'budget' => $payload['budget'],
'year' => $payload['year'],
'admin' => $payload['admin'],
'HNILAGOS' => $payload['HNILAGOS'],
'HNIABUJA' => $payload['HNIABUJA'],
'MASSLAGOS' => $payload['MASSLAGOS'],
'MASSABUJA' => $payload['MASSABUJA'],
]);
return ["code"=>200, "message" => "Global budget successfully editted"];
}
public function fetchGlobalBudgets($payload)
{
$fetchGlobalBudgets = $this->globalBudgetTable()->get();
return ["code"=>200, "message" => "Global budgets successfully fetched", "data" => $fetchGlobalBudgets];
}
public function createMonthlyBudget($payload)
{
$createMonthlyBudget = $this->monthlyBudgetTable()
->insertGetId([
'annual_budget' => $payload['annual_budget'],
'monthly_budget' => $payload['monthly_budget'],
'team' => $payload['team'],
'month' => $payload['month'],
'year' => $payload['year'],
'admin' => $payload['admin'],
]);
return ["code"=>200, "message" => "Monthly budget successfully created"];
}
public function editMonthlyBudget($payload)
{
$editMonthlyBudget = $this->monthlyBudgetTable()
->where([["ID", "=", $payload['ID']]])
->update([
'annual_budget' => $payload['annual_budget'],
'monthly_budget' => $payload['monthly_budget'],
'team' => $payload['team'],
'month' => $payload['month'],
'year' => $payload['year'],
'admin' => $payload['admin'],
]);
return ["code"=>200, "message" => "Monthly budget successfully editted"];
}
public function fetchMonthlyBudgets($payload)
{
$fetchMonthlyBudgets = $this->monthlyBudgetTable()
->where([["month", "=", $payload['month']],
["year", "=", $payload['year']],
])
->get();
return ["code"=>200, "message" => "Monthly budgets successfully fetched", "data" => $fetchMonthlyBudgets];
}
public function createIABudget($payload)
{
$createIABudget = $this->IAMonthlyBudgetTable()
->insertGetId([
'ia' => $payload['IA'],
'monthly_budget' => $payload['monthly_budget'],
'team' => $payload['team'],
'month' => $payload['month'],
'year' => $payload['year'],
'admin' => $payload['admin'],
]);
return ["code"=>200, "message" => "IA Monthly budget successfully created"];
}
public function editIABudget($payload)
{
$editIABudget = $this->IAMonthlyBudgetTable()
->where([["ID", "=", $payload['ID']]])
->update([
'ia' => $payload['IA'],
'monthly_budget' => $payload['monthly_budget'],
'team' => $payload['team'],
'month' => $payload['month'],
'year' => $payload['year'],
'admin' => $payload['admin'],
]);
return ["code"=>200, "message" => "IA Monthly budget successfully editted"];
}
public function fetchIABudgets($payload)
{
$fetchIABudgets = $this->IAMonthlyBudgetTable()
->where([["month", "=", $payload['month']],
["year", "=", $payload['year']],
["team", "=", $payload['team']],
])
->get();
return ["code"=>200, "message" => "IA Monthly budgets successfully fetched", "data" => $fetchIABudgets];
}
public function IAFetch($payload)
{
$IAFetch = formatIWRes(container('IWSRequest')->IAFetch($payload))['data'] ?? [];
return $IAFetch;
}
public function fetchIAGroup()
{
$fetchIAGroup = formatIWRes(container('IWSRequest')->fetchIAGroup())['data'] ?? [];
return $fetchIAGroup;
}
public function IAUpdate($payload)
{
$result = formatIWRes(container('IWSRequest')->IAUpdate($payload['involvementType'],$payload['CustID'],$payload['IA'],$payload['IAID']))['data'];
//log ixtrac response
$message1 = "Client ID: " . $payload['CustID'];
$message2 = "Client Name: " . $payload['client'];
$message3 = "Client ". $payload['client'] ."'s IA is now " . $payload['IA'] . "-" . $payload['IAID'];
$message4 = "Client IA updated by " .$payload['userName'];
$message5 = "Infoware Client IA record update";
//$log = $this->mutualFundModel->activity_log("ACCOUNTNUMBER: " . $payload['accountNumber'], "Register ID: " . $payload['REGISTER_ID'] , $payload['lastName'] . " " . $payload['firstName'], "iXtrac Records updated by " .$payload['UserName'], "iXtrac KYC Update");
$log = $this->mutualFundModel->activity_log($message1,$message2,$message3,$message4,$message5);
return ;
}
public function STBDebitAccounts()
{
$STBDebitAccounts = formatIWRes(container('IWSRequest')->STBDebitAccounts())["data"] ?? [];
return ["code"=>200, "message" => "STB accounts in debit successfully fetched", "data" => $STBDebitAccounts];
}
public function createCP($payload)
{
// date_format($today,"Y-m-d");
$sdate = date_create($payload['startDate']);
$sdate = date_format($sdate,"Y-m-d H:i:s");
$bdate = date_create($payload['bookByDate']);
$bdate = date_format($bdate,"Y-m-d H:i:s");
$mdate = date_create($payload['maturityDate']);
$mdate = date_format($mdate,"Y-m-d H:i:s");
$rates = $this->cpTable()
->insertGetId([
'product' => $payload['product'],
'tenure' => $payload['tenure'],
'price' => $payload['price'],
'rate' => $payload['rate'],
'yield' => $payload['yield'],
'charges' => $payload['charges'],
'startDate' => $sdate,
'maturityDate' => $mdate,
'bookByDate' => $bdate,
'instrumentType' => $payload['instrumentType'],
'admin' => $payload['admin'],
'ipAddress' => $this->get_client_ip(),
]);
return ['code' => 200, 'message' => $payload['product']. ' successfully created.'];
}
public function editCP($payload)
{
$this->cpTable()
->where([["id","=", $payload['ID']]])
->update([
'price' => $payload['price'],
'rate' => $payload['rate'],
'yield' => $payload['yield'],
'admin' => $payload['admin'],
"ipAddress" => $this->get_client_ip(),
"comment" => "Post book date cost updated by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Commercial paper cost and rate successfully updated.'];
}
public function editCPClientRequest($payload)
{
$this->CAMDealTable()
->where([["id","=", $payload['ID']]])
->update([
'price' => $payload['price'],
'amount' => $payload['amount'],
'rate' => $payload['rate'],
// 'admin' => $payload['admin'],
"ipAddress" => $this->get_client_ip(),
"comment" => "Post book date cost updated by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Client commercial paper request successfully updated.'];
}
public function enableCP($payload)
{
$this->cpTable()
->where([["id","=", $payload['ID']]])
->update([
'status' => 1,
"ipAddress" => $this->get_client_ip(),
"comment" => "Instrument enabled by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Commercial paper successfully enabled.'];
}
public function disableCP($payload)
{
$this->cpTable()
->where([["id","=", $payload['ID']]])
->update([
'status' => 0,
"ipAddress" => $this->get_client_ip(),
"comment" => "Instrument disabled by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Commercial paper successfully disabled.'];
}
public function fetchCP($payload)
{
$now_1 = date('Y-m-d');
$now = date('Y-m-d H:i:s');
$cp = $this->cpTable()
->where([
// ["bookByDate","like", $now_1 . '%'],
["status","=", 1],
])
// ->orWhere([
// ["bookByDate",">", $now],
// ["status","=", 1],
// ])
->get();
$cp = json_decode(json_encode($cp), true);
return ['code' => 200, 'message' => 'Commerical papers successfully fetched.', 'data' => $cp ?? []];
}
public function fetchAllCP($payload)
{
$now = date('Y-m-d H:i:s');
$cp = $this->cpTable()
->get();
$cp = json_decode(json_encode($cp), true);
return ['code' => 200, 'message' => 'Commerical papers successfully fetched.', 'data' => $cp ?? []];
}
public function createInvestment($payload)
{
$rates = $this->CAMRateTable()
->insertGetId([
'product' => strtoupper($payload['product']),
'instrumentType' => strtoupper($payload['instrumentType']),
'investmentType' => strtoupper($payload['investmentType']),
'tenure' => $payload['tenure'],
'rate' => $payload['rate'],
'charge' => $payload['charge'],
'admin' => $payload['admin'],
'ipAddress' => $this->get_client_ip(),
]);
return ['code' => 200, 'message' => strtoupper($payload['product']). ' successfully created.'];
}
public function editInvestment($payload)
{
$this->CAMRateTable()
->where([["id","=", $payload['ID']]])
->update([
'product' => strtoupper($payload['product']),
'instrumentType' => strtoupper($payload['instrumentType']),
'investmentType' => strtoupper($payload['investmentType']),
'tenure' => $payload['tenure'],
'rate' => $payload['rate'],
'charge' => $payload['charge'],
// 'admin' => $payload['admin'],
'ipAddress' => $this->get_client_ip(),
"comment" => "Fixed income updated by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => strtoupper($payload['product']). ' successfully updated.'];
}
public function deleteInvestment($payload)
{
$this->CAMRateTable()
->where([["id","=", $payload['ID']]])
->delete();
return ['code' => 200, 'message' => 'Investment product successfully deleted.'];
}
public function fetchInvestment($payload)
{
$cp = $this->CAMRateTable()
->where([
["investmentType","=", strtoupper($payload['investmentType']),],
])
->get();
$cp = json_decode(json_encode($cp), true);
return ['code' => 200, 'message' => 'Investment products successfully fetched.', 'data' => $cp ?? []];
}
public function createFixedIncome($payload)
{
$rates = $this->CAMRateTable()
->insertGetId([
'product' => strtoupper($payload['product']),
'instrumentType' => strtoupper($payload['instrumentType']),
'investmentType' => "FIXED INCOME",
'tenure' => $payload['tenure'],
'rate' => $payload['rate'],
'charge' => $payload['charge'],
'admin' => $payload['admin'],
'ipAddress' => $this->get_client_ip(),
]);
return ['code' => 200, 'message' => strtoupper($payload['product']). ' successfully created.'];
}
public function editFixedIncome($payload)
{
$this->CAMRateTable()
->where([["id","=", $payload['ID']]])
->update([
'product' => strtoupper($payload['product']),
'instrumentType' => strtoupper($payload['instrumentType']),
'investmentType' => "FIXED INCOME",
'tenure' => $payload['tenure'],
'rate' => $payload['rate'],
'charge' => $payload['charge'],
// 'admin' => $payload['admin'],
'ipAddress' => $this->get_client_ip(),
"comment" => "Fixed income updated by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Fixed income successfully updated.'];
}
public function deleteFixedIncome($payload)
{
$this->CAMRateTable()
->where([["id","=", $payload['ID']]])
->delete();
return ['code' => 200, 'message' => 'Fixed income successfully deleted.'];
}
public function fetchFixedIncome($payload)
{
$cp = $this->CAMRateTable()
->where([
["investmentType","=", "FIXED INCOME"],
])
->get();
$cp = json_decode(json_encode($cp), true);
return ['code' => 200, 'message' => 'Fixed income successfully fetched.', 'data' => $cp ?? []];
}
public function createTbills($payload)
{
// date_format($today,"Y-m-d");
$sdate = date_create($payload['startDate']);
$sdate = date_format($sdate,"Y-m-d H:i:s");
$bdate = date_create($payload['bookByDate']);
$bdate = date_format($bdate,"Y-m-d H:i:s");
$mdate = date_create($payload['maturityDate']);
$mdate = date_format($mdate,"Y-m-d H:i:s");
$rates = $this->tbillsTable()
->insertGetId([
'product' => $payload['product'],
'tenure' => $payload['tenure'],
'price' => $payload['price'],
'rate' => $payload['rate'],
'yield' => $payload['yield'],
'charges' => $payload['charges'],
'startDate' => $sdate,
'maturityDate' => $mdate,
'bookByDate' => $bdate,
'instrumentType' => (strtoupper($payload['instrumentType']) == "DIRECT") ? T_BILLS_DIRECT : T_BILLS_CLIENT,
'description' => (strtoupper($payload['instrumentType']) == "DIRECT") ? "Investment in Nigerian Treasury Bills for clients who do not have up to standard investment amount." : "Investment in Nigerian Treasury Bills.",
'admin' => $payload['admin'],
'ipAddress' => $this->get_client_ip(),
]);
return ['code' => 200, 'message' => $payload['product']. ' successfully created.'];
}
public function editTbills($payload)
{
$this->tbillsTable()
->where([["id","=", $payload['ID']]])
->update([
'price' => $payload['price'],
'rate' => $payload['rate'],
'yield' => $payload['yield'],
'admin' => $payload['admin'],
"ipAddress" => $this->get_client_ip(),
"comment" => "Post book date cost updated by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Treasury bills cost and rate successfully updated.'];
}
public function editTbillsClientRequest($payload)
{
$this->CAMDealTable()
->where([["id","=", $payload['ID']]])
->update([
'price' => $payload['price'],
'rate' => $payload['rate'],
'amount' => $payload['amount'],
// 'admin' => $payload['admin'],
"ipAddress" => $this->get_client_ip(),
"comment" => "Post book date cost updated by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Client treasury bills request successfully updated.'];
}
public function enableTbills($payload)
{
$this->tbillsTable()
->where([["id","=", $payload['ID']]])
->update([
'status' => 1,
"ipAddress" => $this->get_client_ip(),
"comment" => "Instrument enabled by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Treasury bill successfully enabled.'];
}
public function updatePin($CustID, $hashedPin)
{
$this->transferPinTable()
->where([["CustID","=", $CustID]])
->update([
'transferPin' => $hashedPin,
]);
return ['code' => 200, 'message' => 'Transfer pin updated'];
}
public function disableTbills($payload)
{
$this->tbillsTable()
->where([["id","=", $payload['ID']]])
->update([
'status' => 0,
"ipAddress" => $this->get_client_ip(),
"comment" => "Instrument disabled by " . $payload['admin'] ,
]);
return ['code' => 200, 'message' => 'Treasury bill successfully disabled.'];
}
public function fetchTbills($payload)
{
$now_1 = date('Y-m-d');
$now = date('Y-m-d H:i:s');
$cp = $this->tbillsTable()
->where([
// ["bookByDate","like", $now_1 . '%'],
["status","=", 1],
])
// ->orWhere([
// ["bookByDate",">", $now],
// ["status","=", 1],
// ])
->get();
$cp = json_decode(json_encode($cp), true);
return ['code' => 200, 'message' => 'Commerical papers successfully fetched.', 'data' => $cp ?? []];
}
public function fetchAllTbills($payload)
{
$now = date('Y-m-d H:i:s');
$cp = $this->tbillsTable()
->get();
$cp = json_decode(json_encode($cp), true);
return ['code' => 200, 'message' => 'Commerical papers successfully fetched.', 'data' => $cp ?? []];
}
public function fetchAllFeedbacks()
{
$feedbacks = $this->feedbackTable()
->get();
$feedbacks = json_decode(json_encode($feedbacks), true);
return ['code' => 200, 'message' => 'Feedbacks successfully fetched.', 'data' => $feedbacks ?? []];
}
public function base64Decode($payload)
{
$imageData = $payload["image"];
$outputFile = dirname(__DIR__, 2) . "/public_view/files/base64/{$payload["outputFile"]}.jpeg" ;
/* encode & write data (binary) */
$ifp = fopen( $outputfile, "wb" );
fwrite( $ifp, base64_decode( $imageData ) );
fclose( $ifp );
$image = IMAGE_URL."base64/{$payload["outputFile"]}.jpeg";
/* return output filename */
return ['code' => 200, 'message' => 'Base64 image successfully decoded.', 'data' => $image ?? []];
}
public function qrCode($payload)
{
//upload report to server
$transactionID = $payload["CustID"];
$directory = dirname(__DIR__, 2) . "/public_view/files/qr/";
$i = 0;
foreach($payload['files'] as $file)
{
$i = $i + 1;
$uploadedFile = $file;
// $uploadedFile = $payload['files'];
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = $this->moveUploadedFile_valuation($transactionID, $directory, $uploadedFile);
error_log('uploaded ' . $filename );
}
$qr = IMAGE_URL."qr/" . $filename;
}
// $payload["count"] = $i;
// if(strtolower($payload["channel"]) == "cswallet")
// {
// (new Mailer())
// ->to($payload['emailAddress'])
// ->from(\getenv("NOREPLY_MAIL"), 'CardinalStone')
// ->subject("Valuation Statement Notification")
// ->usingView('valuation_report', $payload)
// ->send();
// }
return ["code" => 200, "message" => "QR image successfully stored", "data" => $qr];
}
public function contactUs($payload)
{
//send email notificaiton
$result = [
"fullName" => $payload["fullName"],
"message" => $payload["message"],
"emailAddress" => $payload["from"],
];
if(ENVIRONMENT === 'testing'){
(new Mailer())
->to(DEFAULT_EMAIL)
->from($payload["from"], $payload["fullName"])
->subject("CS Alpha Support Request - " . $payload["fullName"])
->usingView('contact_us', $result)
->send();
}else{
(new Mailer())
->to($payload["to"])
->from($payload["from"], $payload["fullName"])
->subject("CS Alpha Support Request - " . $payload["fullName"])
->usingView('contact_us', $result)
->send();
}
// return ["code"=>200, "message" => "Support request successfully sent", "from" => $payload["from"], "to" => $payload["to"], "message" => $payload["message"]];
return ["code"=>200, "message" => "Support request successfully sent"];
}
public function getPaystackKey($payload)
{
$data = $this->paystackKeyTable()
->where([
["business","=",$payload["business"]],
["server","=",$payload["server"]],
["keyType","=",$payload["keyType"]],
])
->get();
$data = json_decode(json_encode($data), true);
// return ["code"=>200, "message" => "Support request successfully sent", "from" => $payload["from"], "to" => $payload["to"], "message" => $payload["message"]];
return ["code"=>200, "message" => "Paystack key successfully fetched", "data" => $data ?? []];
}
public function randomCode()
{
//initiate password reset
$this->chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$this->length = 4;
$code = "";
$charArray = str_split($this->chars);
for ($i = 0; $i < $this->length; $i++) {
$index = array_rand($charArray);
$code .= $charArray[$index];
}
$code .= mt_rand(100, 999999);
return $code;
}
public function liquidatedTbills($payload){
$liquidatedTbills = formatIWRes(container('IWSRequest')->liquidatedTbills($payload))['data'];
return["code" => 200, "message" => "Liquidated T-Bills successfully fetched", "data" => $liquidatedTbills];
}
public function liquidatedFI($payload){
$liquidatedFI = formatIWRes(container('IWSRequest')->liquidatedFI($payload))['data'];
return["code" => 200, "message" => "Liquidated Fixed Income successfully fetched", "data" => $liquidatedFI];
}
public function forgotUsername($payload){
$username = formatIWRes(container('IWSRequest')->forgotUsername($payload))['data'];
return["code" => 200, "message" => "Usernames successfully fetched", "data" => $username];
}
public function pay_encrypt($payload, $password, $secret)
{
$payload = json_encode($payload);
$password = $password;
$secretKey = $secret;
$hash = hash_pbkdf2("sha1", $password, mb_convert_encoding($secretKey, 'UTF-16LE'), 1000, 32, true);
// var_dump($hash);
// var_dump(bin2hex($hash));
$key = substr($hash, 0, 64);
$iv = substr($hash, 0, 32);
$result = openssl_encrypt(iconv('UTF-8', 'UTF-16', $payload), 'aes-256-cbc', $key, 0, $iv);
// return $result;
return ["code"=> 200, "data" => $result];
}
public function pay_decrypt($payload, $secret, $password)
{
$payload = $payload;
$password = $password;
$secretKey = $secret;
$hash = hash_pbkdf2("sha1", $password, mb_convert_encoding($secretKey, 'UTF-16LE'), 1000, 32, true);
$key = substr($hash, 0, 64);
$iv = substr($hash, 0, 16);
$result = iconv('UTF-16', 'UTF-8', openssl_decrypt($payload, 'aes-256-cbc', $key, 0, $iv));
$result =json_decode($result);
$result =json_decode(json_encode($result), true);
if(is_null($result))
{
$hash = hash_pbkdf2("sha1", $password, mb_convert_encoding($secretKey, 'UTF-16LE'), 1000, 32);
$key = substr($hash, 0, 32);
$iv = substr($hash, 0, 16);
$result = openssl_decrypt($payload, 'aes-256-cbc', $key, 0, $iv);
$result =json_decode($result);
$result =json_decode(json_encode($result), true);
}
return ["code"=> 200, "data" => $result];
}
public function getTotalAmountWithdrawnToday($CustID){
$today = Carbon::now()->toDateString();
$totalAmount = $this->withdrawRequestTable()
->where('CustID', $CustID)
->whereDate('createdDate', $today)
->sum('amount');
return $totalAmount;
}
public function getClientWalletStatus_1($payload)
{
// $marginStatus = formatIWRes(container('IWSRequest')->getClientMarginStatus($payload))['data'];
$walletStatus = $this->nubanTable()
->where([
["product", "=", "CSWALLET" ],
["CustID", "=", $payload['CustID'] ],
["accountNumber", "!=", null ],
])->get();
$verify = formatIWRes(container('IWSRequest')->verifyProductInvolvement($payload['CAMID'] , "CSWALLET" , CAM_DB_NAME))['data'][0]['Response'];
if(count($walletStatus) > 0)
{
return [["walletExist" => $verify, "virtualAccountExist" => "True"]];
}else{
return [["walletExist" => $verify, "virtualAccountExist" => "False"]];
}
}
public function getPayoutDetails($payload)
{
$payoutDetails = $this->redemptionPayoutTable()
->where([
["batchID", "=", $payload['batchID']],
])->get();
return ["code" => 200,"message" => "Redemption Payout details Summary Fetched", "data" => $payoutDetails];
}
public function getTransferRecipient($payload)
{
$customer = $this->transferTable()
->where([
["product", "=", "CSWALLET" ],
["CustID", "=", $payload['CustID'] ],
])->get();
return $customer;
}
public function getDeviceDetails($payload)
{
$deviceDetails = $this->deviceDetailsTable()
->where([
["deviceToken", "=", $payload['deviceToken'] ],
])->first();
return $deviceDetails;
}
public function retrieveDeviceDetails()
{
$deviceDetails = $this->deviceDetailsTable()
->select('deviceToken')
->distinct() // Fetch distinct device tokens
->get();
$deviceTokens = [];
// Assuming $deviceDetails holds the fetched data
foreach ($deviceDetails as $device) {
// Assuming 'deviceToken' is the key for device token in the result set
$deviceTokens[] = $device->deviceToken;
}
return $deviceTokens;
}
public function checkDuplicates($payload)
{
$transferRecipients = $this->transferTable()
->where([
["accountNumber", "=", $payload['accountNumber'] ],
])->first();
return $transferRecipients;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment