BxBaseStudioAgentsAutomators.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaView UNA Studio Representation classes
  7. * @ingroup UnaStudio
  8. * @{
  9. */
  10. class BxBaseStudioAgentsAutomators extends BxDolStudioAgentsAutomators
  11. {
  12. protected $_sUrlPage;
  13. public function __construct ($aOptions, $oTemplate = false)
  14. {
  15. parent::__construct ($aOptions, $oTemplate);
  16. $this->_sUrlPage = BX_DOL_URL_STUDIO . 'agents.php?page=automators';
  17. }
  18. public function getPageJsObject()
  19. {
  20. return 'oBxDolStudioPageAgents';
  21. }
  22. public function performActionAdd()
  23. {
  24. $sAction = 'add';
  25. $aForm = $this->_getForm($sAction);
  26. $oForm = new BxTemplFormView($aForm);
  27. $oForm->initChecker();
  28. if($oForm->isSubmittedAndValid()) {
  29. $aValsToAdd = ['added' => time()];
  30. $iProfileId = $oForm->getCleanValue('profile_id');
  31. if(empty($iProfileId)) {
  32. $iProfileId = (int)getParam('sys_agents_profile');
  33. if(empty($iProfileId))
  34. $iProfileId = current(bx_srv('system', 'get_options_agents_profile', [false], 'TemplServices'))['key'];
  35. $aValsToAdd['profile_id'] = $iProfileId;
  36. }
  37. $sSchedulerTime = $oForm->getCleanValue('scheduler_time');
  38. if(!empty($sSchedulerTime))
  39. $aValsToAdd['params'] = json_encode(['scheduler_time' => $sSchedulerTime]);
  40. $iModel = $oForm->getCleanValue('model_id');
  41. $sType = $oForm->getCleanValue('type');
  42. $sMessage = $oForm->getCleanValue('message');
  43. $bMessage = !empty($sMessage);
  44. $sMessageAdd = '';
  45. $sMessageResponse = '';
  46. $oAIModel = BxDolAI::getInstance()->getModelObject($iModel);
  47. $bIsValid = true;
  48. switch($sType) {
  49. case BX_DOL_AI_AUTOMATOR_EVENT:
  50. if(($sResponse = $oAIModel->getResponse($sType, $sMessage, true)) !== false) {
  51. $aResponse = json_decode($sResponse, true);
  52. $aValsToAdd = array_merge($aValsToAdd, [
  53. 'alert_unit' => $aResponse['alert_unit'],
  54. 'alert_action' => $aResponse['alert_action'],
  55. 'params' => json_encode(['trigger' => $aResponse['trigger']])
  56. ]);
  57. $sMessageAdd = $aResponse['trigger'];
  58. }
  59. else {
  60. $oForm->aInputs['message']['error'] = _t('_sys_agents_automators_err_event_not_found');
  61. $bIsValid = false;
  62. }
  63. break;
  64. case BX_DOL_AI_AUTOMATOR_SCHEDULER:
  65. if(($sResponse = $oAIModel->getResponse($sType, $sMessage, true)) !== false) {
  66. $aValsToAdd['params'] = json_encode(['scheduler_time' => $sResponse]);
  67. }
  68. else {
  69. $oForm->aInputs['message']['error'] = _t('_sys_agents_automators_err_event_not_found');
  70. $bIsValid = false;
  71. }
  72. break;
  73. }
  74. if($bIsValid) {
  75. if(($sResponse = $oAIModel->getResponse($sType, $sMessage . $sMessageAdd)) !== false) {
  76. $sMessageResponse = $sResponse;
  77. }
  78. else {
  79. $oForm->aInputs['message']['error'] = _t('_sys_agents_automators_err_cannot_get_code');
  80. $bIsValid = false;
  81. }
  82. }
  83. if($bIsValid) {
  84. if(($iId = $oForm->insert($aValsToAdd)) !== false) {
  85. $aProviders = $oForm->getCleanValue('providers');
  86. if(!empty($aProviders) && is_array($aProviders))
  87. foreach($aProviders as $iProviderId)
  88. $this->_oDb->insertAutomatorProvider([
  89. 'automator_id' => $iId,
  90. 'provider_id' => $iProviderId
  91. ]);
  92. if(($oCmts = BxDolCmts::getObjectInstance($this->_sCmts, $iId)) !== null) {
  93. if($bMessage) {
  94. $aResult = $oCmts->addAuto([
  95. 'cmt_author_id' => bx_get_logged_profile_id(),
  96. 'cmt_parent_id' => 0,
  97. 'cmt_text' => $sMessage
  98. ]);
  99. if(!empty($aResult['id']))
  100. $this->_oDb->updateAutomators(['message_id' => $aResult['id']], ['id' => $iId]);
  101. }
  102. if($sMessageResponse) {
  103. sleep(1);
  104. $oCmts->addAuto([
  105. 'cmt_author_id' => $this->_iProfileIdAi,
  106. 'cmt_parent_id' => 0,
  107. 'cmt_text' => $sMessageResponse
  108. ]);
  109. }
  110. }
  111. $aRes = ['grid' => $this->getCode(false), 'blink' => $iId];
  112. }
  113. else
  114. $aRes = ['msg' => _t('_sys_txt_error_occured')];
  115. return echoJson($aRes);
  116. }
  117. }
  118. $sFormId = $oForm->getId();
  119. $sContent = BxTemplStudioFunctions::getInstance()->popupBox($sFormId . '_popup', _t('_sys_agents_automators_popup_add'), $this->_oTemplate->parseHtmlByName('agents_automator_form.html', [
  120. 'form_id' => $sFormId,
  121. 'form' => $oForm->getCode(true),
  122. 'object' => $this->_sObject,
  123. 'action' => $sAction
  124. ]));
  125. return echoJson(['popup' => ['html' => $sContent, 'options' => ['closeOnOuterClick' => false]]]);
  126. }
  127. public function performActionEdit()
  128. {
  129. $sAction = 'edit';
  130. $iId = $this->_getId();
  131. $aAutomator = $this->_oDb->getAutomatorsBy(['sample' => 'id', 'id' => $iId]);
  132. $aAutomator['providers'] = $this->_oDb->getAutomatorsBy(['sample' => 'providers_by_id_pairs', 'id' => $iId]);
  133. $aForm = $this->_getFormEdit($sAction, $aAutomator);
  134. $oForm = new BxTemplFormView($aForm);
  135. $oForm->initChecker();
  136. if($oForm->isSubmittedAndValid()) {
  137. $aValsToAdd = [];
  138. $aProvidersIds = $oForm->getCleanValue('providers_ids');
  139. $bProvidersIds = !empty($aProvidersIds) && is_array($aProvidersIds);
  140. $aProvidersValues = $oForm->getCleanValue('providers');
  141. $bProvidersValues = !empty($aProvidersValues) && is_array($aProvidersValues);
  142. //--- Remove deleted
  143. if(!empty($aAutomator['providers']) && is_array($aAutomator['providers']))
  144. $this->_oDb->deleteAutomatorProvidersById(array_diff(array_keys($aAutomator['providers']), $aProvidersIds));
  145. //--- Update existed
  146. if($bProvidersIds)
  147. foreach($aProvidersIds as $iIndex => $iApId)
  148. $this->_oDb->updateAutomatorProvider(['provider_id' => (int)$aProvidersValues[$iIndex]], ['id' => (int)$iApId]);
  149. //--- Add new
  150. $iProvidersIds = $bProvidersIds ? count($aProvidersIds) : 0;
  151. $iProvidersValues = $bProvidersValues ? count($aProvidersValues) : 0;
  152. if($iProvidersValues > $iProvidersIds) {
  153. $aProvidersValues = array_slice($aProvidersValues, $iProvidersIds);
  154. foreach($aProvidersValues as $iProvidersValue)
  155. $this->_oDb->insertAutomatorProvider([
  156. 'automator_id' => $iId,
  157. 'provider_id' => (int)$iProvidersValue,
  158. ]);
  159. }
  160. $iProfileId = $oForm->getCleanValue('profile_id');
  161. if(empty($iProfileId)) {
  162. $iProfileId = (int)getParam('sys_agents_profile');
  163. if(empty($iProfileId))
  164. $iProfileId = current(bx_srv('system', 'get_options_agents_profile', [false], 'TemplServices'))['key'];
  165. $aValsToAdd['profile_id'] = $iProfileId;
  166. }
  167. $sSchedulerTime = $oForm->getCleanValue('scheduler_time');
  168. if(!empty($sSchedulerTime))
  169. $aValsToAdd['params'] = json_encode(['scheduler_time' => $sSchedulerTime]);
  170. if($oForm->update($iId, $aValsToAdd) !== false)
  171. $aRes = ['grid' => $this->getCode(false), 'blink' => $iId];
  172. else
  173. $aRes = ['msg' => _t('_sys_txt_error_occured')];
  174. return echoJson($aRes);
  175. }
  176. $sFormId = $oForm->getId();
  177. $sContent = BxTemplStudioFunctions::getInstance()->popupBox($sFormId . '_popup', _t('_sys_agents_automators_popup_edit'), $this->_oTemplate->parseHtmlByName('agents_automator_form.html', [
  178. 'form_id' => $sFormId,
  179. 'form' => $oForm->getCode(true),
  180. 'object' => $this->_sObject,
  181. 'action' => $sAction
  182. ]));
  183. return echoJson(['popup' => ['html' => $sContent, 'options' => ['closeOnOuterClick' => false]]]);
  184. }
  185. protected function _getCellSwitcher ($mixedValue, $sKey, $aField, $aRow)
  186. {
  187. if(empty($aRow['code']) || $aRow['status'] != BX_DOL_AI_AUTOMATOR_STATUS_READY)
  188. return parent::_getCellDefault('', $sKey, $aField, $aRow);
  189. return parent::_getCellSwitcher ($mixedValue, $sKey, $aField, $aRow);
  190. }
  191. protected function _getCellModelId($mixedValue, $sKey, $aField, $aRow)
  192. {
  193. $aModel = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $mixedValue]);
  194. if(!empty($aModel) && is_array($aModel))
  195. $mixedValue = $aModel['title'];
  196. return parent::_getCellDefault($mixedValue, $sKey, $aField, $aRow);
  197. }
  198. protected function _getCellProfileId($mixedValue, $sKey, $aField, $aRow)
  199. {
  200. return parent::_getCellDefault(BxDolProfile::getInstanceMagic($mixedValue)->getDisplayName(), $sKey, $aField, $aRow);
  201. }
  202. protected function _getCellType($mixedValue, $sKey, $aField, $aRow)
  203. {
  204. return parent::_getCellDefault(_t('_sys_agents_automators_field_type_' . $mixedValue), $sKey, $aField, $aRow);
  205. }
  206. protected function _getCellData($sKey, $aField, $aRow)
  207. {
  208. if($sKey == 'message_id' && ($iCmtId = (int)$aRow[$sKey]) != 0 && ($oCmts = BxDolCmts::getObjectInstance($this->_sCmts, $aRow['id'])) !== null) {
  209. $aCmt = $oCmts->getCommentSimple($iCmtId);
  210. if(!empty($aCmt) && is_array($aCmt))
  211. $aRow[$sKey] = $aCmt['cmt_text'];
  212. }
  213. return parent::_getCellData($sKey, $aField, $aRow);
  214. }
  215. protected function _getCellAdded($mixedValue, $sKey, $aField, $aRow)
  216. {
  217. return parent::_getCellDefault(bx_time_js($mixedValue), $sKey, $aField, $aRow);
  218. }
  219. protected function _getCellStatus($mixedValue, $sKey, $aField, $aRow)
  220. {
  221. return parent::_getCellDefault(_t('_sys_agents_automators_field_status_' . $mixedValue), $sKey, $aField, $aRow);
  222. }
  223. protected function _getActionTune($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = [])
  224. {
  225. $a['attr'] = array_merge($a['attr'], [
  226. "onclick" => "window.open('" . $this->_sUrlPage . '&id=' . $aRow['id'] . "', '_self');"
  227. ]);
  228. return $this->_getActionDefault ($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  229. }
  230. protected function _addJsCss()
  231. {
  232. parent::_addJsCss();
  233. $this->_oTemplate->addJs(['jquery.form.min.js', 'agents_automators.js']);
  234. $oForm = new BxTemplStudioFormView([]);
  235. $oForm->addCssJs();
  236. }
  237. protected function _isCheckboxDisabled($aRow)
  238. {
  239. return false;
  240. }
  241. protected function _getActionsDisabledBehavior($aRow)
  242. {
  243. return false;
  244. }
  245. protected function _delete ($mixedId)
  246. {
  247. $mixedResult = parent::_delete($mixedId);
  248. if($mixedResult)
  249. $this->_oDb->deleteAutomatorProviders(['automator_id' => (int)$mixedId]);
  250. return $mixedResult;
  251. }
  252. protected function _getFormEdit($sAction, $aAutomator = [])
  253. {
  254. $aForm = $this->_getForm($sAction, $aAutomator);
  255. $aForm['form_attrs']['action'] .= '&id=' . $aAutomator['id'];
  256. unset($aForm['inputs']['type']);
  257. unset($aForm['inputs']['message']);
  258. return $aForm;
  259. }
  260. protected function _getForm($sAction, $aAutomator = [])
  261. {
  262. $sJsObject = $this->getPageJsObject();
  263. $sType = isset($aAutomator['type']) ? $aAutomator['type'] : 'event';
  264. if(!empty($aAutomator['params']))
  265. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  266. $aForm = array(
  267. 'form_attrs' => array(
  268. 'id' => 'bx_std_agents_automators_' . $sAction,
  269. 'action' => BX_DOL_URL_ROOT . 'grid.php?o=sys_studio_agents_automators&a=' . $sAction,
  270. 'method' => 'post',
  271. ),
  272. 'params' => array (
  273. 'db' => array(
  274. 'table' => 'sys_agents_automators',
  275. 'key' => 'id',
  276. 'submit_name' => 'do_submit',
  277. ),
  278. ),
  279. 'inputs' => array(
  280. 'model_id' => [
  281. 'type' => 'select',
  282. 'name' => 'model_id',
  283. 'caption' => _t('_sys_agents_automators_field_model_id'),
  284. 'info' => '',
  285. 'value' => isset($aAutomator['model_id']) ? $aAutomator['model_id'] : 0,
  286. 'values' => $this->_oDb->getModelsBy(['sample' => 'all_pairs']),
  287. 'required' => '1',
  288. 'db' => [
  289. 'pass' => 'Int',
  290. ]
  291. ],
  292. 'profile_id' => [
  293. 'type' => 'select',
  294. 'name' => 'profile_id',
  295. 'caption' => _t('_sys_agents_automators_field_profile_id'),
  296. 'info' => _t('_sys_agents_automators_field_profile_id_inf'),
  297. 'value' => isset($aAutomator['profile_id']) ? $aAutomator['profile_id'] : 0,
  298. 'values' => bx_srv('system', 'get_options_agents_profile', [], 'TemplServices'),
  299. 'required' => '0',
  300. 'db' => [
  301. 'pass' => 'Int',
  302. ]
  303. ],
  304. 'type' => [
  305. 'type' => 'select',
  306. 'name' => 'type',
  307. 'caption' => _t('_sys_agents_automators_field_type'),
  308. 'info' => '',
  309. 'value' => $sType,
  310. 'values' => [
  311. 'event' => _t('_sys_agents_automators_field_type_event'),
  312. 'scheduler' => _t('_sys_agents_automators_field_type_scheduler'),
  313. 'webhook' => _t('_sys_agents_automators_field_type_webhook'),
  314. ],
  315. 'attrs' => [
  316. 'onchange' => $this->getPageJsObject() . '.onChangeAutomatorType(this)',
  317. ],
  318. 'required' => '1',
  319. 'db' => [
  320. 'pass' => 'Xss',
  321. ]
  322. ],
  323. 'alert_unit' => [
  324. 'type' => 'hidden',
  325. 'name' => 'alert_unit',
  326. 'caption' => _t('_sys_agents_automators_field_alert_unit'),
  327. 'value' => isset($aAutomator['alert_unit']) ? $aAutomator['alert_unit'] : '',
  328. 'tr_attrs' => [
  329. 'style' => $sType != 'event' ? 'display:none' : ''
  330. ],
  331. 'db' => [
  332. 'pass' => 'Xss',
  333. ],
  334. ],
  335. 'alert_action' => [
  336. 'type' => 'hidden',
  337. 'name' => 'alert_action',
  338. 'caption' => _t('_sys_agents_automators_field_alert_action'),
  339. 'value' => isset($aAutomator['alert_action']) ? $aAutomator['alert_action'] : '',
  340. 'tr_attrs' => [
  341. 'style' => $sType != 'event' ? 'display:none' : ''
  342. ],
  343. 'db' => [
  344. 'pass' => 'Xss',
  345. ],
  346. ],
  347. 'scheduler_time' => [
  348. 'type' => 'hidden',
  349. 'name' => 'scheduler_time',
  350. 'caption' => _t('_sys_agents_automators_field_scheduler_time'),
  351. 'value' => isset($aAutomator['params']['scheduler_time']) ? $aAutomator['params']['scheduler_time'] : '',
  352. 'tr_attrs' => [
  353. 'style' => $sType != 'scheduler' ? 'display:none' : ''
  354. ],
  355. ],
  356. 'providers' => [
  357. 'type' => 'custom',
  358. 'name' => 'providers',
  359. 'caption' => _t('_sys_agents_automators_field_providers'),
  360. 'value' => '',
  361. ],
  362. 'message' => [
  363. 'type' => 'textarea',
  364. 'name' => 'message',
  365. 'caption' => _t('_sys_agents_automators_field_message'),
  366. ],
  367. 'submit' => array(
  368. 'type' => 'input_set',
  369. 0 => array (
  370. 'type' => 'submit',
  371. 'name' => 'do_submit',
  372. 'value' => _t('_sys_submit'),
  373. ),
  374. 1 => array (
  375. 'type' => 'reset',
  376. 'name' => 'close',
  377. 'value' => _t('_sys_close'),
  378. 'attrs' => array('class' => 'bx-def-margin-sec-left', 'onclick' => '$(\'.bx-popup-applied:visible\').dolPopupHide();'),
  379. ),
  380. ),
  381. ),
  382. );
  383. if($aForm['inputs']['providers']) {
  384. $oForm = new BxTemplFormView([]);
  385. $sProviders = 'providers';
  386. $aProviders = array_map(function($sTitle) {
  387. return _t($sTitle);
  388. }, ['' => '_sys_please_select'] + $this->_oDb->getProviderBy(['sample' => 'all_pairs', 'active' => 1]));
  389. $aTmplVarsProviders = array();
  390. if(!empty($aAutomator['providers']) && is_array($aAutomator['providers'])) {
  391. foreach($aAutomator['providers'] as $iApId => $iProviderId) {
  392. $aInputSelect = [
  393. 'type' => 'select',
  394. 'name' => 'providers[]',
  395. 'values' => $aProviders,
  396. 'value' => (int)$iProviderId,
  397. 'attrs' => [
  398. 'class' => 'bx-def-margin-sec-top-auto'
  399. ]
  400. ];
  401. $sInput = $oForm->genInput($aInputSelect);
  402. $aInputHidden = [
  403. 'type' => 'hidden',
  404. 'name' => 'providers_ids[]',
  405. 'value' => (int)$iApId,
  406. ];
  407. $sInput .= $oForm->genInput($aInputHidden);
  408. $aTmplVarsProviders[] = ['js_object' => $sJsObject, 'input_select' => $sInput];
  409. }
  410. }
  411. else {
  412. $aInputSelect = [
  413. 'type' => 'select',
  414. 'name' => 'providers[]',
  415. 'values' => $aProviders,
  416. 'value' => '',
  417. 'attrs' => [
  418. 'class' => 'bx-def-margin-sec-top-auto'
  419. ]
  420. ];
  421. $aTmplVarsProviders = [
  422. ['js_object' => $sJsObject, 'input_select' => $oForm->genInput($aInputSelect)],
  423. ];
  424. }
  425. $aInputButton = [
  426. 'type' => 'button',
  427. 'name' => 'providers_add',
  428. 'value' => _t('_sys_agents_automators_field_providers_add'),
  429. 'attrs' => [
  430. 'class' => 'bx-def-margin-sec-top',
  431. 'onclick' => $sJsObject . ".providerAdd(this, '" . $sProviders . "');"
  432. ]
  433. ];
  434. $aForm['inputs']['providers']['content'] = $this->_oTemplate->parseHtmlByName('agents_automator_form_providers.html', [
  435. 'bx_repeat:providers' => $aTmplVarsProviders,
  436. 'btn_add' => $oForm->genInputButton($aInputButton)
  437. ]);
  438. }
  439. return $aForm;
  440. }
  441. protected function _getId()
  442. {
  443. $aIds = bx_get('ids');
  444. if(!empty($aIds) && is_array($aIds))
  445. return array_shift($aIds);
  446. $iId = (int)bx_get('id');
  447. if(!$iId)
  448. return false;
  449. return $iId;
  450. }
  451. }
  452. /** @} */