function handleEvent($eventName, $entityData)
 {
     $moduleName = $entityData->getModuleName();
     // Validate the event target
     if ($moduleName != 'PurchaseOrder') {
         return;
     }
     //Get Current User Information
     global $current_user, $currentModule;
     /**
      * Adjust the balance amount against total & paid amount
      * NOTE: beforesave the total amount will not be populated in event data.
      */
     if ($eventName == 'vtiger.entity.aftersave') {
         if ($currentModule != 'PurchaseOrder') {
             return;
         }
         $entityDelta = new VTEntityDelta();
         $oldCurrency = $entityDelta->getOldValue($entityData->getModuleName(), $entityData->getId(), 'currency_id');
         $oldConversionRate = $entityDelta->getOldValue($entityData->getModuleName(), $entityData->getId(), 'conversion_rate');
         $newCurrency = $entityDelta->getCurrentValue($entityData->getModuleName(), $entityData->getId(), 'currency_id');
         $db = PearDatabase::getInstance();
         $wsid = vtws_getWebserviceEntityId('PurchaseOrder', $entityData->getId());
         $wsrecord = vtws_retrieve($wsid, $current_user);
         if ($oldCurrency != $newCurrency && $oldCurrency != '') {
             if ($oldConversionRate != '') {
                 $wsrecord['paid'] = floatval($wsrecord['paid'] / $oldConversionRate * $wsrecord['conversion_rate']);
             }
         }
         /*
                     $wsrecord['balance'] = floatval($wsrecord['hdnGrandTotal'] - $wsrecord['paid']);
                     if ($wsrecord['balance'] == 0)
                         $wsrecord['postatus'] = 'Received Shipment';
                     $query = "UPDATE vtiger_purchaseorder SET balance=?,paid=? WHERE purchaseorderid=?";
                     $db->pquery($query, array($wsrecord['balance'], $wsrecord['paid'], $entityData->getId()));
                     // TODO Make it available for other event handlers
         */
     }
 }
 function handleEvent($eventName, $entityData)
 {
     $moduleName = $entityData->getModuleName();
     // Validate the event target
     if ($moduleName != 'Invoice') {
         return;
     }
     //Get Current User Information
     global $current_user, $currentModule;
     /**
      * Adjust the balance amount against total & received amount
      * NOTE: beforesave the total amount will not be populated in event data.
      */
     if ($eventName == 'vtiger.entity.aftersave') {
         // Trigger from other module (due to indirect save) need to be ignored - to avoid inconsistency.
         if ($currentModule != 'Invoice') {
             return;
         }
         $entityDelta = new VTEntityDelta();
         $oldCurrency = $entityDelta->getOldValue($entityData->getModuleName(), $entityData->getId(), 'currency_id');
         $newCurrency = $entityDelta->getCurrentValue($entityData->getModuleName(), $entityData->getId(), 'currency_id');
         $oldConversionRate = $entityDelta->getOldValue($entityData->getModuleName(), $entityData->getId(), 'conversion_rate');
         $db = PearDatabase::getInstance();
         $wsid = vtws_getWebserviceEntityId('Invoice', $entityData->getId());
         $wsrecord = vtws_retrieve($wsid, $current_user);
         if ($oldCurrency != $newCurrency && $oldCurrency != '') {
             if ($oldConversionRate != '') {
                 $wsrecord['received'] = floatval($wsrecord['received'] / $oldConversionRate * $wsrecord['conversion_rate']);
             }
         }
         $wsrecord['balance'] = floatval($wsrecord['hdnGrandTotal'] - $wsrecord['received']);
         if ($wsrecord['balance'] == 0) {
             $wsrecord['invoicestatus'] = 'Paid';
         }
         $query = "UPDATE vtiger_invoice SET balance=?,received=? WHERE invoiceid=?";
         $db->pquery($query, array($wsrecord['balance'], $wsrecord['received'], $entityData->getId()));
     }
 }
function HelpDesk_notifyOnPortalTicketComment($entityData)
{
    $adb = PearDatabase::getInstance();
    $moduleName = $entityData->getModuleName();
    $wsId = $entityData->getId();
    $parts = explode('x', $wsId);
    $entityId = $parts[1];
    $ownerIdInfo = getRecordOwnerId($entityId);
    if (!empty($ownerIdInfo['Users'])) {
        $ownerId = $ownerIdInfo['Users'];
        $ownerName = getOwnerName($ownerId);
        $to_email = getUserEmailId('id', $ownerId);
    }
    if (!empty($ownerIdInfo['Groups'])) {
        $ownerId = $ownerIdInfo['Groups'];
        $groupInfo = getGroupName($ownerId);
        $ownerName = $groupInfo[0];
        $to_email = implode(',', getDefaultAssigneeEmailIds($ownerId));
    }
    $wsParentId = $entityData->get('contact_id');
    $parentIdParts = explode('x', $wsParentId);
    $parentId = $parentIdParts[1];
    $entityDelta = new VTEntityDelta();
    $oldComments = $entityDelta->getOldValue($entityData->getModuleName(), $entityId, 'comments');
    $newComments = $entityDelta->getCurrentValue($entityData->getModuleName(), $entityId, 'comments');
    $commentDiff = str_replace($oldComments, '', $newComments);
    $latestComment = strip_tags($commentDiff);
    //send mail to the assigned to user when customer add comment
    // SalesPlatform.ru begin
    $subject = getTranslatedString('LBL_RESPONDTO_TICKETID', $moduleName) . " " . $entityData->get('ticket_no') . " " . getTranslatedString('LBL_CUSTOMER_PORTAL', $moduleName);
    //$subject = getTranslatedString('LBL_RESPONDTO_TICKETID', $moduleName)."##". $entityId."##". getTranslatedString('LBL_CUSTOMER_PORTAL', $moduleName);
    // SalesPlatform.ru end
    $contents = getTranslatedString('Dear', $moduleName) . " " . $ownerName . "," . "<br><br>" . getTranslatedString('LBL_CUSTOMER_COMMENTS', $moduleName) . "<br><br>\n\t\t\t\t\t\t<b>" . $latestComment . "</b><br><br>" . getTranslatedString('LBL_RESPOND', $moduleName) . "<br><br>" . getTranslatedString('LBL_REGARDS', $moduleName) . "<br>" . getTranslatedString('LBL_SUPPORT_ADMIN', $moduleName);
    //get the contact email id who creates the ticket from portal and use this email as from email id in email
    $result = $adb->pquery("SELECT lastname, firstname, email FROM vtiger_contactdetails WHERE contactid=?", array($parentId));
    $customername = $adb->query_result($result, 0, 'firstname') . ' ' . $adb->query_result($result, 0, 'lastname');
    $customername = decode_html($customername);
    //Fix to display the original UTF-8 characters in sendername instead of ascii characters
    $from_email = $adb->query_result($result, 0, 'email');
    send_mail('HelpDesk', $to_email, '', $from_email, $subject, $contents);
}
function updateInventoryProductRel($entity)
{
    global $log, $adb, $updateInventoryProductRel_update_product_array, $updateInventoryProductRel_deduct_stock;
    $entity_id = vtws_getIdComponents($entity->getId());
    $entity_id = $entity_id[1];
    $update_product_array = $updateInventoryProductRel_update_product_array;
    $log->debug("Entering into function updateInventoryProductRel(" . $entity_id . ").");
    if (!empty($update_product_array)) {
        foreach ($update_product_array as $id => $seq) {
            foreach ($seq as $seq => $product_info) {
                foreach ($product_info as $key => $index) {
                    $updqtyinstk = getPrdQtyInStck($key);
                    $upd_qty = $updqtyinstk + $index;
                    updateProductQty($key, $upd_qty);
                }
            }
        }
    }
    $moduleName = $entity->getModuleName();
    if ($moduleName === 'Invoice') {
        $statusFieldName = 'invoicestatus';
        $statusFieldValue = 'Cancel';
    } elseif ($moduleName === 'PurchaseOrder') {
        $statusFieldName = 'postatus';
        $statusFieldValue = 'Received Shipment';
    }
    $statusChanged = false;
    $vtEntityDelta = new VTEntityDelta();
    $oldEntity = $vtEntityDelta->getOldValue($moduleName, $entity_id, $statusFieldName);
    $recordDetails = $entity->getData();
    $statusChanged = $vtEntityDelta->hasChanged($moduleName, $entity_id, $statusFieldName);
    if ($statusChanged) {
        if ($recordDetails[$statusFieldName] == $statusFieldValue) {
            $adb->pquery("UPDATE vtiger_inventoryproductrel SET incrementondel=0 WHERE id=?", array($entity_id));
            $updateInventoryProductRel_deduct_stock = false;
            if (empty($update_product_array)) {
                addProductsToStock($entity_id);
            }
        } elseif ($oldEntity == $statusFieldValue) {
            $updateInventoryProductRel_deduct_stock = false;
            deductProductsFromStock($entity_id);
        }
    } elseif ($recordDetails[$statusFieldName] == $statusFieldValue) {
        $updateInventoryProductRel_deduct_stock = false;
    }
    if ($updateInventoryProductRel_deduct_stock) {
        $adb->pquery("UPDATE vtiger_inventoryproductrel SET incrementondel=1 WHERE id=?", array($entity_id));
        $product_info = $adb->pquery("SELECT productid,sequence_no, quantity from vtiger_inventoryproductrel WHERE id=?", array($entity_id));
        $numrows = $adb->num_rows($product_info);
        for ($index = 0; $index < $numrows; $index++) {
            $productid = $adb->query_result($product_info, $index, 'productid');
            $qty = $adb->query_result($product_info, $index, 'quantity');
            $sequence_no = $adb->query_result($product_info, $index, 'sequence_no');
            $qtyinstk = getPrdQtyInStck($productid);
            $upd_qty = $qtyinstk - $qty;
            updateProductQty($productid, $upd_qty);
            $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($entity_id, $sequence_no));
            if ($adb->num_rows($sub_prod_query) > 0) {
                for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                    $sub_prod_id = $adb->query_result($sub_prod_query, $j, "productid");
                    $sqtyinstk = getPrdQtyInStck($sub_prod_id);
                    $supd_qty = $sqtyinstk - $qty;
                    updateProductQty($sub_prod_id, $supd_qty);
                }
            }
        }
    }
    $log->debug("Exit from function updateInventoryProductRel(" . $entity_id . ")");
}