BxBaseStudioAgentsAutomators.php 22 KB

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