BxBaseStudioAgentsAutomators.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 getJsObject()
  19. {
  20. return 'oBxDolStudioAgentsAutomators';
  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 = [];
  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. $sMessage = $oForm->getCleanValue('message');
  41. $bMessage = !empty($sMessage);
  42. $sMessageAdd = '';
  43. $sMessageResponse = '';
  44. if($bMessage)
  45. $aValsToAdd['messages'] = 1;
  46. $oAI = BxDolAI::getInstance();
  47. $iModel = $oForm->getCleanValue('model_id');
  48. $aModel = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $iModel]);
  49. if(!empty($aModel['params']))
  50. $aModel['params'] = json_decode($aModel['params'], true);
  51. $bIsValid = true;
  52. $sType = $oForm->getCleanValue('type');
  53. switch($sType) {
  54. case 'event':
  55. $aMessages = [
  56. ['role' => 'system', 'content' => file_get_contents(BX_DIRECTORY_PATH_ROOT. '/ai_alert_instructions.html' )],
  57. ['role' => 'user', 'content' => $sMessage]
  58. ];
  59. $sResponse = $oAI->chat($aModel['url'], $aModel['model'], $aModel['key'], $aModel['params'], $aMessages);
  60. if(trim($sResponse) != 'false') {
  61. $sResponse = str_replace(['```json', '```'], '', $sResponse);
  62. $aResponse = json_decode($sResponse, true);
  63. $aValsToAdd = array_merge($aValsToAdd, [
  64. 'alert_unit' => $aResponse['alert_unit'],
  65. 'alert_action' => $aResponse['alert_action']
  66. ]);
  67. $sMessageAdd = $aResponse['trigger'];
  68. }
  69. else {
  70. $oForm->aInputs['message']['err'] = _t('_sys_agents_automators_err_event_not_found');
  71. $bIsValid = false;
  72. }
  73. break;
  74. case 'scheduler':
  75. $aMessages = [
  76. ['role' => 'system', 'content' => file_get_contents(BX_DIRECTORY_PATH_ROOT. '/ai_cron_instructions.html' )],
  77. ['role' => 'user', 'content' => $sMessage]
  78. ];
  79. $sResponse = $oAI->chat($aModel['url'], $aModel['model'], $aModel['key'], $aModel['params'], $aMessages);
  80. if(trim($sResponse) != 'false') {
  81. $aValsToAdd['params'] = json_encode(['scheduler_time' => $aResponse]);
  82. }
  83. else {
  84. $oForm->aInputs['message']['err'] = _t('_sys_agents_automators_err_event_not_found');
  85. $bIsValid = false;
  86. }
  87. break;
  88. }
  89. if($bIsValid) {
  90. $aMessages = [
  91. ['role' => 'system', 'content' => file_get_contents(BX_DIRECTORY_PATH_ROOT. '/ai_' . $sType . '_instructions.html' ) . file_get_contents(BX_DIRECTORY_PATH_ROOT. '/ai_common_instructions.html' )],
  92. ['role' => 'user', 'content' => $sMessage . $sMessageAdd]
  93. ];
  94. $sResponse = $oAI->chat($aModel['url'], $aModel['model'], $aModel['key'], $aModel['params'], $aMessages);
  95. if(trim($sResponse) != 'false') {
  96. $sResponse = str_replace(['```php', '```'], '', $sResponse);
  97. $sMessageResponse = $sResponse;
  98. }
  99. else {
  100. $oForm->aInputs['message']['err'] = _t('_sys_agents_automators_err_cannot_get_code');
  101. $bIsValid = false;
  102. }
  103. }
  104. if($bIsValid) {
  105. if(($iId = $oForm->insert($aValsToAdd)) !== false) {
  106. if(($oCmts = BxDolCmts::getObjectInstance($this->_sCmts, $iId)) !== null) {
  107. if($bMessage)
  108. $oCmts->addAuto([
  109. 'cmt_author_id' => bx_get_logged_profile_id(),
  110. 'cmt_parent_id' => 0,
  111. 'cmt_text' => $sMessage
  112. ]);
  113. if($sMessageResponse) {
  114. sleep(1);
  115. $oCmts->addAuto([
  116. 'cmt_author_id' => $this->_iProfileAi,
  117. 'cmt_parent_id' => 0,
  118. 'cmt_text' => $sMessageResponse
  119. ]);
  120. $aValsToAdd['messages']++;
  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. $aForm = $this->_getFormEdit($sAction, $aAutomator);
  145. $oForm = new BxTemplFormView($aForm);
  146. $oForm->initChecker();
  147. if($oForm->isSubmittedAndValid()) {
  148. $aValsToAdd = [];
  149. $iProfileId = $oForm->getCleanValue('profile_id');
  150. if(empty($iProfileId)) {
  151. $iProfileId = (int)getParam('sys_agents_profile');
  152. if(empty($iProfileId))
  153. $iProfileId = current(bx_srv('system', 'get_options_agents_profile', [false], 'TemplServices'))['key'];
  154. $aValsToAdd['profile_id'] = $iProfileId;
  155. }
  156. $sSchedulerTime = $oForm->getCleanValue('scheduler_time');
  157. if(!empty($sSchedulerTime))
  158. $aValsToAdd['params'] = json_encode(['scheduler_time' => $sSchedulerTime]);
  159. if($oForm->update($iId, $aValsToAdd))
  160. $aRes = ['grid' => $this->getCode(false), 'blink' => $iId];
  161. else
  162. $aRes = ['msg' => _t('_sys_txt_error_occured')];
  163. return echoJson($aRes);
  164. }
  165. $sFormId = $oForm->getId();
  166. $sContent = BxTemplStudioFunctions::getInstance()->popupBox($sFormId . '_popup', _t('_sys_agents_automators_popup_edit'), $this->_oTemplate->parseHtmlByName('agents_automator_form.html', [
  167. 'form_id' => $sFormId,
  168. 'form' => $oForm->getCode(true),
  169. 'object' => $this->_sObject,
  170. 'action' => $sAction
  171. ]));
  172. return echoJson(['popup' => ['html' => $sContent, 'options' => ['closeOnOuterClick' => false]]]);
  173. }
  174. public function getCode($isDisplayHeader = true)
  175. {
  176. return $this->_oTemplate->parseHtmlByName('agents_automator.html', [
  177. 'content' => parent::getCode($isDisplayHeader),
  178. 'js_object' => $this->getJsObject(),
  179. 'page_url' => $this->_sUrlPage,
  180. 'grid_object' => $this->_sObject,
  181. 'params_divider' => $this->sParamsDivider
  182. ]);
  183. }
  184. protected function _getCellModelId($mixedValue, $sKey, $aField, $aRow)
  185. {
  186. $aModel = $this->_oDb->getModelsBy(['sample' => 'id', 'id' => $mixedValue]);
  187. if(!empty($aModel) && is_array($aModel))
  188. $mixedValue = $aModel['name'];
  189. return parent::_getCellDefault($mixedValue, $sKey, $aField, $aRow);
  190. }
  191. protected function _getCellProfileId($mixedValue, $sKey, $aField, $aRow)
  192. {
  193. return parent::_getCellDefault(BxDolProfile::getInstanceMagic($mixedValue)->getDisplayName(), $sKey, $aField, $aRow);
  194. }
  195. protected function _getCellType($mixedValue, $sKey, $aField, $aRow)
  196. {
  197. return parent::_getCellDefault(_t('_sys_agents_automators_field_type_' . $mixedValue), $sKey, $aField, $aRow);
  198. }
  199. protected function _getCellStatus($mixedValue, $sKey, $aField, $aRow)
  200. {
  201. return parent::_getCellDefault(_t('_sys_agents_automators_field_status_' . $mixedValue), $sKey, $aField, $aRow);
  202. }
  203. protected function _getActionTune($sType, $sKey, $a, $isSmall = false, $isDisabled = false, $aRow = [])
  204. {
  205. $a['attr'] = array_merge($a['attr'], [
  206. "onclick" => "window.open('" . $this->_sUrlPage . '&id=' . $aRow['id'] . "', '_self');"
  207. ]);
  208. return $this->_getActionDefault ($sType, $sKey, $a, $isSmall, $isDisabled, $aRow);
  209. }
  210. protected function _addJsCss()
  211. {
  212. parent::_addJsCss();
  213. $this->_oTemplate->addJs(['jquery.form.min.js', 'agents_automators.js']);
  214. $oForm = new BxTemplStudioFormView([]);
  215. $oForm->addCssJs();
  216. }
  217. protected function _isCheckboxDisabled($aRow)
  218. {
  219. return false;
  220. }
  221. protected function _getActionsDisabledBehavior($aRow)
  222. {
  223. return false;
  224. }
  225. protected function _getFormEdit($sAction, $aAutomator = [])
  226. {
  227. $aForm = $this->_getForm($sAction, $aAutomator);
  228. $aForm['form_attrs']['action'] .= '&id=' . $aAutomator['id'];
  229. unset($aForm['inputs']['message']);
  230. return $aForm;
  231. }
  232. protected function _getForm($sAction, $aAutomator = [])
  233. {
  234. $sType = isset($aAutomator['type']) ? $aAutomator['type'] : 'event';
  235. if(!empty($aAutomator['params']))
  236. $aAutomator['params'] = json_decode($aAutomator['params'], true);
  237. $aForm = array(
  238. 'form_attrs' => array(
  239. 'id' => 'bx_std_agents_automators_' . $sAction,
  240. 'action' => BX_DOL_URL_ROOT . 'grid.php?o=sys_studio_agents_automators&a=' . $sAction,
  241. 'method' => 'post',
  242. ),
  243. 'params' => array (
  244. 'db' => array(
  245. 'table' => 'sys_agents_automators',
  246. 'key' => 'id',
  247. 'submit_name' => 'do_submit',
  248. ),
  249. ),
  250. 'inputs' => array(
  251. 'model_id' => [
  252. 'type' => 'select',
  253. 'name' => 'model_id',
  254. 'caption' => _t('_sys_agents_automators_field_model_id'),
  255. 'info' => '',
  256. 'value' => isset($aAutomator['model_id']) ? $aAutomator['model_id'] : 0,
  257. 'values' => $this->_oDb->getModelsBy(['sample' => 'all_pairs']),
  258. 'required' => '1',
  259. 'db' => [
  260. 'pass' => 'Int',
  261. ]
  262. ],
  263. 'profile_id' => [
  264. 'type' => 'select',
  265. 'name' => 'profile_id',
  266. 'caption' => _t('_sys_agents_automators_field_profile_id'),
  267. 'info' => _t('_sys_agents_automators_field_profile_id_inf'),
  268. 'value' => isset($aAutomator['profile_id']) ? $aAutomator['profile_id'] : 0,
  269. 'values' => bx_srv('system', 'get_options_agents_profile', [], 'TemplServices'),
  270. 'required' => '0',
  271. 'db' => [
  272. 'pass' => 'Int',
  273. ]
  274. ],
  275. 'type' => [
  276. 'type' => 'select',
  277. 'name' => 'type',
  278. 'caption' => _t('_sys_agents_automators_field_type'),
  279. 'info' => '',
  280. 'value' => $sType,
  281. 'values' => [
  282. 'event' => _t('_sys_agents_automators_field_type_event'),
  283. 'scheduler' => _t('_sys_agents_automators_field_type_scheduler'),
  284. 'webhook' => _t('_sys_agents_automators_field_type_webhook'),
  285. ],
  286. 'attrs' => [
  287. 'onchange' => $this->getJsObject() . '.onChangeType(this)',
  288. ],
  289. 'required' => '1',
  290. 'db' => [
  291. 'pass' => 'Xss',
  292. ]
  293. ],
  294. 'alert_unit' => [
  295. 'type' => 'hidden',
  296. 'name' => 'alert_unit',
  297. 'caption' => _t('_sys_agents_automators_field_alert_unit'),
  298. 'value' => isset($aAutomator['alert_unit']) ? $aAutomator['alert_unit'] : '',
  299. 'tr_attrs' => [
  300. 'style' => $sType != 'event' ? 'display:none' : ''
  301. ],
  302. 'db' => [
  303. 'pass' => 'Xss',
  304. ],
  305. ],
  306. 'alert_action' => [
  307. 'type' => 'hidden',
  308. 'name' => 'alert_action',
  309. 'caption' => _t('_sys_agents_automators_field_alert_action'),
  310. 'value' => isset($aAutomator['alert_action']) ? $aAutomator['alert_action'] : '',
  311. 'tr_attrs' => [
  312. 'style' => $sType != 'event' ? 'display:none' : ''
  313. ],
  314. 'db' => [
  315. 'pass' => 'Xss',
  316. ],
  317. ],
  318. 'scheduler_time' => [
  319. 'type' => 'hidden',
  320. 'name' => 'scheduler_time',
  321. 'caption' => _t('_sys_agents_automators_field_scheduler_time'),
  322. 'value' => isset($aAutomator['params']['scheduler_time']) ? $aAutomator['params']['scheduler_time'] : '',
  323. 'tr_attrs' => [
  324. 'style' => $sType != 'scheduler' ? 'display:none' : ''
  325. ],
  326. ],
  327. 'message' => [
  328. 'type' => 'textarea',
  329. 'name' => 'message',
  330. 'caption' => _t('_sys_agents_automators_field_message'),
  331. ],
  332. 'submit' => array(
  333. 'type' => 'input_set',
  334. 0 => array (
  335. 'type' => 'submit',
  336. 'name' => 'do_submit',
  337. 'value' => _t('_sys_submit'),
  338. ),
  339. 1 => array (
  340. 'type' => 'reset',
  341. 'name' => 'close',
  342. 'value' => _t('_sys_close'),
  343. 'attrs' => array('class' => 'bx-def-margin-sec-left', 'onclick' => '$(\'.bx-popup-applied:visible\').dolPopupHide();'),
  344. ),
  345. ),
  346. ),
  347. );
  348. return $aForm;
  349. }
  350. protected function _getId()
  351. {
  352. $aIds = bx_get('ids');
  353. if(!empty($aIds) && is_array($aIds))
  354. return array_shift($aIds);
  355. $iId = (int)bx_get('id');
  356. if(!$iId)
  357. return false;
  358. return $iId;
  359. }
  360. }
  361. /** @} */