Esempio n. 1
0
 function process(Mobile_API_Request $request)
 {
     $current_user = vglobal('current_user');
     $current_user = $this->getActiveUser();
     $records = $request->get('records');
     if (empty($records)) {
         $records = array($request->get('record'));
     } else {
         $records = Zend_Json::decode($records);
     }
     $deleted = array();
     foreach ($records as $record) {
         try {
             vtws_delete($record, $current_user);
             $result = true;
         } catch (Exception $e) {
             $result = false;
         }
         $deleted[$record] = $result;
     }
     $response = new Mobile_API_Response();
     $response->setResult(array('deleted' => $deleted));
     return $response;
 }
 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;
 }
Esempio n. 3
0
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;
}
Esempio n. 4
0
    public function put($recordDetails,$user){
        $this->user = $user;
        $recordDetails = $this->syncToNativeFormat($recordDetails);
        $createdRecords = $recordDetails['created'];
        $updatedRecords = $recordDetails['updated'];
        $deletedRecords = $recordDetails['deleted'];

        if(count($createdRecords)>0){
            $createdRecords = $this->translateReferenceFieldNamesToIds($createdRecords,$user);
			$createdRecords = $this->fillNonExistingMandatoryPicklistValues($createdRecords);
		}
        foreach($createdRecords as $index=>$record){
            $createdRecords[$index] = vtws_create($record['module'], $record, $this->user);
        }
        
        if(count($updatedRecords) >0){
            $updatedRecords = $this->translateReferenceFieldNamesToIds($updatedRecords,$user);
        }
        
        $crmIds = array();
        foreach($updatedRecords as $index=>$record){
            $webserviceRecordId = $record["id"];
            $recordIdComp = vtws_getIdComponents($webserviceRecordId);
            $crmIds[] = $recordIdComp[1];

        }
        $assignedRecordIds = wsapp_checkIfRecordsAssignToUser($crmIds, $this->user->id);
        foreach($updatedRecords as $index=>$record){
            $webserviceRecordId = $record["id"];
            $recordIdComp = vtws_getIdComponents($webserviceRecordId);
            if(in_array($recordIdComp[1], $assignedRecordIds))
            {
                $updatedRecords[$index] = vtws_revise($record, $this->user);
            }
            else{
                $this->assignToChangedRecords[$index] = $record;
            }
        }
        $hasDeleteAccess = null;
        $deletedCrmIds = array();
        foreach($deletedRecords as $index=>$record){
            $webserviceRecordId = $record;
            $recordIdComp = vtws_getIdComponents($webserviceRecordId);
            $deletedCrmIds[] = $recordIdComp[1];
        }
        $assignedDeletedRecordIds = wsapp_checkIfRecordsAssignToUser($deletedCrmIds, $this->user->id);
        foreach($deletedRecords as $index=>$record){
            $idComp = vtws_getIdComponents($record);
            if(empty ($hasDeleteAccess)){
             $handler = vtws_getModuleHandlerFromId($idComp[0], $this->user);
             $meta = $handler->getMeta();
             $hasDeleteAccess = $meta->hasDeleteAccess();
            }
            if($hasDeleteAccess){
                if(in_array($idComp[1], $assignedDeletedRecordIds)){
                    vtws_delete($record, $this->user);
                }
            }
        }
        $recordDetails['created'] = $createdRecords;
        $recordDetails['updated'] = $updatedRecords;
        $recordDetails['deleted'] = $deletedRecords;
		return $this->nativeToSyncFormat($recordDetails);
    }
Esempio n. 5
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;
 }
 public function put($recordDetails, $user)
 {
     $log = vglobal('log');
     $this->user = $user;
     $recordDetails = $this->syncToNativeFormat($recordDetails);
     $createdRecords = $recordDetails['created'];
     $updatedRecords = $recordDetails['updated'];
     $deletedRecords = $recordDetails['deleted'];
     if (count($createdRecords) > 0) {
         $createdRecords = $this->translateReferenceFieldNamesToIds($createdRecords, $user);
         $createdRecords = $this->fillNonExistingMandatoryPicklistValues($createdRecords);
         $createdRecords = $this->fillMandatoryFields($createdRecords, $user);
     }
     foreach ($createdRecords as $index => $record) {
         $createdRecords[$index] = vtws_create($record['module'], $record, $this->user);
     }
     if (count($updatedRecords) > 0) {
         $updatedRecords = $this->translateReferenceFieldNamesToIds($updatedRecords, $user);
     }
     $crmIds = array();
     foreach ($updatedRecords as $index => $record) {
         $webserviceRecordId = $record["id"];
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         $crmIds[] = $recordIdComp[1];
     }
     $assignedRecordIds = array();
     if ($this->isClientUserSyncType()) {
         $assignedRecordIds = wsapp_checkIfRecordsAssignToUser($crmIds, $this->user->id);
         // To check if the record assigned to group
         if ($this->isClientUserAndGroupSyncType()) {
             $getUserGroups = new GetUserGroups();
             $getUserGroups->getAllUserGroups($this->user->id);
             $groupIds = $getUserGroups->user_groups;
             if (!empty($groupIds)) {
                 $groupRecordId = wsapp_checkIfRecordsAssignToUser($crmIds, $groupIds);
                 $assignedRecordIds = array_merge($assignedRecordIds, $groupRecordId);
             }
         }
         // End
     }
     foreach ($updatedRecords as $index => $record) {
         $webserviceRecordId = $record["id"];
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         try {
             if (in_array($recordIdComp[1], $assignedRecordIds)) {
                 $updatedRecords[$index] = vtws_revise($record, $this->user);
             } else {
                 if (!$this->isClientUserSyncType()) {
                     $updatedRecords[$index] = vtws_revise($record, $this->user);
                 } else {
                     $this->assignToChangedRecords[$index] = $record;
                 }
             }
         } catch (Exception $e) {
             continue;
         }
         // Added to handle duplication
         if ($record['duplicate']) {
             $updatedRecords[$index]['duplicate'] = true;
         }
         // End
     }
     $hasDeleteAccess = null;
     $deletedCrmIds = array();
     foreach ($deletedRecords as $index => $record) {
         $webserviceRecordId = $record;
         $recordIdComp = vtws_getIdComponents($webserviceRecordId);
         $deletedCrmIds[] = $recordIdComp[1];
     }
     $assignedDeletedRecordIds = wsapp_checkIfRecordsAssignToUser($deletedCrmIds, $this->user->id);
     // To get record id's assigned to group of the current user
     if ($this->isClientUserAndGroupSyncType()) {
         if (!empty($groupIds)) {
             foreach ($groupIds as $group) {
                 $groupRecordId = wsapp_checkIfRecordsAssignToUser($deletedCrmIds, $group);
                 $assignedDeletedRecordIds = array_merge($assignedDeletedRecordIds, $groupRecordId);
             }
         }
     }
     // End
     foreach ($deletedRecords as $index => $record) {
         $idComp = vtws_getIdComponents($record);
         if (empty($hasDeleteAccess)) {
             $handler = vtws_getModuleHandlerFromId($idComp[0], $this->user);
             $meta = $handler->getMeta();
             $hasDeleteAccess = $meta->hasDeleteAccess();
         }
         if ($hasDeleteAccess) {
             if (in_array($idComp[1], $assignedDeletedRecordIds)) {
                 try {
                     vtws_delete($record, $this->user);
                 } catch (Exception $e) {
                     continue;
                 }
             }
         }
     }
     $recordDetails['created'] = $createdRecords;
     $recordDetails['updated'] = $updatedRecords;
     $recordDetails['deleted'] = $deletedRecords;
     return $this->nativeToSyncFormat($recordDetails);
 }
Esempio n. 7
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;
}