From 97954250cdf3107fc9dd29355d1ea1094ea87237 Mon Sep 17 00:00:00 2001 From: Erawat Chamanont Date: Fri, 22 Sep 2023 13:09:21 +0100 Subject: [PATCH] BTHAB-185: Update statuses on contribution deletion --- .../Hook/Pre/DeleteSalesOrderContribution.php | 79 +++++++++++++++++++ civicase.php | 13 +++ 2 files changed, 92 insertions(+) create mode 100644 CRM/Civicase/Hook/Pre/DeleteSalesOrderContribution.php diff --git a/CRM/Civicase/Hook/Pre/DeleteSalesOrderContribution.php b/CRM/Civicase/Hook/Pre/DeleteSalesOrderContribution.php new file mode 100644 index 000000000..e8d5c9f98 --- /dev/null +++ b/CRM/Civicase/Hook/Pre/DeleteSalesOrderContribution.php @@ -0,0 +1,79 @@ +shouldRun($op, $objectName)) { + return; + } + + $salesOrderId = $this->getQuotationId($objectId); + if (empty($salesOrderId)) { + return; + } + + $caseSaleOrderContributionService = new CRM_Civicase_Service_CaseSalesOrderContributionCalculator($salesOrderId); + $invoicingStatusId = $caseSaleOrderContributionService->calculateInvoicingStatus(); + $paymentStatusId = $caseSaleOrderContributionService->calculatePaymentStatus(); + + CaseSalesOrder::update() + ->addWhere('id', '=', $salesOrderId) + ->addValue('invoicing_status_id', $invoicingStatusId) + ->addValue('payment_status_id', $paymentStatusId) + ->execute(); + + $caseSalesOrder = CaseSalesOrder::get() + ->addSelect('case_id') + ->addWhere('id', '=', $salesOrderId) + ->execute() + ->first(); + + $caseSaleOrderContributionService = new \CRM_Civicase_Service_CaseSalesOrderOpportunityCalculator($caseSalesOrder['case_id']); + $caseSaleOrderContributionService->updateOpportunityFinancialDetails(); + } + + /** + * Determines if the hook should run or not. + * + * @param string $op + * The operation being performed. + * @param string $objectName + * Object name. + * + * @return bool + * returns a boolean to determine if hook will run or not. + */ + private function shouldRun($op, $objectName) { + return strtolower($objectName) == 'contribution' && $op == 'delete'; + } + + /** + * Gets quotation ID by contribution ID. + */ + private function getQuotationId($id) { + return Contribution::get() + ->addSelect('Opportunity_Details.Quotation') + ->addWhere('id', '=', $id) + ->execute() + ->first()['Opportunity_Details.Quotation']; + } + +} diff --git a/civicase.php b/civicase.php index 3cf5b82a7..a2eaae277 100644 --- a/civicase.php +++ b/civicase.php @@ -258,6 +258,19 @@ function civicase_civicrm_post($op, $objectName, $objectId, &$objectRef) { } } +/** + * Implements hook_civicrm_pre(). + */ +function civicase_civicrm_pre($op, $objectName, $id, &$params) { + $hooks = [ + new CRM_Civicase_Hook_Pre_DeleteSalesOrderContribution(), + ]; + + foreach ($hooks as $hook) { + $hook->run($op, $objectName, $id, $params); + } +} + /** * Implements hook_civicrm_postProcess(). */