Exemple #1
0
 protected function processRetrieve(Mobile_API_Request $request)
 {
     $current_user = $this->getActiveUser();
     $recordid = $request->get('record');
     $record = vtws_retrieve($recordid, $current_user);
     return $record;
 }
/**
 * Retrieve inventory record with LineItems
 */
function vtws_retrieve_inventory($id)
{
    $current_user = vglobal('current_user');
    $record = vtws_retrieve($id, $current_user);
    $handler = vtws_getModuleHandlerFromName('LineItem', $user);
    $id = vtws_getIdComponents($id);
    $id = $id[1];
    $inventoryLineItems = $handler->getAllLineItemForParent($id);
    $record['LineItems'] = $inventoryLineItems;
    return $record;
}
Exemple #3
0
 function process(Mobile_API_Request $request)
 {
     $current_user = vglobal('current_user');
     // Required for vtws_update API
     $current_user = $this->getActiveUser();
     $module = $request->get('module');
     $recordid = $request->get('record');
     $valuesJSONString = $request->get('values');
     $values = "";
     if (!empty($valuesJSONString) && is_string($valuesJSONString)) {
         $values = Zend_Json::decode($valuesJSONString);
     } else {
         $values = $valuesJSONString;
         // Either empty or already decoded.
     }
     $response = new Mobile_API_Response();
     if (empty($values)) {
         $response->setError(1501, "Values cannot be empty!");
         return $response;
     }
     try {
         // Retrieve or Initalize
         if (!empty($recordid) && !$this->isTemplateRecordRequest($request)) {
             $this->recordValues = vtws_retrieve($recordid, $current_user);
         } else {
             $this->recordValues = array();
         }
         // Set the modified values
         foreach ($values as $name => $value) {
             $this->recordValues[$name] = $value;
         }
         // Update or Create
         if (isset($this->recordValues['id'])) {
             $this->recordValues = vtws_update($this->recordValues, $current_user);
         } else {
             // Set right target module name for Calendar/Event record
             if ($module == 'Calendar') {
                 if (!empty($this->recordValues['eventstatus']) && $this->recordValues['activitytype'] != 'Task') {
                     $module = 'Events';
                 }
             }
             $this->recordValues = vtws_create($module, $this->recordValues, $current_user);
         }
         // Update the record id
         $request->set('record', $this->recordValues['id']);
         // Gather response with full details
         $response = parent::process($request);
     } catch (Exception $e) {
         $response->setError($e->getCode(), $e->getMessage());
     }
     return $response;
 }
 public function process(Vtiger_Request $request)
 {
     include_once 'include/Webservices/Retrieve.php';
     include_once 'include/Webservices/Revise.php';
     $user = CRMEntity::getInstance('Users');
     $user->id = 1;
     $user->retrieve_entity_info($user->id, 'Users');
     $wsrecord = vtws_retrieve(vtws_getWebserviceEntityId('Invoice', 159), $user);
     $new['LineItems'] = $wsrecord['LineItems'];
     $new['id'] = $wsrecord['id'];
     $new['LineItems'][] = array('parent_id' => '7x159', 'productid' => '14x109', 'sequence_no' => '2', 'quantity' => '3', 'listprice' => '2.1', 'comment' => 'Kommentar ' . date('Y-m-d H:i:s'), 'incrementondel' => '1', 'tax1' => 5);
     $lead = vtws_revise($new, $user);
     echo '<pre>';
     var_dump($wsrecord);
     echo '</pre>';
 }
Exemple #5
0
 public function getRecordData($moduleName, $recordId)
 {
     ${"GLOBALS"}["yhkvuqi"] = "moduleName";
     include_once "include/Webservices/Retrieve.php";
     include_once "include/Webservices/Utils.php";
     ${"GLOBALS"}["rwzcgorvwd"] = "modelData";
     if (${${"GLOBALS"}["yhkvuqi"]} == "Calendar") {
         ${${"GLOBALS"}["qdpmrziapjb"]} = vtws_getCalendarEntityType(${${"GLOBALS"}["kpdkgyrhwuc"]});
     }
     try {
         ${"GLOBALS"}["zwvujejhu"] = "recordId";
         ${${"GLOBALS"}["tykmttbjma"]} = vtws_getWebserviceEntityId(${${"GLOBALS"}["qdpmrziapjb"]}, ${${"GLOBALS"}["zwvujejhu"]});
         ${${"GLOBALS"}["cnbxfeulpcc"]} = vtws_retrieve(${${"GLOBALS"}["tykmttbjma"]}, vglobal("current_user"));
     } catch (WebServiceException $ex) {
         echo "getRecordData Error: " . $ex->getMessage();
     }
     return ${${"GLOBALS"}["rwzcgorvwd"]};
 }
 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()));
     }
 }
 public function getParentById($parentId)
 {
     if (empty(self::$parentCache[$parentId])) {
         return vtws_retrieve($parentId, $this->user);
     } else {
         return self::$parentCache[$parentId];
     }
 }
 public function createRecords()
 {
     $adb = PearDatabase::getInstance();
     $moduleName = $this->module;
     $focus = CRMEntity::getInstance($moduleName);
     $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user);
     $moduleMeta = $moduleHandler->getMeta();
     $moduleObjectId = $moduleMeta->getEntityId();
     $moduleFields = $moduleMeta->getModuleFields();
     $tableName = Import_Utils::getDbTableName($this->user);
     $sql = 'SELECT * FROM ' . $tableName . ' WHERE status = ' . Import_Data_Controller::$IMPORT_RECORD_NONE;
     if ($this->batchImport) {
         $configReader = new ConfigReader('modules/Import/config.inc', 'ImportConfig');
         $importBatchLimit = $configReader->getConfig('importBatchLimit');
         $sql .= ' LIMIT ' . $importBatchLimit;
     }
     $result = $adb->query($sql);
     $numberOfRecords = $adb->num_rows($result);
     if ($numberOfRecords <= 0) {
         return;
     }
     $fieldMapping = $this->fieldMapping;
     $fieldColumnMapping = $moduleMeta->getFieldColumnMapping();
     for ($i = 0; $i < $numberOfRecords; ++$i) {
         $row = $adb->raw_query_result_rowdata($result, $i);
         $rowId = $row['id'];
         $entityInfo = null;
         $fieldData = array();
         foreach ($fieldMapping as $fieldName => $index) {
             $fieldData[$fieldName] = $row[$fieldName];
         }
         $mergeType = $this->mergeType;
         $createRecord = false;
         if (method_exists($focus, 'importRecord')) {
             $entityInfo = $focus->importRecord($this, $fieldData);
         } else {
             if (!empty($mergeType) && $mergeType != Import_Utils::$AUTO_MERGE_NONE) {
                 $queryGenerator = new QueryGenerator($moduleName, $this->user);
                 $queryGenerator->initForDefaultCustomView();
                 $fieldsList = array('id');
                 $queryGenerator->setFields($fieldsList);
                 $mergeFields = $this->mergeFields;
                 foreach ($mergeFields as $index => $mergeField) {
                     if ($index != 0) {
                         $queryGenerator->addConditionGlue(QueryGenerator::$AND);
                     }
                     $comparisonValue = $fieldData[$mergeField];
                     $fieldInstance = $moduleFields[$mergeField];
                     if ($fieldInstance->getFieldDataType() == 'owner') {
                         $userId = getUserId_Ol($comparisonValue);
                         $comparisonValue = getUserFullName($userId);
                     }
                     if ($fieldInstance->getFieldDataType() == 'reference') {
                         if (strpos($comparisonValue, '::::') > 0) {
                             $referenceFileValueComponents = explode('::::', $comparisonValue);
                         } else {
                             $referenceFileValueComponents = explode(':::', $comparisonValue);
                         }
                         if (count($referenceFileValueComponents) > 1) {
                             $comparisonValue = trim($referenceFileValueComponents[1]);
                         }
                     }
                     $queryGenerator->addCondition($mergeField, $comparisonValue, 'e');
                 }
                 $query = $queryGenerator->getQuery();
                 $duplicatesResult = $adb->query($query);
                 $noOfDuplicates = $adb->num_rows($duplicatesResult);
                 if ($noOfDuplicates > 0) {
                     if ($mergeType == Import_Utils::$AUTO_MERGE_IGNORE) {
                         $entityInfo['status'] = self::$IMPORT_RECORD_SKIPPED;
                     } elseif ($mergeType == Import_Utils::$AUTO_MERGE_OVERWRITE || $mergeType == Import_Utils::$AUTO_MERGE_MERGEFIELDS) {
                         for ($index = 0; $index < $noOfDuplicates - 1; ++$index) {
                             $duplicateRecordId = $adb->query_result($duplicatesResult, $index, $fieldColumnMapping['id']);
                             $entityId = vtws_getId($moduleObjectId, $duplicateRecordId);
                             vtws_delete($entityId, $this->user);
                         }
                         $baseRecordId = $adb->query_result($duplicatesResult, $noOfDuplicates - 1, $fieldColumnMapping['id']);
                         $baseEntityId = vtws_getId($moduleObjectId, $baseRecordId);
                         if ($mergeType == Import_Utils::$AUTO_MERGE_OVERWRITE) {
                             $fieldData = $this->transformForImport($fieldData, $moduleMeta);
                             $fieldData['id'] = $baseEntityId;
                             $entityInfo = vtws_update($fieldData, $this->user);
                             $entityInfo['status'] = self::$IMPORT_RECORD_UPDATED;
                             //Prepare data for event handler
                             $entityData = array();
                             $entityData['rowId'] = $rowId;
                             $entityData['tableName'] = $tableName;
                             $entityData['entityInfo'] = $entityInfo;
                             $entityData['fieldData'] = $fieldData;
                             $entityData['moduleName'] = $moduleName;
                             $entityData['user'] = $this->user;
                             cbEventHandler::do_action('corebos.entity.import.overwrite', $entityData);
                         }
                         if ($mergeType == Import_Utils::$AUTO_MERGE_MERGEFIELDS) {
                             $filteredFieldData = array();
                             $defaultFieldValues = $this->getDefaultFieldValues($moduleMeta);
                             foreach ($fieldData as $fieldName => $fieldValue) {
                                 if (!empty($fieldValue)) {
                                     $filteredFieldData[$fieldName] = $fieldValue;
                                 }
                             }
                             $existingFieldValues = vtws_retrieve($baseEntityId, $this->user);
                             foreach ($existingFieldValues as $fieldName => $fieldValue) {
                                 if (empty($fieldValue) && empty($filteredFieldData[$fieldName]) && !empty($defaultFieldValues[$fieldName])) {
                                     $filteredFieldData[$fieldName] = $fieldValue;
                                 }
                             }
                             $filteredFieldData = $this->transformForImport($filteredFieldData, $moduleMeta, false, true);
                             $filteredFieldData['id'] = $baseEntityId;
                             $entityInfo = vtws_revise($filteredFieldData, $this->user);
                             $entityInfo['status'] = self::$IMPORT_RECORD_MERGED;
                             //Prepare data for event handler
                             $entityData = array();
                             $entityData['rowId'] = $rowId;
                             $entityData['tableName'] = $tableName;
                             $entityData['entityInfo'] = $entityInfo;
                             $entityData['fieldData'] = $fieldData;
                             $entityData['moduleName'] = $moduleName;
                             $entityData['user'] = $this->user;
                             cbEventHandler::do_action('corebos.entity.import.merge', $entityData);
                         }
                     } else {
                         $createRecord = true;
                     }
                 } else {
                     $createRecord = true;
                 }
             } else {
                 $createRecord = true;
             }
             if ($createRecord) {
                 $fieldData = $this->transformForImport($fieldData, $moduleMeta);
                 if ($fieldData == null) {
                     $entityInfo = null;
                 } else {
                     $entityInfo = vtws_create($moduleName, $fieldData, $this->user);
                     $entityInfo['status'] = self::$IMPORT_RECORD_CREATED;
                     //Prepare data for event handler
                     $entityData = array();
                     $entityData['rowId'] = $rowId;
                     $entityData['tableName'] = $tableName;
                     $entityData['entityInfo'] = $entityInfo;
                     $entityData['fieldData'] = $fieldData;
                     $entityData['moduleName'] = $moduleName;
                     $entityData['user'] = $this->user;
                     cbEventHandler::do_action('corebos.entity.import.create', $entityData);
                 }
             }
         }
         if ($entityInfo == null) {
             $entityInfo = array('id' => null, 'status' => self::$IMPORT_RECORD_FAILED);
         }
         $this->importedRecordInfo[$rowId] = $entityInfo;
         $this->updateImportStatus($rowId, $entityInfo);
     }
     unset($result);
     return true;
 }
function vtws_convertlead($entityvalues, $user)
{
    global $adb, $log;
    if (empty($entityvalues['assignedTo'])) {
        $entityvalues['assignedTo'] = vtws_getWebserviceEntityId('Users', $user->id);
    }
    if (empty($entityvalues['transferRelatedRecordsTo'])) {
        $entityvalues['transferRelatedRecordsTo'] = 'Contacts';
    }
    $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads');
    $handlerPath = $leadObject->getHandlerPath();
    $handlerClass = $leadObject->getHandlerClass();
    require_once $handlerPath;
    $leadHandler = new $handlerClass($leadObject, $user, $adb, $log);
    $leadInfo = vtws_retrieve($entityvalues['leadId'], $user);
    $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?";
    $leadIdComponents = vtws_getIdComponents($entityvalues['leadId']);
    $result = $adb->pquery($sql, array($leadIdComponents[1]));
    if ($result === false) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR));
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount > 0) {
        throw new WebServiceException(WebServiceErrorCode::$LEAD_ALREADY_CONVERTED, "Lead is already converted");
    }
    $entityIds = array();
    $availableModules = array('Accounts', 'Contacts', 'Potentials');
    if (!($entityvalues['entities']['Accounts']['create'] || $entityvalues['entities']['Contacts']['create'])) {
        return null;
    }
    foreach ($availableModules as $entityName) {
        if ($entityvalues['entities'][$entityName]['create']) {
            $entityvalue = $entityvalues['entities'][$entityName];
            $entityObject = VtigerWebserviceObject::fromName($adb, $entityvalue['name']);
            $handlerPath = $entityObject->getHandlerPath();
            $handlerClass = $entityObject->getHandlerClass();
            require_once $handlerPath;
            $entityHandler = new $handlerClass($entityObject, $user, $adb, $log);
            $entityObjectValues = array();
            $entityObjectValues['assigned_user_id'] = $entityvalues['assignedTo'];
            $entityObjectValues = vtws_populateConvertLeadEntities($entityvalue, $entityObjectValues, $entityHandler, $leadHandler, $leadInfo);
            //update potential related to property
            if ($entityvalue['name'] == 'Potentials') {
                if (!empty($entityIds['Accounts'])) {
                    $entityObjectValues['related_to'] = $entityIds['Accounts'];
                }
                if (!empty($entityIds['Contacts'])) {
                    $entityObjectValues['contact_id'] = $entityIds['Contacts'];
                }
            }
            //update the contacts relation
            if ($entityvalue['name'] == 'Contacts') {
                if (!empty($entityIds['Accounts'])) {
                    $entityObjectValues['account_id'] = $entityIds['Accounts'];
                }
            }
            try {
                $create = true;
                if ($entityvalue['name'] == 'Accounts') {
                    $sql = "SELECT vtiger_account.accountid FROM vtiger_account,vtiger_crmentity WHERE vtiger_crmentity.crmid=vtiger_account.accountid AND vtiger_account.accountname=? AND vtiger_crmentity.deleted=0";
                    $result = $adb->pquery($sql, array($entityvalue['accountname']));
                    if ($adb->num_rows($result) > 0) {
                        $entityIds[$entityName] = vtws_getWebserviceEntityId('Accounts', $adb->query_result($result, 0, 'accountid'));
                        $create = false;
                    }
                }
                if ($create) {
                    $entityRecord = vtws_create($entityvalue['name'], $entityObjectValues, $user);
                    $entityIds[$entityName] = $entityRecord['id'];
                }
            } catch (Exception $e) {
                throw new WebServiceException(WebServiceErrorCode::$UNKNOWNOPERATION, $e->getMessage() . ' : ' . $entityvalue['name']);
            }
        }
    }
    try {
        $accountIdComponents = vtws_getIdComponents($entityIds['Accounts']);
        $accountId = $accountIdComponents[1];
        $contactIdComponents = vtws_getIdComponents($entityIds['Contacts']);
        $contactId = $contactIdComponents[1];
        if (!empty($accountId) && !empty($contactId) && !empty($entityIds['Potentials'])) {
            $potentialIdComponents = vtws_getIdComponents($entityIds['Potentials']);
            $potentialId = $potentialIdComponents[1];
            $sql = "insert into vtiger_contpotentialrel values(?,?)";
            $result = $adb->pquery($sql, array($contactId, $potentialIdComponents[1]));
            if ($result === false) {
                throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_CREATE_RELATION, "Failed to related Contact with the Potential");
            }
        }
        $transfered = vtws_convertLeadTransferHandler($leadIdComponents, $entityIds, $entityvalues);
        $relatedIdComponents = vtws_getIdComponents($entityIds[$entityvalues['transferRelatedRecordsTo']]);
        vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactId, $relatedIdComponents[1]);
        vtws_updateConvertLeadStatus($entityIds, $entityvalues['leadId'], $user);
    } catch (Exception $e) {
        foreach ($entityIds as $entity => $id) {
            vtws_delete($id, $user);
        }
        return null;
    }
    return $entityIds;
}
Exemple #11
0
 public function createRecords()
 {
     $adb = PearDatabase::getInstance();
     $moduleName = $this->module;
     $focus = CRMEntity::getInstance($moduleName);
     $moduleHandler = vtws_getModuleHandlerFromName($moduleName, $this->user);
     $moduleMeta = $moduleHandler->getMeta();
     $moduleObjectId = $moduleMeta->getEntityId();
     $moduleFields = $moduleMeta->getModuleFields();
     $entityData = array();
     $tableName = Import_Utils_Helper::getDbTableName($this->user);
     $sql = 'SELECT * FROM ' . $tableName . ' WHERE status = ' . Import_Data_Action::$IMPORT_RECORD_NONE;
     if ($this->batchImport) {
         $configReader = new Import_Config_Model();
         $importBatchLimit = $configReader->get('importBatchLimit');
         $sql .= ' LIMIT ' . $importBatchLimit;
     }
     $result = $adb->query($sql);
     $numberOfRecords = $adb->num_rows($result);
     if ($numberOfRecords <= 0) {
         return;
     }
     $fieldMapping = $this->fieldMapping;
     $fieldColumnMapping = $moduleMeta->getFieldColumnMapping();
     for ($i = 0; $i < $numberOfRecords; ++$i) {
         $row = $adb->raw_query_result_rowdata($result, $i);
         $rowId = $row['id'];
         $entityInfo = null;
         $fieldData = array();
         foreach ($fieldMapping as $fieldName => $index) {
             $fieldData[$fieldName] = $row[$fieldName];
         }
         $mergeType = $this->mergeType;
         $createRecord = false;
         if (method_exists($focus, 'importRecord')) {
             $entityInfo = $focus->importRecord($this, $fieldData);
         } else {
             if (!empty($mergeType) && $mergeType != Import_Utils_Helper::$AUTO_MERGE_NONE) {
                 $queryGenerator = new QueryGenerator($moduleName, $this->user);
                 $customView = new CustomView($moduleName);
                 $viewId = $customView->getViewIdByName('All', $moduleName);
                 if (!empty($viewId)) {
                     $queryGenerator->initForCustomViewById($viewId);
                 } else {
                     $queryGenerator->initForDefaultCustomView();
                 }
                 $fieldsList = array('id');
                 $queryGenerator->setFields($fieldsList);
                 $mergeFields = $this->mergeFields;
                 if ($queryGenerator->getWhereFields() && $mergeFields) {
                     $queryGenerator->addConditionGlue(QueryGenerator::$AND);
                 }
                 foreach ($mergeFields as $index => $mergeField) {
                     if ($index != 0) {
                         $queryGenerator->addConditionGlue(QueryGenerator::$AND);
                     }
                     $comparisonValue = $fieldData[$mergeField];
                     $fieldInstance = $moduleFields[$mergeField];
                     if ($fieldInstance->getFieldDataType() == 'owner') {
                         $userId = getUserId_Ol($comparisonValue);
                         $comparisonValue = getUserFullName($userId);
                     }
                     if ($fieldInstance->getFieldDataType() == 'reference') {
                         if (strpos($comparisonValue, '::::') > 0) {
                             $referenceFileValueComponents = explode('::::', $comparisonValue);
                         } else {
                             $referenceFileValueComponents = explode(':::', $comparisonValue);
                         }
                         if (count($referenceFileValueComponents) > 1) {
                             $comparisonValue = trim($referenceFileValueComponents[1]);
                         }
                     }
                     $queryGenerator->addCondition($mergeField, $comparisonValue, 'e', '', '', '', true);
                 }
                 $query = $queryGenerator->getQuery();
                 $duplicatesResult = $adb->query($query);
                 $noOfDuplicates = $adb->num_rows($duplicatesResult);
                 if ($noOfDuplicates > 0) {
                     if ($mergeType == Import_Utils_Helper::$AUTO_MERGE_IGNORE) {
                         $entityInfo['status'] = self::$IMPORT_RECORD_SKIPPED;
                     } elseif ($mergeType == Import_Utils_Helper::$AUTO_MERGE_OVERWRITE || $mergeType == Import_Utils_Helper::$AUTO_MERGE_MERGEFIELDS) {
                         for ($index = 0; $index < $noOfDuplicates - 1; ++$index) {
                             $duplicateRecordId = $adb->query_result($duplicatesResult, $index, $fieldColumnMapping['id']);
                             $entityId = vtws_getId($moduleObjectId, $duplicateRecordId);
                             vtws_delete($entityId, $this->user);
                         }
                         $baseRecordId = $adb->query_result($duplicatesResult, $noOfDuplicates - 1, $fieldColumnMapping['id']);
                         $baseEntityId = vtws_getId($moduleObjectId, $baseRecordId);
                         if ($mergeType == Import_Utils_Helper::$AUTO_MERGE_OVERWRITE) {
                             $fieldData = $this->transformForImport($fieldData, $moduleMeta);
                             $fieldData['id'] = $baseEntityId;
                             $entityInfo = vtws_update($fieldData, $this->user);
                             $entityInfo['status'] = self::$IMPORT_RECORD_UPDATED;
                         }
                         if ($mergeType == Import_Utils_Helper::$AUTO_MERGE_MERGEFIELDS) {
                             $filteredFieldData = array();
                             foreach ($fieldData as $fieldName => $fieldValue) {
                                 // empty will give false for value = 0
                                 if (!empty($fieldValue) || $fieldValue != "") {
                                     $filteredFieldData[$fieldName] = $fieldValue;
                                 }
                             }
                             // Custom handling for default values & mandatory fields
                             // need to be taken care than normal import as we merge
                             // existing record values with newer values.
                             $fillDefault = false;
                             $mandatoryValueChecks = false;
                             $existingFieldValues = vtws_retrieve($baseEntityId, $this->user);
                             $defaultFieldValues = $this->getDefaultFieldValues($moduleMeta);
                             foreach ($existingFieldValues as $fieldName => $fieldValue) {
                                 if (empty($fieldValue) && empty($filteredFieldData[$fieldName]) && !empty($defaultFieldValues[$fieldName])) {
                                     $filteredFieldData[$fieldName] = $defaultFieldValues[$fieldName];
                                 }
                             }
                             $filteredFieldData = $this->transformForImport($filteredFieldData, $moduleMeta, $fillDefault, $mandatoryValueChecks);
                             $filteredFieldData['id'] = $baseEntityId;
                             $entityInfo = vtws_revise($filteredFieldData, $this->user);
                             $entityInfo['status'] = self::$IMPORT_RECORD_MERGED;
                             $fieldData = $filteredFieldData;
                         }
                     } else {
                         $createRecord = true;
                     }
                 } else {
                     $createRecord = true;
                 }
             } else {
                 $createRecord = true;
             }
             if ($createRecord) {
                 $fieldData = $this->transformForImport($fieldData, $moduleMeta);
                 if ($fieldData == null) {
                     $entityInfo = null;
                 } else {
                     try {
                         $entityInfo = vtws_create($moduleName, $fieldData, $this->user);
                     } catch (Exception $e) {
                     }
                 }
             }
         }
         if ($entityInfo == null) {
             $entityInfo = array('id' => null, 'status' => self::$IMPORT_RECORD_FAILED);
         } else {
             if ($createRecord) {
                 $entityInfo['status'] = self::$IMPORT_RECORD_CREATED;
             }
         }
         if ($createRecord || $mergeType == Import_Utils_Helper::$AUTO_MERGE_MERGEFIELDS || $mergeType == Import_Utils_Helper::$AUTO_MERGE_OVERWRITE) {
             $entityIdComponents = vtws_getIdComponents($entityInfo['id']);
             $recordId = $entityIdComponents[1];
             $entityfields = getEntityFieldNames($this->module);
             switch ($this->module) {
                 case 'HelpDesk':
                     $entityfields['fieldname'] = array('ticket_title');
                     break;
                 case 'Documents':
                     $entityfields['fieldname'] = array('notes_title');
                     break;
                 case 'Documents':
                     $entityfields['fieldname'] = array('notes_title');
                     break;
             }
             $label = '';
             if (is_array($entityfields['fieldname'])) {
                 foreach ($entityfields['fieldname'] as $field) {
                     $label .= $fieldData[$field] . " ";
                 }
             } else {
                 $label = $fieldData[$entityfields['fieldname']];
             }
             $label = trim($label);
             $adb->pquery('UPDATE vtiger_crmentity SET label=? WHERE crmid=?', array($label, $recordId));
         }
         $this->importedRecordInfo[$rowId] = $entityInfo;
         $this->updateImportStatus($rowId, $entityInfo);
     }
     if ($this->entityData) {
         $entity = new VTEventsManager($adb);
         $entity->triggerEvent('vtiger.batchevent.save', $this->entityData);
     }
     $this->entityData = null;
     $result = null;
     return true;
 }
Exemple #12
0
function vtws_convertlead($entityvalues, $user)
{
    $adb = PearDatabase::getInstance();
    $log = vglobal('log');
    $log->debug('Start ' . __CLASS__ . ':' . __FUNCTION__);
    if (empty($entityvalues['assignedTo'])) {
        $entityvalues['assignedTo'] = vtws_getWebserviceEntityId('Users', $user->id);
    }
    if (empty($entityvalues['transferRelatedRecordsTo'])) {
        $entityvalues['transferRelatedRecordsTo'] = 'Accounts';
    }
    $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads');
    $handlerPath = $leadObject->getHandlerPath();
    $handlerClass = $leadObject->getHandlerClass();
    require_once $handlerPath;
    $leadHandler = new $handlerClass($leadObject, $user, $adb, $log);
    $leadInfo = vtws_retrieve($entityvalues['leadId'], $user);
    $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?";
    $leadIdComponents = vtws_getIdComponents($entityvalues['leadId']);
    $result = $adb->pquery($sql, array($leadIdComponents[1]));
    if ($result === false) {
        $log->error('Error converting a lead: ' . vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR));
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, vtws_getWebserviceTranslatedString('LBL_' . WebServiceErrorCode::$DATABASEQUERYERROR));
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount > 0) {
        $log->error('Error converting a lead: Lead is already converted');
        throw new WebServiceException(WebServiceErrorCode::$LEAD_ALREADY_CONVERTED, "Lead is already converted");
    }
    require_once "include/events/include.inc";
    $em = new VTEventsManager($adb);
    // Initialize Event trigger cache
    $em->initTriggerCache();
    $entityData = VTEntityData::fromEntityId($adb, $leadIdComponents[1]);
    $em->triggerEvent('entity.convertlead.before', [$entityvalues, $user, $leadInfo]);
    $entityIds = [];
    $availableModules = ['Accounts', 'Contacts', 'Potentials'];
    if (!($entityvalues['entities']['Accounts']['create'] || $entityvalues['entities']['Contacts']['create'])) {
        return null;
    }
    foreach ($availableModules as $entityName) {
        if ($entityvalues['entities'][$entityName]['create']) {
            $entityvalue = $entityvalues['entities'][$entityName];
            $entityObject = VtigerWebserviceObject::fromName($adb, $entityvalue['name']);
            $handlerPath = $entityObject->getHandlerPath();
            $handlerClass = $entityObject->getHandlerClass();
            require_once $handlerPath;
            $entityHandler = new $handlerClass($entityObject, $user, $adb, $log);
            $entityObjectValues = array();
            $entityObjectValues['assigned_user_id'] = $entityvalues['assignedTo'];
            $entityObjectValues = vtws_populateConvertLeadEntities($entityvalue, $entityObjectValues, $entityHandler, $leadHandler, $leadInfo);
            //update potential related to property
            if ($entityvalue['name'] == 'Potentials') {
                if (!empty($entityIds['Accounts'])) {
                    $entityObjectValues['related_to'] = $entityIds['Accounts'];
                }
                if (!empty($entityIds['Contacts'])) {
                    $entityObjectValues['contact_id'] = $entityIds['Contacts'];
                }
            }
            //update the contacts relation
            if ($entityvalue['name'] == 'Contacts') {
                if (!empty($entityIds['Accounts'])) {
                    $entityObjectValues['parent_id'] = $entityIds['Accounts'];
                }
            }
            try {
                $create = true;
                if ($entityvalue['name'] == 'Accounts' && $entityvalue['convert_to_id'] && is_int($entityvalue['convert_to_id'])) {
                    $entityIds[$entityName] = vtws_getWebserviceEntityId('Accounts', $entityvalue['convert_to_id']);
                    $create = false;
                }
                if ($create) {
                    $entityRecord = vtws_create($entityvalue['name'], $entityObjectValues, $user);
                    $entityIds[$entityName] = $entityRecord['id'];
                }
            } catch (Exception $e) {
                $log->error('Error converting a lead: ' . $e->getMessage());
                throw new WebServiceException(WebServiceErrorCode::$UNKNOWNOPERATION, $e->getMessage() . ' : ' . $entityvalue['name']);
            }
        }
    }
    try {
        $accountIdComponents = vtws_getIdComponents($entityIds['Accounts']);
        $accountId = $accountIdComponents[1];
        $contactIdComponents = vtws_getIdComponents($entityIds['Contacts']);
        $contactId = $contactIdComponents[1];
        if (!empty($accountId) && !empty($contactId) && !empty($entityIds['Potentials'])) {
            $potentialIdComponents = vtws_getIdComponents($entityIds['Potentials']);
            $potentialId = $potentialIdComponents[1];
            $sql = "insert into vtiger_contpotentialrel values(?,?)";
            $result = $adb->pquery($sql, array($contactId, $potentialIdComponents[1]));
            if ($result === false) {
                throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_CREATE_RELATION, "Failed to related Contact with the Potential");
            }
        }
        $transfered = vtws_convertLeadTransferHandler($leadIdComponents, $entityIds, $entityvalues);
        $relatedIdComponents = vtws_getIdComponents($entityIds[$entityvalues['transferRelatedRecordsTo']]);
        vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactId, $relatedIdComponents[1]);
        vtws_updateConvertLeadStatus($entityIds, $entityvalues['leadId'], $user);
        if ($em) {
            $em->triggerEvent('entity.convertlead.after', [$entityvalues, $user, $leadInfo, $entityIds]);
        }
    } catch (Exception $e) {
        $log->error('Error converting a lead: ' . $e->getMessage());
        foreach ($entityIds as $entity => $id) {
            vtws_delete($id, $user);
        }
        return null;
    }
    $log->debug('End ' . __CLASS__ . ':' . __FUNCTION__);
    return $entityIds;
}
 /**
  * Retrieve record.
  * @param String $reference
  * @return array
  */
 public function retrieve($reference)
 {
     return vtws_retrieve($reference, $this->restUser);
 }
function showMandatoryFieldsAndValues($entityValues)
{
    global $log, $adb, $current_user;
    $yes = getTranslatedString('LBL_YES');
    $no = getTranslatedString('LBL_NO');
    echo "<table width=100% border=0>";
    echo "<tr><td>" . getTranslatedString('LBL_MANDATORY_FIELDS', 'Settings') . "</td></tr>";
    $availableModules = array('Accounts', 'Contacts', 'Potentials');
    $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads');
    $handlerPath = $leadObject->getHandlerPath();
    $handlerClass = $leadObject->getHandlerClass();
    require_once $handlerPath;
    $leadHandler = new $handlerClass($leadObject, $current_user, $adb, $log);
    $leadInfo = vtws_retrieve($entityValues['leadId'], $current_user);
    foreach ($availableModules as $entityName) {
        if (!isset($entityValues['entities'][$entityName])) {
            continue;
        }
        $tabid = getTabid($entityName);
        $entityvalue = $entityValues['entities'][$entityName];
        $entityObject = VtigerWebserviceObject::fromName($adb, $entityvalue['name']);
        $handlerPath = $entityObject->getHandlerPath();
        $handlerClass = $entityObject->getHandlerClass();
        require_once $handlerPath;
        $entityHandler = new $handlerClass($entityObject, $current_user, $adb, $log);
        $entityObjectValues = array();
        $entityObjectValues['assigned_user_id'] = $entityValues['assignedTo'];
        $entityObjectValues = vtws_populateConvertLeadEntities($entityvalue, $entityObjectValues, $entityHandler, $leadHandler, $leadInfo);
        if ($entityvalue['name'] == 'Potentials') {
            if (!empty($entityIds['Accounts'])) {
                $entityObjectValues['related_to'] = $entityIds['Accounts'];
            } else {
                $entityObjectValues['related_to'] = $entityIds['Contacts'];
            }
        }
        if ($entityvalue['name'] == 'Contacts') {
            if (!empty($entityIds['Accounts'])) {
                $entityObjectValues['account_id'] = $entityIds['Accounts'];
            }
        }
        echo "<tr><td colspan=3><b>" . getTranslatedString($entityvalue['name'], $entityvalue['name']) . "</b></td></tr>";
        echo "<tr><td><b>" . getTranslatedString('FieldName', 'Settings') . "</b></td><td><b>" . getTranslatedString('LBL_MANDATORY_FIELD', 'Settings') . "</b></td><td><b>" . getTranslatedString('Values', 'Settings') . "</b></td></tr>";
        foreach ($entityObjectValues as $fname => $value) {
            if ($fname == 'create' or $fname == 'name') {
                continue;
            }
            echo "<tr>";
            $frs = $adb->pquery('select fieldlabel,typeofdata from vtiger_field where tabid=? and fieldname=?', array($tabid, $fname));
            $finfo = $adb->fetch_array($frs);
            $flbl = getTranslatedString($finfo['fieldlabel'], $entityName);
            echo "<td>{$flbl} ({$fname})</td>";
            echo "<td>" . (strpos($finfo['typeofdata'], '~M') > 0 ? $yes : $no) . "</td>";
            echo "<td>{$value}</td>";
            echo "</tr>";
        }
    }
    echo "</table>";
}
Exemple #15
0
function vtws_convertlead($leadId, $assignedTo, $accountName, $avoidPotential, $potential, $user)
{
    global $adb, $log;
    if (empty($assignedTo)) {
        $assignedTo = vtws_getWebserviceEntityId('Users', $user->id);
    }
    if ((bool) $avoidPotential !== true) {
        try {
            if (empty($potential)) {
                throw new WebServiceException(WebServiceErrorCode::$INVALID_POTENTIAL_FOR_CONVERT_LEAD, "Invalid lead information given for potential");
            }
        } catch (Zend_Json_Exception $e) {
            throw new WebServiceException(WebServiceErrorCode::$INVALID_POTENTIAL_FOR_CONVERT_LEAD, "Potentail information given is not in valid JSON format");
        }
    }
    $currencyInfo = getCurrencySymbolandCRate($user->currency_id);
    $rate = $currencyInfo['rate'];
    if ($potential['amount'] != '') {
        $potential['amount'] = convertToDollar($potential['amount'], $rate);
    }
    $leadObject = VtigerWebserviceObject::fromName($adb, 'Leads');
    $handlerPath = $leadObject->getHandlerPath();
    $handlerClass = $leadObject->getHandlerClass();
    require_once $handlerPath;
    $leadHandler = new $handlerClass($leadObject, $user, $adb, $log);
    $leadHandler->getMeta()->retrieveMeta();
    $leadInfo = vtws_retrieve($leadId, $user);
    $sql = "select converted from vtiger_leaddetails where converted = 1 and leadid=?";
    $leadIdComponents = vtws_getIdComponents($leadId);
    $result = $adb->pquery($sql, array($leadIdComponents[1]));
    if ($result === false) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount > 0) {
        throw new WebServiceException(WebServiceErrorCode::$LEAD_ALREADY_CONVERTED, "Lead is already converted");
    }
    $customFieldMapping = vtws_getConvertLeadFieldMapping();
    //check if accountName given in request is empty then default to lead company field.
    if (empty($accountName)) {
        $accountName = $leadInfo['company'];
    }
    $sql = "select vtiger_account.accountid from vtiger_account\n\t\tleft join vtiger_crmentity on vtiger_account.accountid = vtiger_crmentity.crmid\n\t\twhere vtiger_crmentity.deleted=0 and vtiger_account.accountname = ?";
    $result = $adb->pquery($sql, array($accountName));
    if ($result === false) {
        throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
    }
    $rowCount = $adb->num_rows($result);
    if ($rowCount != 0 && vtlib_isModuleActive('Accounts') === true) {
        $crmId = $adb->query_result($result, 0, "accountid");
        $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $crmId);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Account");
        }
        //Retrieve the lead related products and relate them with this new account
        $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $crmId, "Accounts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Account");
        }
        $status = vtws_saveLeadRelations($leadIdComponents[1], $crmId, "Accounts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Account");
        }
    } else {
        //don't create account if no company name is given in input and lead doest not have
        // company field populated, DONE TO RESPECT B2C model.
        if (!empty($accountName)) {
            $accountObject = VtigerWebserviceObject::fromName($adb, 'Accounts');
            $handlerPath = $accountObject->getHandlerPath();
            $handlerClass = $accountObject->getHandlerClass();
            require_once $handlerPath;
            $accountHandler = new $handlerClass($accountObject, $user, $adb, $log);
            if ($accountHandler->getMeta()->hasWriteAccess()) {
                $account = array();
                if (!empty($leadInfo["annualrevenue"])) {
                    $account['annual_revenue'] = $leadInfo["annualrevenue"];
                }
                if (!empty($leadInfo["noofemployees"])) {
                    $account['employees'] = $leadInfo["noofemployees"];
                }
                $account['accountname'] = $accountName;
                $account['industry'] = $leadInfo["industry"];
                $account['phone'] = $leadInfo["phone"];
                $account['fax'] = $leadInfo["fax"];
                $account['rating'] = $leadInfo["rating"];
                $account['email1'] = $leadInfo["email"];
                $account['website'] = $leadInfo["website"];
                $account['bill_city'] = $leadInfo["city"];
                $account['bill_code'] = $leadInfo["code"];
                $account['bill_country'] = $leadInfo["country"];
                $account['bill_state'] = $leadInfo["state"];
                $account['bill_street'] = $leadInfo["lane"];
                $account['bill_pobox'] = $leadInfo["pobox"];
                $account['ship_city'] = $leadInfo["city"];
                $account['ship_code'] = $leadInfo["code"];
                $account['ship_country'] = $leadInfo["country"];
                $account['ship_state'] = $leadInfo["state"];
                $account['ship_street'] = $leadInfo["lane"];
                $account['ship_pobox'] = $leadInfo["pobox"];
                $account['assigned_user_id'] = $assignedTo;
                $account['description'] = $leadInfo['description'];
                $leadFields = $leadHandler->getMeta()->getModuleFields();
                $accountFields = $accountHandler->getMeta()->getModuleFields();
                foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
                    $accountFieldId = $mappingDetails['Accounts'];
                    if (empty($accountFieldId)) {
                        continue;
                    }
                    $accountField = vtws_getFieldfromFieldId($accountFieldId, $accountFields);
                    if ($accountField == null) {
                        //user doesn't have access so continue.TODO update even if user doesn't have access
                        continue;
                    }
                    $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
                    if ($leadField == null) {
                        //user doesn't have access so continue.TODO update even if user doesn't have access
                        continue;
                    }
                    $leadFieldName = $leadField->getFieldName();
                    $accountFieldName = $accountField->getFieldName();
                    $account[$accountFieldName] = $leadInfo[$leadFieldName];
                }
                $account = vtws_create('Accounts', $account, $user);
                $accountIdComponents = vtws_getIdComponents($account['id']);
                $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $accountIdComponents[1]);
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Account");
                }
                //Retrieve the lead related products and relate them with this new account
                $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $accountIdComponents[1], "Accounts");
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Account");
                }
                $status = vtws_saveLeadRelations($leadIdComponents[1], $accountIdComponents[1], "Accounts");
                if ($status === false) {
                    throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Account");
                }
            }
        }
    }
    $contactObject = VtigerWebserviceObject::fromName($adb, 'Contacts');
    $handlerPath = $contactObject->getHandlerPath();
    $handlerClass = $contactObject->getHandlerClass();
    require_once $handlerPath;
    $contactHandler = new $handlerClass($contactObject, $user, $adb, $log);
    if (!empty($crmId)) {
        $accountId = $crmId;
        $webserviceAccountId = vtws_getWebserviceEntityId('Accounts', $crmId);
    } elseif (!empty($accountName)) {
        if (count($accountIdComponents) === 2) {
            $accountId = $accountIdComponents[1];
            $webserviceAccountId = vtws_getId($accountIdComponents[0], $accountIdComponents[1]);
        }
    } else {
        $accountId = '';
        $webserviceAccountId = '';
    }
    if ($contactHandler->getMeta()->hasWriteAccess()) {
        $contact = array();
        $contact['assigned_user_id'] = $assignedTo;
        $contact['description'] = $leadInfo['description'];
        $contact['account_id'] = $webserviceAccountId;
        $contact['salutationtype'] = $leadInfo["salutationtype"];
        $contact['firstname'] = $leadInfo["firstname"];
        $contact['lastname'] = $leadInfo["lastname"];
        $contact['email'] = $leadInfo["email"];
        $contact['phone'] = $leadInfo["phone"];
        $contact['mobile'] = $leadInfo["mobile"];
        $contact['title'] = $leadInfo["designation"];
        $contact['fax'] = $leadInfo["fax"];
        $contact['yahooid'] = $leadInfo['yahooid'];
        $contact['leadsource'] = $leadInfo['leadsource'];
        $contact['mailingcity'] = $leadInfo["city"];
        $contact['mailingzip'] = $leadInfo["code"];
        $contact['mailingcountry'] = $leadInfo["country"];
        $contact['mailingstate'] = $leadInfo["state"];
        $contact['mailingstreet'] = $leadInfo["lane"];
        $contact['mailingpobox'] = $leadInfo["pobox"];
        $leadFields = $leadHandler->getMeta()->getModuleFields();
        $contactFields = $contactHandler->getMeta()->getModuleFields();
        foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
            $contactFieldId = $mappingDetails['Contacts'];
            if (empty($contactFieldId)) {
                continue;
            }
            $contactField = vtws_getFieldfromFieldId($contactFieldId, $contactFields);
            if ($contactField == null) {
                //user doesn't have access so continue.TODO update even if user doesn't have access
                continue;
            }
            $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
            if ($leadField == null) {
                //user doesn't have access so continue.TODO update even if user doesn't have access
                continue;
            }
            $leadFieldName = $leadField->getFieldName();
            $contactFieldName = $contactField->getFieldName();
            $contact[$contactFieldName] = $leadInfo[$leadFieldName];
        }
        $contact = vtws_create('Contacts', $contact, $user);
        $contactIdComponents = vtws_getIdComponents($contact['id']);
        $contactId = $contactIdComponents[1];
        //To convert relates Activites and Email.
        $status = vtws_getRelatedActivities($leadIdComponents[1], $accountId, $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Related Activities to the Contact");
        }
        $status = vtws_getRelatedNotesAttachments($leadIdComponents[1], $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Documents to the Contact");
        }
        //Retrieve the lead related products and relate them with this new contact
        $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $contactIdComponents[1], "Contacts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Contact");
        }
        $status = vtws_saveLeadRelations($leadIdComponents[1], $contactIdComponents[1], "Contacts");
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Contact");
        }
        //Retrieve the lead related Campaigns and relate them with this new contact --Minnie
        $status = vtws_saveLeadRelatedCampaigns($leadIdComponents[1], $contactIdComponents[1]);
        if ($status === false) {
            throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Related Campaigns to the Contact");
        }
    }
    if ((bool) $avoidPotential != true) {
        $potentialObject = VtigerWebserviceObject::fromName($adb, 'Potentials');
        $handlerPath = $potentialObject->getHandlerPath();
        $handlerClass = $potentialObject->getHandlerClass();
        require_once $handlerPath;
        $potentialHandler = new $handlerClass($potentialObject, $user, $adb, $log);
        if ($potentialHandler->getMeta()->hasWriteAccess()) {
            if (!empty($webserviceAccountId)) {
                $relatedTo = $webserviceAccountId;
            } else {
                if (!empty($contactId)) {
                    $relatedTo = vtws_getWebserviceEntityId('Contacts', $contactId);
                }
            }
            $potential['assigned_user_id'] = $assignedTo;
            $potential['description'] = $leadInfo['description'];
            $potential['related_to'] = $relatedTo;
            $potential['leadsource'] = $leadInfo['leadsource'];
            $leadFields = $leadHandler->getMeta()->getModuleFields();
            $potentialFields = $potentialHandler->getMeta()->getModuleFields();
            foreach ($customFieldMapping as $leadFieldId => $mappingDetails) {
                $potentialFieldId = $mappingDetails['Potentials'];
                if (empty($potentialFieldId)) {
                    continue;
                }
                $potentialField = vtws_getFieldfromFieldId($potentialFieldId, $potentialFields);
                if ($potentialField == null) {
                    //user doesn't have access so continue.TODO update even if user doesn't have access
                    continue;
                }
                $leadField = vtws_getFieldfromFieldId($leadFieldId, $leadFields);
                if ($leadField == null) {
                    //user doesn't have access so continue.TODO update even if user doesn't have access
                    continue;
                }
                $leadFieldName = $leadField->getFieldName();
                $potentialFieldName = $potentialField->getFieldName();
                $potential[$potentialFieldName] = $leadInfo[$leadFieldName];
            }
            $potential = vtws_create('Potentials', $potential, $user);
            $potentialIdComponents = vtws_getIdComponents($potential['id']);
            if (!empty($accountId) && !empty($contactId)) {
                $sql = "insert into vtiger_contpotentialrel values(?,?)";
                $result = $adb->pquery($sql, array($contactId, $potentialIdComponents[1]));
                if ($result === false) {
                    throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_CREATE_RELATION, "Failed to related Contact with the Potential");
                }
            }
            //Retrieve the lead related products and relate them with this new potential
            $status = vtws_saveLeadRelatedProducts($leadIdComponents[1], $potentialIdComponents[1], "Potentials");
            if ($status === false) {
                throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move related Products to the Potential");
            }
            $status = vtws_saveLeadRelations($leadIdComponents[1], $potentialIdComponents[1], "Potentials");
            if ($status === false) {
                throw new WebServiceException(WebServiceErrorCode::$LEAD_RELATED_UPDATE_FAILED, "Failed to move Records to the Potential");
            }
            $potentialId = $potentialIdComponents[1];
        }
    }
    //Updating the converted status
    if ($accountId != '' || $contactId != '') {
        $sql = "UPDATE vtiger_leaddetails SET converted = 1 where leadid=?";
        $result = $adb->pquery($sql, array($leadIdComponents[1]));
        if ($result === false) {
            throw new WebServiceException(WebServiceErrorCode::$FAILED_TO_MARK_CONVERTED, "Failed mark lead converted");
        }
        //updating the campaign-lead relation --Minnie
        $sql = "delete from vtiger_campaignleadrel where leadid=?";
        $adb->pquery($sql, array($leadIdComponents[1]));
    }
    $result = array('leadId' => $leadId);
    if (!empty($webserviceAccountId)) {
        $result['accountId'] = $webserviceAccountId;
    } else {
        $result['accountId'] = '';
    }
    if (!empty($contactId)) {
        $result['contactId'] = vtws_getWebserviceEntityId('Contacts', $contactId);
    } else {
        $result['contactId'] = '';
    }
    if (!empty($potentialId)) {
        $result['potentialId'] = $potential['id'];
    } else {
        $result['potentialId'] = '';
    }
    return $result;
}