BxBaseStudioAgentsAutomators.php 22 KB

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