Exemplo n.º 1
0
 public static function synchronize($ownerID, array $entityFields = null)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     $query = new Query(DealStageHistoryTable::getEntity());
     $query->addSelect('START_DATE');
     $query->addSelect('END_DATE');
     $query->addSelect('RESPONSIBLE_ID');
     $query->addFilter('=OWNER_ID', $ownerID);
     $query->setLimit(1);
     $dbResult = $query->exec();
     $first = $dbResult->fetch();
     if (!is_array($first)) {
         return false;
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('ASSIGNED_BY_ID', 'BEGINDATE', 'CLOSEDATE'));
         $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null;
         if (!is_array($entityFields)) {
             return false;
         }
     }
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     $beginDate = isset($entityFields['BEGINDATE']) ? $entityFields['BEGINDATE'] : '';
     /** @var Date $startDate */
     $startDate = new Date($beginDate);
     $closeDate = isset($entityFields['CLOSEDATE']) ? $entityFields['CLOSEDATE'] : '';
     /** @var Date $endDate */
     $endDate = $closeDate !== '' ? new Date($closeDate) : new Date('9999-12-31', 'Y-m-d');
     if ($startDate->getTimestamp() === $first['START_DATE']->getTimestamp() && $endDate->getTimestamp() === $first['END_DATE']->getTimestamp() && $responsibleID === (int) $first['RESPONSIBLE_ID']) {
         return false;
     }
     DealStageHistoryTable::synchronize($ownerID, array('START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID));
     return true;
 }
Exemplo n.º 2
0
 /**
  * Recounts involvement and activity score for selected day
  * @param Type\Date $day
  */
 protected static function recountDailyInvolvement(Type\Date $day = null)
 {
     // should be called only after recount*ActiveUsers
     // because we need ACTIVE_USERS already set up
     $departments = array();
     if ($day === null) {
         $day = new Type\Date();
     }
     // users' departments
     $usersDepartments = static::getUsersDepartments();
     // add "company" for each user
     foreach ($usersDepartments as &$_usersDepartments) {
         $_usersDepartments[] = 0;
     }
     // count
     $result = UserDayTable::getList(array('filter' => array('=DAY' => \ConvertTimeStamp($day->getTimestamp(), 'SHORT'))));
     while ($row = $result->fetch()) {
         $invCount = 0;
         if (!isset($usersDepartments[$row['USER_ID']])) {
             // skip deleted users
             continue;
         }
         foreach ($row as $k => $v) {
             // skip non-activity fields
             if ($k == 'USER_ID' || $k == 'DAY') {
                 continue;
             }
             // initialize
             foreach ($usersDepartments[$row['USER_ID']] as $deptId) {
                 if (!isset($departments[$deptId][$k])) {
                     $departments[$deptId][$k] = 0;
                 }
             }
             // summarize
             foreach ($usersDepartments[$row['USER_ID']] as $deptId) {
                 $departments[$deptId][$k] += $v;
             }
             // increment involvement count
             if ($k != 'TOTAL' && $v > 0) {
                 ++$invCount;
             }
         }
         // check involvement
         if ($invCount >= static::INVOLVEMENT_SERVICE_COUNT) {
             foreach ($usersDepartments[$row['USER_ID']] as $deptId) {
                 if (!isset($departments[$deptId]['INVOLVED'])) {
                     $departments[$deptId]['INVOLVED'] = 0;
                 }
                 ++$departments[$deptId]['INVOLVED'];
             }
         }
     }
     // normalize involved count
     foreach ($departments as &$_department) {
         if (!isset($_department['INVOLVED'])) {
             $_department['INVOLVED'] = 0;
         }
     }
     // update db
     foreach ($departments as $deptId => $activity) {
         $activity['INVOLVEMENT'] = new SqlExpression('CASE WHEN ?# > 0 THEN ROUND((?i / ?# * 100), 0) ELSE 0 END', 'ACTIVE_USERS', $activity['INVOLVED'], 'ACTIVE_USERS');
         unset($activity['INVOLVED']);
         DepartmentDayTable::update(array('DEPT_ID' => $deptId, 'DAY' => $day), $activity);
     }
 }
Exemplo n.º 3
0
 public static function getMissedPeriods(array $stats, $dateStart, $dateFinish)
 {
     $missedPeriods = array();
     $datePrevoius = false;
     $checkDate = new Date($dateStart);
     $dateCurrent = new Date($dateStart);
     $dateFinish = new Date($dateFinish);
     while ($dateCurrent->getTimestamp() <= $dateFinish->getTimestamp()) {
         if (!array_key_exists($dateCurrent->toString(), $stats)) {
             if (!$datePrevoius || $dateCurrent->getTimestamp() >= $checkDate->getTimestamp()) {
                 $missedPeriods[] = array($dateCurrent->toString(), $dateCurrent->toString());
                 $checkDate = new Date($dateCurrent->toString());
                 $checkDate->add("+" . YandexDirectLive::MAX_STAT_DAYS_DELTA . " days");
                 $datePrevoius = true;
             } else {
                 $missedPeriods[count($missedPeriods) - 1][1] = $dateCurrent->toString();
             }
         } else {
             $datePrevoius = false;
         }
         $dateCurrent->add("+1 days");
     }
     return $missedPeriods;
 }
Exemplo n.º 4
0
 public function createInvoices(array $params)
 {
     $count = isset($params['COUNT']) ? (int) $params['COUNT'] : 0;
     if ($count <= 0) {
         return;
     }
     $sum = isset($params['SUM']) ? (int) $params['SUM'] : 0;
     if ($sum <= 0) {
         return;
     }
     $dealID = isset($params['DEAL_ID']) ? (int) $params['DEAL_ID'] : 0;
     $companyID = isset($params['COMPANY_ID']) ? (int) $params['COMPANY_ID'] : 0;
     $contactID = isset($params['CONTACT_ID']) ? (int) $params['CONTACT_ID'] : 0;
     $userIDs = isset($params['USER_IDS']) && is_array($params['USER_IDS']) ? $params['USER_IDS'] : array();
     if (empty($userIDs)) {
         $userIDs[] = \CCrmSecurityHelper::GetCurrentUserID();
     }
     $prefix = isset($params['PREFIX']) ? $params['PREFIX'] : '';
     if ($prefix === '') {
         $prefix = $this->id;
     }
     $date = isset($params['DATE']) ? $params['DATE'] : null;
     if (!$date) {
         $date = $date = new Date();
     }
     $maxDateOffset = isset($params['MAX_DATE_OFFSET']) ? (int) $params['MAX_DATE_OFFSET'] : 0;
     $dateFormat = Date::convertFormatToPhp(FORMAT_DATE);
     $dateTimeFormat = Date::convertFormatToPhp(FORMAT_DATETIME);
     $isWon = isset($params['IS_WON']) ? $params['IS_WON'] : false;
     if ($isWon) {
         $totalSum = $sum;
     } else {
         $totalSum = $sum - mt_rand((int) ($sum / 3), $sum);
     }
     $entity = new \CCrmInvoice(false);
     $invoiceSum = (int) $totalSum / $count;
     $totalInvoiceSum = 0;
     for ($i = 1; $i <= $count; $i++) {
         if ($i == $count) {
             $invoiceSum = $totalSum - $totalInvoiceSum;
         }
         $totalInvoiceSum += $invoiceSum;
         $time = DateTime::createFromTimestamp($date->getTimestamp());
         if ($maxDateOffset > 0) {
             $time->add(mt_rand(0, $maxDateOffset) . ' days');
         }
         $time->setTime(mt_rand(8, 20), mt_rand(0, 59), 0);
         $siteTime = $time->format($dateTimeFormat);
         $siteDate = $time->format($dateFormat);
         \CCrmOwnerType::GetCaption(\CCrmOwnerType::Company, $companyID, false);
         $companyInfo = self::getCompanyInfo($companyID);
         $contactInfo = self::getContactInfo($contactID);
         $fields = array('ORDER_TOPIC' => "{$prefix} invoice # {$i}", 'STATUS_ID' => $isWon ? 'P' : 'N', 'DATE_INSERT' => $siteTime, 'DATE_BILL' => $siteDate, 'RESPONSIBLE_ID' => self::getRandomItem($userIDs), 'UF_DEAL_ID' => $dealID, 'UF_COMPANY_ID' => $companyID, 'UF_CONTACT_ID' => $contactID, 'PERSON_TYPE_ID' => 1, 'PAY_SYSTEM_ID' => 1, 'INVOICE_PROPERTIES' => array(10 => $companyInfo['TITLE'], 11 => $companyInfo['FULL_ADDRESS'], 12 => $contactInfo['FULL_NAME'], 13 => $contactInfo['EMAIL'], 14 => $contactInfo['PHONE']), 'PRODUCT_ROWS' => array(array('ID' => 0, 'PRODUCT_NAME' => "{$prefix} product", 'QUANTITY' => 1, 'PRICE' => $invoiceSum, 'PRODUCT_ID' => 0, 'CUSTOMIZED' => 'Y')));
         $ID = $entity->Add($fields);
     }
 }
 /**
  * @return boolean
  */
 public static function synchronize($ownerID, array $entityFields = null)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('STAGE_ID', 'ASSIGNED_BY_ID', 'BEGINDATE', 'CLOSEDATE', 'OPPORTUNITY', 'CURRENCY_ID'));
         $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null;
         if (!is_array($entityFields)) {
             return false;
         }
     }
     $stageID = isset($entityFields['STAGE_ID']) ? $entityFields['STAGE_ID'] : '';
     $semanticID = \CCrmDeal::GetSemanticID($stageID);
     $isLost = PhaseSemantics::isLost($semanticID);
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     /** @var Date $startDate */
     $startDate = self::parseDateString(isset($entityFields['BEGINDATE']) ? $entityFields['BEGINDATE'] : '');
     if ($startDate === null) {
         $startDate = new Date();
     }
     /** @var Date $endDate */
     $endDate = self::parseDateString(isset($entityFields['CLOSEDATE']) ? $entityFields['CLOSEDATE'] : '');
     if ($endDate === null) {
         $endDate = new Date('9999-12-31', 'Y-m-d');
     }
     $sum = isset($entityFields['OPPORTUNITY']) ? (double) $entityFields['OPPORTUNITY'] : 0.0;
     $currencyID = isset($entityFields['CURRENCY_ID']) ? $entityFields['CURRENCY_ID'] : '';
     if ($currencyID === '') {
         $currencyID = \CCrmCurrency::GetBaseCurrencyID();
     }
     $accountCurrencyID = \CCrmCurrency::GetAccountCurrencyID();
     $sumData = \CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => $currencyID, 'SUM' => $sum));
     if (is_array($sumData)) {
         $sum = (double) $sumData['ACCOUNT_SUM'];
     }
     $latest = self::getLatest($ownerID);
     if (!is_array($latest)) {
         if ($semanticID === PhaseSemantics::SUCCESS) {
             //Creation of stub for successfully completed entity without invoices
             self::innerRegister(array('OWNER_ID' => $ownerID, 'CREATED_DATE' => new Date(), 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID, 'STAGE_SEMANTIC_ID' => PhaseSemantics::SUCCESS, 'STAGE_ID' => $stageID, 'IS_LOST' => 'N', 'CURRENCY_ID' => $accountCurrencyID, 'INVOICE_SUM' => 0.0, 'INVOICE_QTY' => 0, 'TOTAL_INVOICE_SUM' => 0.0, 'TOTAL_INVOICE_QTY' => 0, 'TOTAL_SUM' => $sum));
         }
         return true;
     }
     if ($startDate->getTimestamp() === $latest['START_DATE']->getTimestamp() && $endDate->getTimestamp() === $latest['END_DATE']->getTimestamp() && $responsibleID === (int) $latest['RESPONSIBLE_ID'] && $stageID === $latest['STAGE_ID'] && $semanticID === $latest['STAGE_SEMANTIC_ID'] && $sum === (double) $latest['TOTAL_SUM']) {
         return false;
     }
     if ($semanticID !== $latest['STAGE_SEMANTIC_ID'] && $latest['STAGE_SEMANTIC_ID'] === PhaseSemantics::SUCCESS && (int) $latest['INVOICE_QTY'] === 0) {
         //Clean up stub for successfully completed entity without invoices
         DealInvoiceStatisticsTable::delete(array('OWNER_ID' => $ownerID, 'CREATED_DATE' => $latest['CREATED_DATE']));
     } else {
         DealInvoiceStatisticsTable::synchronize($ownerID, array('START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID, 'STAGE_SEMANTIC_ID' => $semanticID, 'STAGE_ID' => $stageID, 'IS_LOST' => $isLost ? 'Y' : 'N', 'TOTAL_SUM' => $sum));
     }
     return true;
 }
Exemplo n.º 6
0
 /**
  * @return void
  */
 public static function register($ownerID, array $entityFields = null)
 {
     if (!is_int($ownerID)) {
         $ownerID = (int) $ownerID;
     }
     if ($ownerID <= 0) {
         throw new Main\ArgumentException('Owner ID must be greater than zero.', 'ownerID');
     }
     if (!is_array($entityFields)) {
         $dbResult = \CCrmDeal::GetListEx(array(), array('=ID' => $ownerID, 'CHECK_PERMISSIONS' => 'N'), false, false, array('STAGE_ID', 'ASSIGNED_BY_ID', 'BEGINDATE', 'CLOSEDATE', 'CURRENCY_ID', 'OPPORTUNITY', 'UF_*'));
         $entityFields = is_object($dbResult) ? $dbResult->Fetch() : null;
         if (!is_array($entityFields)) {
             return;
         }
     }
     $bindingMap = self::getSlotBindingMap();
     $stageID = isset($entityFields['STAGE_ID']) ? $entityFields['STAGE_ID'] : '';
     $semanticID = \CCrmDeal::GetSemanticID($stageID);
     $isLost = PhaseSemantics::isLost($semanticID);
     $isFinalized = PhaseSemantics::isFinal($semanticID);
     $responsibleID = isset($entityFields['ASSIGNED_BY_ID']) ? (int) $entityFields['ASSIGNED_BY_ID'] : 0;
     /** @var Date $startDate */
     $startDate = self::parseDateString(isset($entityFields['BEGINDATE']) ? $entityFields['BEGINDATE'] : '');
     if ($startDate === null || $startDate->getTimestamp() === false) {
         $startDate = isset($entityFields['DATE_CREATE']) ? self::parseDateString($entityFields['DATE_CREATE']) : null;
         if ($startDate === null || $startDate->getTimestamp() === false) {
             $startDate = new Date();
         }
     }
     /** @var Date $endDate */
     $endDate = self::parseDateString(isset($entityFields['CLOSEDATE']) ? $entityFields['CLOSEDATE'] : '');
     if ($endDate === null || $endDate->getTimestamp() === false) {
         $endDate = new Date('9999-12-31', 'Y-m-d');
     }
     $date = $isFinalized ? $endDate : $startDate;
     $day = (int) $date->format('d');
     $month = (int) $date->format('m');
     $quarter = $month <= 3 ? 1 : ($month <= 6 ? 2 : ($month <= 9 ? 3 : 4));
     $year = (int) $date->format('Y');
     $currencyID = isset($entityFields['CURRENCY_ID']) ? $entityFields['CURRENCY_ID'] : '';
     $accountingCurrencyID = \CCrmCurrency::GetAccountCurrencyID();
     $sum = isset($entityFields['OPPORTUNITY']) ? (double) $entityFields['OPPORTUNITY'] : 0.0;
     $binding = $bindingMap->get('SUM_TOTAL');
     if ($binding === null) {
         $total = isset($entityFields['OPPORTUNITY']) ? (double) $entityFields['OPPORTUNITY'] : 0.0;
     } else {
         $bindingFieldName = $binding->getFieldName();
         if ($bindingFieldName === '') {
             $bindingFieldName = 'OPPORTUNITY';
         }
         $total = isset($entityFields[$bindingFieldName]) ? (double) $entityFields[$bindingFieldName] : 0.0;
         if ($bindingFieldName !== 'OPPORTUNITY' && $binding->getOption('ADD_PRODUCT_ROW_SUM') === 'Y') {
             $total += $sum;
         }
     }
     if ($currencyID !== $accountingCurrencyID) {
         $accData = \CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => $currencyID, 'SUM' => $total, 'EXCH_RATE' => isset($entityFields['EXCH_RATE']) ? $entityFields['EXCH_RATE'] : null));
         if (is_array($accData)) {
             $total = (double) $accData['ACCOUNT_SUM'];
         }
     }
     $sumSlots = array();
     $sumSlotFields = DealSumStatisticsTable::getSumSlotFieldNames();
     foreach ($sumSlotFields as $fieldName) {
         $binding = $bindingMap->get($fieldName);
         if ($binding === null) {
             $slotSum = 0.0;
         } else {
             $bindingFieldName = $binding->getFieldName();
             $slotSum = $bindingFieldName !== '' && isset($entityFields[$bindingFieldName]) ? (double) $entityFields[$bindingFieldName] : 0.0;
             if ($binding->getOption('ADD_PRODUCT_ROW_SUM') === 'Y') {
                 $slotSum += $sum;
             }
         }
         if ($currencyID !== $accountingCurrencyID) {
             $accData = \CCrmAccountingHelper::PrepareAccountingData(array('CURRENCY_ID' => $currencyID, 'SUM' => $slotSum, 'EXCH_RATE' => isset($entityFields['EXCH_RATE']) ? $entityFields['EXCH_RATE'] : null));
             if (is_array($accData)) {
                 $slotSum = (double) $accData['ACCOUNT_SUM'];
             }
         }
         $sumSlots[$fieldName] = $slotSum;
     }
     $entities = self::getAll($ownerID);
     $final = null;
     $process = null;
     foreach ($entities as $entity) {
         if (PhaseSemantics::isFinal($entity['STAGE_SEMANTIC_ID'])) {
             $final = $entity;
         } else {
             $process = $entity;
         }
         if ($final && $process) {
             break;
         }
     }
     $latest = self::getLatest($ownerID);
     if (is_array($latest) && isset($latest['START_DATE']) && isset($latest['END_DATE'])) {
         if ($startDate->getTimestamp() === $latest['START_DATE']->getTimestamp() && $endDate->getTimestamp() === $latest['END_DATE']->getTimestamp() && $responsibleID === (int) $latest['RESPONSIBLE_ID'] && $stageID === $latest['STAGE_ID'] && $currencyID === $latest['CURRENCY_ID'] && $total === (double) $latest['SUM_TOTAL'] && $sumSlots['UF_SUM_1'] === (double) $latest['UF_SUM_1'] && $sumSlots['UF_SUM_2'] === (double) $latest['UF_SUM_2'] && $sumSlots['UF_SUM_3'] === (double) $latest['UF_SUM_3'] && $sumSlots['UF_SUM_4'] === (double) $latest['UF_SUM_4'] && $sumSlots['UF_SUM_5'] === (double) $latest['UF_SUM_5']) {
             return;
         }
         if ($startDate->getTimestamp() !== $latest['START_DATE']->getTimestamp() || $endDate->getTimestamp() !== $latest['END_DATE']->getTimestamp() || $responsibleID !== (int) $latest['RESPONSIBLE_ID']) {
             if (!$isFinalized) {
                 DealSumStatisticsTable::deleteByFilter(array('OWNER_ID' => $ownerID, 'SEMANTIC_ID' => PhaseSemantics::getFinalSemantis()));
                 DealSumStatisticsTable::synchronize($ownerID, array('CREATED_DATE' => $startDate, 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID), PhaseSemantics::getProcessSemantis());
             } else {
                 if ($startDate->getTimestamp() === $endDate->getTimestamp()) {
                     DealSumStatisticsTable::deleteByFilter(array('OWNER_ID' => $ownerID, 'SEMANTIC_ID' => PhaseSemantics::getProcessSemantis()));
                     DealSumStatisticsTable::synchronize($ownerID, array('CREATED_DATE' => $endDate, 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID), PhaseSemantics::getFinalSemantis());
                 } else {
                     //Diphasic update of "final" semantics (first update with forged date: "1970-01-01") for avoid possible primary key conflict with "process" semantics
                     DealSumStatisticsTable::synchronize($ownerID, array('CREATED_DATE' => new Date('1970-01-01', 'Y-m-d'), 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID), PhaseSemantics::getFinalSemantis());
                     DealSumStatisticsTable::synchronize($ownerID, array('CREATED_DATE' => $startDate, 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID), PhaseSemantics::getProcessSemantis());
                     DealSumStatisticsTable::synchronize($ownerID, array('CREATED_DATE' => $endDate, 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'RESPONSIBLE_ID' => $responsibleID), PhaseSemantics::getFinalSemantis());
                 }
             }
         }
     }
     $data = array_merge(array('OWNER_ID' => $ownerID, 'CREATED_DATE' => $date, 'START_DATE' => $startDate, 'END_DATE' => $endDate, 'PERIOD_YEAR' => $year, 'PERIOD_QUARTER' => $quarter, 'PERIOD_MONTH' => $month, 'PERIOD_DAY' => $day, 'RESPONSIBLE_ID' => $responsibleID, 'STAGE_SEMANTIC_ID' => $semanticID, 'STAGE_ID' => $stageID, 'IS_LOST' => $isLost ? 'Y' : 'N', 'CURRENCY_ID' => $accountingCurrencyID, 'SUM_TOTAL' => $total), $sumSlots);
     DealSumStatisticsTable::upsert($data);
 }