functions.php 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042
  1. <?php
  2. use CheckPoints\CheckPoint;
  3. use CheckPointTypes\CheckPointType;
  4. //use Tasks\Task;
  5. require_once 'ocs.php';
  6. $onlineMobileTimeoutSeconds = 600;
  7. function VagrantRequest($accid, $tagid, $name, $eventtype, $echo=false)
  8. {
  9. if ($tagid=='unavailable')
  10. return;
  11. global $link;
  12. $account = Account::Find($accid);
  13. $jobstring = "No role";
  14. if ($account)
  15. {
  16. $jobtypes = $account->getJobtypesIds();
  17. $jobstring = GetJobNames($jobtypes)[0];
  18. $company = $account->getCompany();
  19. if ($company)
  20. {
  21. if (intval($company->id) > 1)
  22. return;
  23. }
  24. // $jobnames_account = GetJobNames($jobtypes)[0];
  25. // $jobstring = implode(",", $jobnames_account);
  26. }
  27. // var_dump($jobstring);
  28. //return;
  29. $params['projectId'] = "000T";
  30. $params['role'] = $jobstring;
  31. $params['fullName'] = $name; //"123";//"2019-10-28T13:00:00";
  32. $params['employeeId'] = $accid; //"123";//"2019-10-28T13:00:00";
  33. $params['tagId'] = $tagid; //"123";//"2019-10-28T13:00:00";
  34. $params['eventType'] = $eventtype; //1;//"2019-10-28T13:00:00";
  35. $url = "https://vagrantsmopp.azurewebsites.net/api/EmployeeTag";
  36. $jsonEncoded = json_encode($params);
  37. $curl = curl_init();
  38. curl_setopt($curl, CURLOPT_URL, $url);
  39. curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Accept:application/json"));
  40. curl_setopt($curl, CURLOPT_TIMEOUT, 60);
  41. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  42. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  43. curl_setopt($curl, CURLOPT_POST, 1);
  44. curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonEncoded);
  45. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  46. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  47. $result = curl_exec($curl);
  48. $str = "insert into vagrant_log (acc_id, eventtype, reply, stamp, tagid) values ($accid, $eventtype, '$result', NOW(), '$tagid')";
  49. mysqli_query($link, $str);
  50. if ($echo) {
  51. var_dump($result);
  52. var_dump($params);
  53. // echo $str;
  54. }
  55. }
  56. function GetCompanyID($act, $activeid)
  57. {
  58. $companyID = 0;
  59. switch ($act)
  60. {
  61. case "tasktypes":
  62. $tt = Tasktype::Find($activeid);
  63. if ($tt)
  64. $companyID = $tt->company;
  65. break;
  66. case "tasks":
  67. $task = Task::Find($activeid);
  68. if ($task) {
  69. $type = $task->type;
  70. $tt = Tasktype::Find($type);
  71. if ($tt)
  72. $companyID = $tt->company;
  73. }
  74. break;
  75. case "projects":
  76. $proj = Project::Find($activeid);
  77. if ($proj)
  78. $companyID = $proj->getCompany();
  79. break;
  80. case "project_types":
  81. $proj = ProjectType::Find($activeid);
  82. if ($proj)
  83. $companyID = $proj->company;
  84. break;
  85. }
  86. return $companyID;
  87. }
  88. function EnqueueCMD($acc_id, $cmd)
  89. {
  90. global $link;
  91. $str = "insert into commands (account_id, cmd, created) values ($acc_id, '$cmd', NOW())";
  92. $query = mysqli_query($link, $str);
  93. }
  94. function DequeueCMD($acc_id)
  95. {
  96. global $link;
  97. $str = "select * from commands where account_id = $acc_id";
  98. $query = mysqli_query($link, $str);
  99. $cmdarr = array();
  100. while ($res = mysqli_fetch_array($query)) {
  101. $cmd = $res['cmd'];
  102. array_push($cmdarr, $cmd);
  103. mysqli_query($link, "delete from commands where id = ".$res['id']);
  104. }
  105. return $cmdarr;
  106. }
  107. function XLSRead($inputFileName, $activeSheet = 0)
  108. {
  109. error_reporting(E_ALL);
  110. set_time_limit(0);
  111. date_default_timezone_set('Europe/London');
  112. /** Include path **/
  113. set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel_1.8.0_doc/Classes/');
  114. /** PHPExcel_IOFactory */
  115. include 'PHPExcel/IOFactory.php';
  116. //$inputFileName = 'example1.xls';
  117. //$inputFileName = './sampleData/example1.xls';
  118. // echo 'Loading file ', pathinfo($inputFileName, PATHINFO_BASENAME), ' using IOFactory to identify the format<br />';
  119. $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
  120. echo '<hr />';
  121. if ($activeSheet > 0)
  122. $objPHPExcel->setActiveSheetIndex($activeSheet);
  123. $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
  124. //var_dump($sheetData);
  125. return $sheetData;
  126. }
  127. function FindAction($actionID)
  128. {
  129. global $link, $companyID;
  130. $query1 = mysqli_query($link, "select * from projecttypes where id=$actionID");
  131. if ($res1 = mysqli_fetch_array($query1)) {
  132. return $res1;
  133. }
  134. }
  135. function FindActions($tasktype = '')
  136. {
  137. global $link, $companyID, $entityManager;
  138. return $entityManager->getRepository('ProjectType')->findBy(array('company' => $companyID));
  139. // //return $entityManager->getRepository('MyProject\Domain\User')->findBy(array('age' => 20, 'surname' => 'Miller'));
  140. //
  141. // $str = "select p_r.id,p_r.name,p_r.company
  142. // from projecttypes p_r
  143. // join projecttypes_tasktypes p_t on p_t.projecttype_id = p_r.id
  144. // join tasktypes t on t.id = p_t.tasktype_id
  145. // where p_r.company = $companyID" ;
  146. //
  147. ////$str = "select * from project_types where company=$companyID";
  148. // if ($tasktype != '') {
  149. // //$str .= " and $tasktype in (tasktypes)";
  150. // $str .= " and t.id = $tasktype";
  151. // }
  152. // //var_dump($str); die();
  153. //
  154. // $query1 = mysqli_query($link, $str);
  155. // $returnArr = array();
  156. // while ($res1 = mysqli_fetch_array($query1)) {
  157. // array_push($returnArr, $res1);
  158. // }
  159. //
  160. // return $returnArr;
  161. }
  162. function FindParentTaskType($ttid)
  163. {
  164. global $link;
  165. $str = "select * from tasktypes tt where main_task=1 and $ttid IN (tt.subtasks)";
  166. //echo '$str'.$str;
  167. $returnArr = array();
  168. $query1 = mysqli_query($link, $str);
  169. while ($res1 = mysqli_fetch_array($query1)) {
  170. array_push($returnArr, $res1);
  171. }
  172. return $returnArr;
  173. }
  174. function FindTaskOwner($tid)
  175. {
  176. global $link;
  177. $str = "select id from accounts accs where $tid IN (accs.active_task_ids)";
  178. // echo '$str'.$str;
  179. $returnArr = array();
  180. $query1 = mysqli_query($link, $str);
  181. if ($res1 = mysqli_fetch_row($query1)) {
  182. return $res1[0];
  183. }
  184. return null;
  185. // while ($res1 = mysqli_fetch_array($query1)) {
  186. //
  187. // array_push($returnArr, $res1);
  188. // }
  189. // return $returnArr;
  190. }
  191. function StartProject($action, $project_id, $manager=null)
  192. {
  193. global $entityManager;
  194. // var_dump($entityManager);
  195. // echo "<br>"; die();
  196. //$assign_id - id таблицы входных данных
  197. //$action - действие (например перемещение)
  198. //данная функция:
  199. //1. ищет в базе среди tasktype данное действие (глобальное main_task=true)
  200. //2. создает задачу найденного типа
  201. $existing_tasks = GetTasksForProject($project_id);
  202. if (sizeof($existing_tasks) > 0) {
  203. echo "<span style='color: red'>Задачи для этого проекта уже созданы</span><br>";
  204. OCSnewproject($project_id);
  205. return true;
  206. }
  207. // $tasktypesarr = GrabTasktypes("all", intval($action));
  208. if ( null == $entityManager ) {
  209. $entityManager = $manager;
  210. }
  211. $tasktypesarr = ProjectType::GrabTasktypesByProjectType(intval($action), $entityManager);
  212. if (sizeof($tasktypesarr) > 0) {
  213. CreateTasks($tasktypesarr, $project_id);
  214. OCSnewproject($project_id);
  215. return true;
  216. }
  217. else
  218. {
  219. echo "<span style='color: red'>Ошибка: нет подходящих задач под выбранное действие</span>";
  220. OCSnewproject($project_id);
  221. return false;
  222. }
  223. }
  224. function getTaskStatusName($status)
  225. {
  226. global $link;
  227. $name = '';
  228. $color = '';
  229. $query = mysqli_query($link,"select * from task_status_names where id=".$status);
  230. if ($res = mysqli_fetch_array($query))
  231. {
  232. $name = $res['name'];
  233. $color = $res['color'];
  234. }
  235. return array ($name, $color);
  236. }
  237. function GetHrefActive($href, $name, $li=true)
  238. {
  239. global $act;
  240. $hrefactive = '';
  241. if ($href == $act) {
  242. $hrefactive = ' style="color:blue" class="active" ';
  243. }
  244. $liopen = '<li>';
  245. $liclose = '</li>';
  246. if ($li == false)
  247. {
  248. $liopen = '';
  249. $liclose = '';
  250. }
  251. echo $liopen.'<a class="menuleft" href="?act='.$href.'"'.$hrefactive.'>'.$name.'</a>'.$liclose;
  252. }
  253. function GetAccordeonNum($act)
  254. {
  255. $accordnum = 0;
  256. switch($act)
  257. {
  258. case "global": $accordnum = 0;break;
  259. case "companies": $accordnum = 0;break;
  260. case "projects": $accordnum = 0;break;
  261. case "locations": $accordnum = 0;break;
  262. case "projects_old": $accordnum = 0;break;
  263. case "project_types": $accordnum = 0;break;
  264. case "loco": $accordnum = 0;break;
  265. case "penalties": $accordnum = 3;break;
  266. case "filelib": $incl ="filelib/in.php";break;
  267. case "accounts": $incl ="accounts.php";$accordnum = 0;break;
  268. case "analytics": $incl ="analytics.php";$accordnum = 0;break;
  269. case "markers": $incl ="markers.php";$accordnum = 1;break;
  270. case "tasks": $incl ="tasks.php";$accordnum = 2;break;
  271. case "checkpoints": $incl ="checkpoints.php";$accordnum = 2;break;
  272. case "checkitems": $incl ="checkitems.php";$accordnum = 2;break;
  273. case "tasksdone": $incl ="tasksdone.php";$accordnum = 2;break;
  274. case "tasktypes": $incl ="tasktypes.php";$accordnum = 2;break;
  275. case "docs": $incl ="docs.php";$accordnum = 4;break;
  276. case "reports": $incl ="reports.php";$accordnum = 4;break;
  277. case "journal": $incl ="journal.php";$accordnum = 4;break;
  278. case "devices": $incl ="devices.php";$accordnum = 1;break;
  279. case "staff": $incl ="staff.php";$accordnum = 3;break;
  280. case "objects": $incl ="objects.php";$accordnum = 1;break;
  281. case "object": $incl ="object.php";$accordnum = 1;break;
  282. case "typeobject": $incl ="typeobject.php";$accordnum = 1;break;
  283. case "input_data": $incl ="input_data.php";$accordnum = 3;break;
  284. case "jobs": $incl ="jobs.php";$accordnum = 3;break;
  285. case "dashboard": $incl ="dashboard.php";$accordnum = 0;break;
  286. }
  287. return $accordnum;
  288. }
  289. function GetInclude($act, $cmdlevel)
  290. {
  291. $incl = '';
  292. $accordnum = GetAccordeonNum($act);
  293. if ($cmdlevel==10) {//head admins
  294. switch($act) {
  295. case "asusg_dayplan": $incl ="asusg_dayplan.php";break;
  296. case "penalties": $incl ="penalties.php";break;
  297. case "loco": $incl ="loco.php";break;
  298. case "locations": $incl ="locations.php";break;
  299. case "algo": $incl ="algo.php";break;
  300. case "locations2": $incl = "locations2.php";break;
  301. case "global": $incl ="global.php";break;
  302. case "companies": $incl ="companies.php";break;
  303. case "accounts": $incl ="accounts.php";break;
  304. case "markers": $incl ="markers.php";break;
  305. case "tasks": $incl ="tasks.php";break;
  306. case "tasksdone": $incl ="tasksdone.php";break;
  307. case "analytics": $incl ="analytics.php";break;
  308. case "mp_using": $incl ="user_activity.php";break;
  309. case "checkpoints": $incl ="checkpoints.php";break;
  310. case "checkitems": $incl ="checkitems.php";break;
  311. case "tasktypes": $incl ="tasktypes.php";break;
  312. case "docs": $incl ="docs.php";break;
  313. case "reports": $incl ="reports.php";break;
  314. case "devices": $incl ="devices.php";break;
  315. case "projects": $incl ="projects.php";break;
  316. case "project_types": $incl ="project_types.php";break;
  317. case "projects_old": $incl ="projects_old.php";break;
  318. case "staff": $incl ="staff.php";break;
  319. case "objects": $incl ="objects.php";break;
  320. case "object": $incl ="object.php";break;
  321. case "typeobject": $incl ="typeobject.php";break;
  322. case "input_data": $incl ="input_data.php";break;
  323. case "jobs": $incl ="jobs.php";break;
  324. case "dashboard": $incl ="dashboard.php";break;
  325. case "journal": $incl ="journal.php";break;
  326. case "filelib": $incl ="filelib/in.php";break;
  327. case "addproject": $incl ="addproject.php";break;
  328. case "oprt_management": $incl ="oprt_management.php";break;
  329. case "_peekdatasafe" : $incl = "_peekdatasafe.php";break;
  330. case "_log" : $incl = "_log.php"; break;
  331. //--Левое меню
  332. //Список устройств
  333. case "tmc/new" : case "tmc/list_materials" : case "tmc/detail/added" : $incl = "tmc/new.php"; break;
  334. case "tmc/repair" : case "tmc/repair_list" : $incl = "tmc/repair.php"; break;
  335. case "tmc/write" : case "tmc/write_list" : $incl = "tmc/write-off.php"; break;
  336. case "tmc/edit" : $incl = "tmc/edit.php"; break;
  337. //Передача устройств
  338. case "tmc/issued_tmcs" : $incl = "tmc/issued_tmcs.php"; break;
  339. case "tmc/free_tmcs" : $incl = "tmc/free_tmcs.php"; break;
  340. case "tmc/give" : case "tmc/list_materials_give" : $incl = "tmc/give.php"; break;
  341. case "tmc/take" : $incl = "tmc/take.php"; break;
  342. //Места хранения
  343. case "tmc/storage" : $incl = "tmc/new_storage.php"; break;
  344. case "tmc/find_cell" : $incl = "tmc/find_cell.php"; break;
  345. case "views/metrics" : $incl = "views/metrics.php"; break;
  346. default:
  347. }
  348. }
  349. else if ($cmdlevel==1) //company admin
  350. {
  351. switch($act)
  352. {
  353. case "penalties": $incl ="penalties.php";break;
  354. case "loco": $incl ="loco.php";break;
  355. case "locations": $incl ="locations.php";break;
  356. case "companies": $incl ="companies.php";break;
  357. case "accounts": $incl ="accounts.php";break;
  358. case "markers": $incl ="markers.php";break;
  359. case "tasks": $incl ="tasks.php";break;
  360. case "tasktypes": $incl ="tasktypes.php";break;
  361. case "docs": $incl ="docs.php";break;
  362. case "reports": $incl ="reports.php";break;
  363. case "staff": $incl ="staff.php";break;
  364. case "projects": $incl ="projects.php";break;
  365. case "objects": $incl ="objects.php";break;
  366. case "input_data": $incl ="input_data.php";break;
  367. case "jobs": $incl ="jobs.php";break;
  368. case "dashboard": $incl ="dashboard.php";break;
  369. case "journal": $incl ="journal.php";break;
  370. default:
  371. }
  372. }
  373. else if ($cmdlevel==2) //company ops
  374. {
  375. switch($act)
  376. {
  377. case "markers": $incl ="markers.php";break;
  378. case "tasks": $incl ="tasks.php";break;
  379. case "tasktypes": $incl ="tasktypes.php";break;
  380. case "docs": $incl ="docs.php";break;
  381. case "reports": $incl ="reports.php";break;
  382. case "staff": $incl ="staff.php";break;
  383. case "projects": $incl ="projects.php";break;
  384. case "input_data": $incl ="input_data.php";break;
  385. case "dashboard": $incl ="dashboard.php";break;
  386. case "journal": $incl ="journal.php";break;
  387. default:
  388. }
  389. }
  390. return array($incl,$accordnum);
  391. }
  392. function getConfirmTypeName($id)
  393. {
  394. global $link;
  395. $query = mysqli_query($link,"select * from confirmtypes where id=".$id);
  396. if ($query && $res = mysqli_fetch_array($query))
  397. {
  398. $name = $res['name'];
  399. }
  400. return $name;
  401. }
  402. function GrabConfirmTypes($company = 0)
  403. {
  404. global $link;
  405. $str = "select * from confirmtypes where company=0";
  406. $types = array();
  407. if ($company > 0)
  408. $str .= " OR company=".$company;
  409. //echo "GrabConfirmTypes $company $str";
  410. $query = mysqli_query($link,$str);
  411. while ($query && $res = mysqli_fetch_array($query))
  412. {
  413. array_push($types, $res);
  414. }
  415. //print_r($types);
  416. return $types;
  417. }
  418. function getConfirmTypebyTask($tid)
  419. {
  420. global $link;
  421. $query = mysqli_query($link,"select type from tasks where id=".$tid);
  422. if ($res = mysqli_fetch_array($query)) {
  423. $tasktype = $res['type'];
  424. // echo "tid $tid tasktype $tasktype ";
  425. }
  426. $query = mysqli_query($link,"select confirmtype from tasktypes where id=".$tasktype);
  427. if ($res = mysqli_fetch_array($query))
  428. {
  429. $confirmtype = intval($res['confirmtype']);
  430. // echo " confirmtype $confirmtype ";
  431. }
  432. return $confirmtype;
  433. }
  434. function GetOnlineAccountList($byteAnswer = false)
  435. {
  436. global $link;
  437. //$date2 = date(strtotime("-3 minutes"));
  438. // echo 'GetOnlineAccountList1';
  439. $date = 'last_seen_mobile';
  440. ///$query = mysqli_query("select * from accounts where DATE(".$date.") < (NOW() + INTERVAL 1 DAY)");
  441. $query = mysqli_query($link,"select * from accounts where ".$date." > (NOW() - INTERVAL 3 MINUTE)");
  442. $accs = array();
  443. while ($res = mysqli_fetch_array($query))
  444. {
  445. array_push($accs, $res);
  446. }
  447. if (!$byteAnswer)
  448. {
  449. ;
  450. // foreach ($accs as $acc)
  451. // {
  452. // echo 'online acc '.$acc['name'].'<br>';
  453. // }
  454. }
  455. else
  456. {
  457. $buf = "";//pack("C", 10);
  458. foreach ($accs as $acc) {
  459. $buf .= pack("l", $acc['id']); //заголовок - номер пакета 1б и длина 2б. v-ushort, c- byte, C- ubyte, s - short, L - int, l - uint
  460. }
  461. $c = ConstructVariablePacket(10, $buf);
  462. echo base64_encode($c);
  463. }
  464. }
  465. function Online($acc_id)
  466. {
  467. $acc = GetAccount($acc_id);
  468. return OnlineAccountCheck($acc['last_seen_mobile'], 1);
  469. }
  470. function TimeString($timeobj)
  471. {
  472. if ($timeobj != null)
  473. return $timeobj->format('d.m.Y H:i');
  474. //return date('d.m.Y H:i', $timeobj);
  475. }
  476. function OnlineAccountCheck($last_seen)
  477. {
  478. //var_dump($last_seen);
  479. global $onlineMobileTimeoutSeconds;
  480. $last_seen = date($last_seen);
  481. $time = (time()-strtotime($last_seen));
  482. //$date1 = date('d.m.Y H:i', strtotime($last_seen_mobile));
  483. if ($time <= $onlineMobileTimeoutSeconds)
  484. return true;
  485. return false;
  486. }
  487. function GrabTasksByType($type)
  488. {
  489. global $link;
  490. $str = "select * from tasks where type=$type";
  491. $query = mysqli_query($link, $str);
  492. $tasks = array();
  493. while ($res = mysqli_fetch_array($query))
  494. {
  495. array_push($tasks, $res);
  496. }
  497. return $tasks;
  498. }
  499. function DeleteTasksByType($task_type, $full=true)
  500. {
  501. global $link;
  502. $tasks = GrabTasksByType($task_type);
  503. foreach ($tasks as $task)
  504. {
  505. DeleteTask($task['id']);
  506. }
  507. }
  508. function ClearTaskTypeFromJobs($task_type)
  509. {
  510. global $link;
  511. $query1 = mysqli_query($link, "select * from jobtypes where $task_type in (tasktypes)");
  512. $jobs = array();
  513. while ($res1 = mysqli_fetch_array($query1))
  514. {
  515. array_push($jobs, $res1);
  516. }
  517. //print_r($jobs);
  518. foreach ($jobs as $job)
  519. {
  520. $tasktypes = explode(",", $job['tasktypes']);
  521. foreach (array_keys($tasktypes, "$task_type") as $key) {
  522. unset($tasktypes[$key]);
  523. }
  524. $tasktypes = implode(",", $tasktypes);
  525. mysqli_query($link, "update jobtypes set tasktypes = '$tasktypes'");
  526. }
  527. }
  528. function DeletePic($path)
  529. {
  530. unlink ( $path );
  531. }
  532. function DeleteTask($task_id, $full=true)
  533. {
  534. //echo "DeleteTask!!!";
  535. CheckPoint::DeleteByTask($task_id);
  536. global $link;
  537. if ($full)
  538. {
  539. $subtasks = GrabSubTasks($task_id);
  540. foreach ($subtasks as $sub)
  541. {
  542. DeleteTask($sub['id'], false);
  543. }
  544. }
  545. $accid = GetAccountFromTask($task_id);
  546. Account::ClearTasksFromAccount($accid);
  547. mysqli_query($link, "delete from tasks where id =".$task_id);
  548. }
  549. function GetImagePathFromTask($task)
  550. {
  551. $taskid = $task->id;
  552. $companyID = getCompanyByTask($taskid)[0];
  553. $project_id = $task->input_id;
  554. $imgpath = "data/$companyID/$project_id/$taskid/";
  555. return $imgpath;
  556. }
  557. function GetVideoPathFromTasktype($taskid)
  558. {
  559. // $rootPath = $_SERVER['DOCUMENT_ROOT'];
  560. // $videoPath = $rootPath."/guides/$taskid/";
  561. $videoPath = "guides/$taskid/";
  562. return $videoPath;
  563. }
  564. //in minutes
  565. function TimeSpent($timeStart, $timeEnd)
  566. {
  567. $accepted = strtotime($timeStart);
  568. $finished = strtotime($timeEnd);
  569. return round(($finished - $accepted)/60.0, 0, PHP_ROUND_HALF_UP);
  570. //return round (($finished - $accepted)/60.0, 2);
  571. }
  572. function TimeSpentForTaskFromArray($taskarr)
  573. {
  574. $accepted_time = $taskarr['accepted_time'];
  575. $finished_time = $taskarr['finished_time'];
  576. $accepted = strtotime($accepted_time);
  577. $finished = strtotime($finished_time);
  578. //return round (($finished - $accepted)/60.0, 2);
  579. return $finished - $accepted;
  580. //return round(($finished - $accepted)/60.0, 0, PHP_ROUND_HALF_UP);
  581. }
  582. function GetAssigneeNamesfromGlobal($taskid)
  583. {
  584. global $link;
  585. $str = "select id from tasks where parent_id = $taskid";
  586. $query1 = mysqli_query($link, $str);
  587. $accids = array();
  588. while ($res1 = mysqli_fetch_row($query1)) {
  589. // array_push($accids, $res1['assignees_arr']);
  590. $accid = FindTaskOwner($res1[0]);
  591. // var_dump($accid);
  592. // echo "tid ".$res1[0];
  593. array_push($accids, $accid);
  594. }
  595. $accarr = array();
  596. $accnames = array();
  597. foreach ($accids as $accid)
  598. {
  599. if (!in_array($accid, $accarr)) {
  600. array_push($accarr, $accid);
  601. $accname = GetAccount($accid)['name'];
  602. array_push($accnames, $accname);
  603. }
  604. }
  605. $assignee_names_parent = implode(",", $accnames);
  606. return $assignee_names_parent;
  607. }
  608. function EchoScriptName($name)
  609. {
  610. echo "<script>
  611. var page = '$name';";
  612. echo "</script>";
  613. }
  614. function GetProject($project_id)
  615. {
  616. global $link;
  617. $str = "select * from projects_locotech where id = $project_id";
  618. $query1 = mysqli_query($link, $str);
  619. if ($res1 = mysqli_fetch_array($query1)) {
  620. return $res1;
  621. }
  622. return 0;
  623. }
  624. function GetLocoSerial($project_id)
  625. {
  626. global $link;
  627. $str = "select loco_number from projects_locotech where id = $project_id";
  628. $query1 = mysqli_query($link, $str);
  629. if ($res1 = mysqli_fetch_row($query1)) {
  630. return $res1[0];
  631. }
  632. return 0;
  633. }
  634. function CleanTasks($project_id)
  635. {
  636. global $link;
  637. $str = "select id from tasks where input_id = $project_id";
  638. $query1 = mysqli_query($link, $str);
  639. while ($res1 = mysqli_fetch_row($query1)) {
  640. $taskid = $res1[0];
  641. DeleteTask($taskid);
  642. }
  643. }
  644. function EchoTask2(Task $task, $activeid, $parent = false)
  645. {
  646. global $entityManager;
  647. $tasktype_id = $task->type;
  648. /**
  649. * @var $type Tasktype
  650. */
  651. $type = Tasktype::Find($tasktype_id);
  652. $taskname = $type->name;
  653. $letter = $type->letter;
  654. $lettersign = "";
  655. if ($letter)
  656. $lettersign = "[Секция $letter]";
  657. $project_id = intval($task->project->id);
  658. $project = $task->project;
  659. //$action_id = $project->getAction();
  660. // $action = $project->getProjectType();
  661. $action = $project->projecttype;
  662. // if ($action != null)
  663. // if (!isset($action)) {
  664. // echo "action $action_id null";
  665. // return;
  666. // }
  667. try {
  668. $action_id = $action->id;
  669. $action_name = $action->name;
  670. }
  671. catch (Exception $e)
  672. {
  673. // echo "exception ".$e->getMessage();
  674. // \Doctrine\Common\Util\Debug::dump($action);
  675. }
  676. $created_time = TimeString($task->created);
  677. $taskid = $task->id;
  678. $assigned = TimeString($task->assigned);
  679. $zone = $task->zone_id;
  680. $zonename = GetZoneName($zone);
  681. $zone_req= $type->zone_required_id;
  682. $zone_req_name = GetZoneName($zone_req);
  683. $status = $task->status;
  684. $statusname = getTaskStatusName($status);
  685. $desc = $task->text;//$type->description;
  686. $loco = GetLocoSerial($project_id);
  687. $section = Section::Find($loco);
  688. // if ($section)
  689. // $loco = $section->getSectionNumber();
  690. $class = 'content__menu__task';
  691. $assignee_id = $task->assignees_arr;
  692. if ($activeid == $taskid)
  693. $class .= ' content__menu__task_active';
  694. else
  695. $class .= ' list';
  696. //PARENT LIST TO LEFT
  697. if ($parent) {
  698. // \Doctrine\Common\Util\Debug::dump(isset($task->getAccount());
  699. if ($task->getAccount() != null && 0 < $task->assignees_arr) {
  700. $assignee_names_parent = $task->getAccount()->name;//GetAssigneeNamesfromGlobal($taskid);
  701. }
  702. if ($status != '1')
  703. $statusname[0] .= ': '.$assignee_names_parent."<br> Выдана: $assigned ";
  704. //echo "111 $assignee_names_parent $taskid $class $taskname $desc $project_id $action_id $action_name $created_time ".$statusname[0];
  705. echo "<div onclick='SelectTask($taskid)' class='$class'>
  706. <h3 class='content__menu__task-title'>
  707. $taskid. $taskname <br>
  708. $lettersign<br>
  709. Описание: $desc
  710. </h3>
  711. <p class='content__menu__task-text'>
  712. Проект: $project_id<br>
  713. Тип проекта: $action_id. $action_name<br>
  714. Локомотив №: $loco <br>
  715. Создана: $created_time <br> <br>
  716. $statusname[0]
  717. </p>
  718. </div>";
  719. }
  720. else
  721. {
  722. $confirmtype = $type->confirmtype;
  723. $confirmname = getConfirmTypeName($confirmtype);
  724. $priority = $task->priority.'.';
  725. $assignee_names = GetAccount($assignee_id)['name'];
  726. if ($status =='2' || $status =='3' || $status =='5')
  727. $statusname[0] .= ': '.$assignee_names;
  728. $statustitle = $statusname[0];
  729. if ($status =='3')
  730. $statusname[0] = "<span style='color: green'>$statusname[0]</span>";
  731. $statusclass = 'content__main__item';
  732. switch ($status)
  733. {
  734. case '2': $statusclass .= ' content__main__item_wait'; break;
  735. case '3': $statusclass .= ' content__main__item_wait'; break;
  736. case '4': $statusclass .= ' content__main__item_wait'; break;
  737. case '5': $statusclass .= ' content__main__item_ready';
  738. $accepted_time = TimeString($task->accepted_time);
  739. $finished_time = TimeString($task->finished_time);
  740. $timetodo = intval($type->time_to_complete_minutes);
  741. $result = TimeSpent($accepted_time, $finished_time);
  742. //echo "acc $accepted_time fin $finished_time <br>";
  743. if (!$parent) {
  744. if ($result >= 0)
  745. $result = " за $result из $timetodo минут";
  746. $statusname[0] .= ': ' . $accepted_time.$result;
  747. }
  748. break;
  749. }
  750. $zoneOk = (intval($zone_req)== intval($zone));
  751. if ($zoneOk)
  752. {
  753. $zoneText = "соответствие";
  754. $zonecolor = "green";
  755. }
  756. else {
  757. $zoneText = "неверно";
  758. $zonecolor = "red";
  759. }
  760. if ($zone)
  761. $zonestring = "<span style='color: $zonecolor'>[$zoneText]</span>";
  762. else
  763. $zonestring = "";
  764. echo "
  765. <div class='$statusclass' title='$statustitle'>
  766. <h3 class='content__main__item__title'>
  767. $priority $taskname
  768. </h3>
  769. <p class='content__main__item__text'>
  770. Тип задачи: $tasktype_id<br>
  771. Описание: $desc <br>
  772. Тип подтверждения: $confirmname<br>
  773. $taskid. Создана $created_time<br>
  774. Выдана: $assigned<br>
  775. Зона выполнения: $zone ($zonename) $zonestring<br>
  776. Зона выполнения требуемая: $zone_req ($zone_req_name)<br>
  777. $statusname[0]<br><br>
  778. Вы можете <span class='content__main__item__del' onclick='DelTask($taskid)'>удалить</span>
  779. или <span class='content__main__item__recall' onclick='Revoke($assignee_id)'>отозвать</span> эту задачу,
  780. если что-то пошло не так.
  781. </p>
  782. </div>
  783. ";
  784. $cps = CheckPoint::FindAllByTask($taskid);
  785. if (sizeof($cps) > 0)
  786. {
  787. //echo "<p>";
  788. echo "<div style='margin-left: 50px'>";
  789. echo "<h4>Контрольная карта:</h4>";
  790. foreach ($cps as $cp) {
  791. if ($cp->parentCheckpointId == 0)
  792. {
  793. echo "<b>$cp->id. [$taskname]<br> $cp->name:</b><br>";
  794. }
  795. if ($cp->value != null)
  796. echo $cp->value . '<br>';
  797. // else {
  798. $children = $cp->childrenCheckpoints;
  799. if (0 < count($children))
  800. {
  801. echo '<ul>';
  802. foreach ($children as $child) {
  803. if ('1' == $child->state)
  804. {
  805. if ('' == $child->value)
  806. echo "<li>$child->name</li>";
  807. else
  808. echo "<li>$child->name: $child->value</li>";
  809. }
  810. // У чайлдов замечаний нет. ПИА.
  811. /*$textnotes = $entityManager->getRepository('Tasknote')->findBy(array('checkpoint_id' => $child->id));
  812. foreach ($textnotes as $tn)
  813. {
  814. echo "Замечание: $tn->text<br>";
  815. }/**/
  816. }
  817. echo '</ul>';
  818. }
  819. // }
  820. if ($cp->parentCheckpointId == 0)
  821. {
  822. $textnotes = $entityManager->getRepository('Tasknote')->findBy(array('checkpoint_id' => $cp->id));
  823. foreach ($textnotes as $tn)
  824. {
  825. echo "<pre> Замечание: $tn->text</pre>";
  826. }
  827. }
  828. }
  829. echo "</div><br><br>";
  830. }
  831. //echo "</p>";
  832. //LOAD MEDIA DATA
  833. $imgpath = GetImagePathFromTask($task);
  834. $files1 = scandir($imgpath);
  835. //print_r($files1);
  836. if (sizeof($files1) > 2)
  837. {
  838. echo '<div class="content__main__images" style="margin-left: 44px; margin-right:44px">';
  839. $x = '';
  840. foreach ($files1 as $file )
  841. {
  842. $prevx = $x;
  843. $x = pathinfo($file)['extension'];
  844. if ($prevx != '' && $prevx != $x)
  845. echo "<br>";
  846. if($file === '.' || $file === '..') {continue;}
  847. if ($x == 'jpg') {
  848. echo "<div class='content__main__imgwrap'>";
  849. echo "<img title='$file' src='$imgpath$file' width =112 height='84' class='content__main__img' onclick=\"openpic('" . $imgpath.$file . "')\">";
  850. echo '<img src="ProSysNew/delete.svg" alt="удалить" class="content__main__imgdel" onclick=delpic("'. $imgpath . $file .'")>';
  851. echo '</div>';
  852. }
  853. if ($x == 'mp3') {
  854. echo "<div class='content__main__imgwrap'>
  855. <img class='content__main__img' title='$file' onclick=\"openaudio('" . $imgpath . $file . "')\" src='images/audio.svg'>
  856. </div>";
  857. // echo "<a href='$imgpath$file'>$file</a>";
  858. }
  859. }
  860. echo '</div>';
  861. }
  862. $notes = FindTaskNotes($taskid);
  863. if (sizeof($notes) > 0) {
  864. echo "<div style='float:none; background-color: rgba(0,170,255,0.03); padding: 5px; border: solid; margin-right:44px; margin-left:44px; border-width: .5px; border-color: #9cb2c4; border-radius: 10px; border-top-left-radius: 0px;'><p><b>Текстовые заметки: </b></p>";
  865. foreach ($notes as $note) {
  866. if (!$note['checkpoint_id']) {
  867. $notedate = $note['date'];
  868. $noteid = $note['id'];
  869. $notetext = $note['text'];
  870. echo "<p><b>$noteid.</b> [$taskname] $notetext</p>";
  871. }
  872. }
  873. echo '</div><br><br>';
  874. }
  875. }
  876. //locotube
  877. if ($task->parent_id) {
  878. echo '<div class="content__main__images" style="margin-left: 44px; margin-right:44px">';
  879. showVideoLinks($task);
  880. // getTaskVideos($task);
  881. echo '</div>';
  882. }
  883. //video files
  884. echo '<div class="content__main__images" style="margin-left: 44px; margin-right:44px">';
  885. $ocsVideo = OCSgetvideo($taskid);
  886. $splitted = explode(",",$ocsVideo);
  887. $domain = "http://ocs.prmsys.net/video/";
  888. foreach ($splitted as $spl) {
  889. if ($spl == "")
  890. continue;
  891. $link = "$domain$spl";
  892. echo "<div class='content__main__imgwrap' onclick=\"openvideo('$link')\">
  893. <video height='144' class='content__main__img' preload='metadata' title='$link'>
  894. <source src='$link'>
  895. </video>
  896. </div>";
  897. }
  898. echo '</div>';
  899. echo '<div>';
  900. if ($status != '1')
  901. echo " <input style='margin-right: 20px' type='button' onclick='ReopenTask($taskid)' value='Открыть заново'>";
  902. echo '</div>';
  903. }
  904. function showVideoLinks($task)
  905. {
  906. $urls = \app\models\entity\Locotube::getLinks($task, 310);
  907. foreach ($urls as $url): ?>
  908. <a href="<?= $url ?>" target="_blank">
  909. <img style="width: 32px; height: 32px; margin-bottom: 14px" src="images/mp4.png" alt="mp4">
  910. </a>
  911. <? endforeach;
  912. }
  913. function getTaskVideos(Task $task)
  914. {
  915. if ('DateTime' != get_class($task->accepted_time)) return;
  916. $userId = $task->getAccount()->getId();
  917. $sp = DIRECTORY_SEPARATOR;
  918. $path = $sp . 'uploads' . $sp . 'locotube' . $sp . $userId . $sp;
  919. $fullPath = __DIR__ . $path;
  920. if (is_dir($fullPath)) {
  921. $files = scandir($fullPath);
  922. $start = $task->accepted_time;
  923. $finish = $task->finished_time;
  924. foreach ($files as $file) {
  925. if ($file[0] == '.') continue;
  926. $videoDate = parseDate($file);
  927. if ($start <= $videoDate && $videoDate <= $finish) { ?>
  928. <a href="/player.php?file=<?= $path . $file ?>" target="_blank">
  929. <img style="width: 32px; height: 32px; margin-bottom: 14px" src="images/mp4.png" alt="mp4">
  930. </a>
  931. <?php
  932. }
  933. }
  934. }
  935. }
  936. function parseDate(string $str)
  937. {
  938. $date = new DateTime();
  939. // $date->setTimezone(new DateTimeZone('+0010'));
  940. $y = substr($str, 0, 4);
  941. $m = substr($str, 5, 2);
  942. $d = substr($str, 7, 2);
  943. $date->setDate($y, $m, $d);
  944. $h = substr($str, 10, 2);
  945. $i = substr($str, 12, 2);
  946. $s = substr($str, 14, 2);
  947. $date->setTime($h, $i, $s);
  948. return $date;
  949. }
  950. function FindTaskNotes($taskID)
  951. {
  952. global $link;
  953. $query = mysqli_query($link,"select * from task_notes where task_id=".$taskID);
  954. $notes = array();
  955. while ($res1 = mysqli_fetch_array($query))
  956. {
  957. array_push($notes, $res1);
  958. }
  959. return $notes;
  960. }
  961. function ActionsForm($action_data, $c_action)
  962. {
  963. echo "<option selected value = '0' ><Выберите тип проекта></option >";
  964. foreach ($action_data as $val) {
  965. if ($val->id == $c_action)
  966. $sel = 'selected';
  967. else
  968. $sel = '';
  969. echo "<option $sel value = '".$val->id."' > ".$val->name."</option >";
  970. }
  971. }
  972. function AddJob($acc_id, $new_jobtype_id, $job_ids)
  973. {
  974. global $link;
  975. $job_ids .= ','.$new_jobtype_id;
  976. mysqli_query($link, "update accounts set jobtypes='".$job_ids."' where id=".$acc_id);
  977. echo "<span style='color: darkolivegreen'>Должность добавлена!</span><br><br>";
  978. }
  979. function JobTaskTypesIDs($job_id)
  980. {
  981. $tts = GrabJobTaskTypes($job_id);
  982. $arr = array();
  983. if (sizeof($tts) > 0) {
  984. foreach ($tts as $tt) {
  985. array_push($arr, $tt->id);
  986. }
  987. }
  988. return $arr;
  989. }
  990. function GrabJobTaskTypes($job_id)
  991. {
  992. /**
  993. * @var Jobtype$jobtype
  994. */
  995. $tasktypes = array();
  996. $jobtype = Jobtype::Find($job_id);
  997. if ($jobtype != null)
  998. $tasktypes = $jobtype->getTaskTypes();
  999. return $tasktypes;
  1000. }
  1001. //function GrabJobTaskTypes($job_id)
  1002. //{
  1003. // global $link;
  1004. // $subtaskarr = array();
  1005. // $query = mysqli_query($link,"select tasktypes from jobtypes where id=".$job_id);
  1006. // if ($res = mysqli_fetch_row($query)) {
  1007. // $tasktype_data = $res[0];
  1008. // $subtaskarr = explode(",", $tasktype_data);
  1009. // }
  1010. // return array_filter($subtaskarr);
  1011. //}
  1012. function ShowJobTasks($job_id)
  1013. {
  1014. $subtaskarr = GrabJobTaskTypes($job_id);
  1015. foreach ($subtaskarr as $taskid) {
  1016. $taskarr = GrabTasktype($taskid);
  1017. $name = $taskarr['name'];
  1018. if ($name != '')
  1019. echo '<span style=\'color:blue\'>'.$taskarr['name'].'</span> <b>|</b> ';
  1020. }
  1021. }
  1022. function FillArrayString($elem_name, $make_array = false)
  1023. {
  1024. //echo sizeof($_REQUEST)." elname $elem_name<br>";
  1025. //print_r($_REQUEST);
  1026. $subtask_arr = array();
  1027. foreach (array_keys($_REQUEST) as $var) {
  1028. //echo "var $var ${$var} <br>";
  1029. $sub = substr($var, 0, -1);
  1030. $sub2 = substr($var, 0, -2);
  1031. $sub3 = substr($var, 0, -3);
  1032. //echo "sub $sub<br>";
  1033. if ($sub === $elem_name || $sub2 === $elem_name || $sub3 === $elem_name)
  1034. {
  1035. if ($_REQUEST[$var] != '')
  1036. array_push($subtask_arr, $_REQUEST[$var]);
  1037. }
  1038. }
  1039. $subtask_string = implode(",", $subtask_arr);
  1040. if ($make_array) {
  1041. $subtask_string = $subtask_arr;
  1042. }
  1043. //print_r($subtask_arr);
  1044. return $subtask_string;
  1045. }
  1046. function ShowTasksSelect($arr, $c_action=0, $id="", $keyword, $alg=false)
  1047. {
  1048. if ($id !="") {
  1049. $id = "id='$id'";
  1050. }
  1051. $max = sizeof($arr);
  1052. echo "<select onchange='AddSelect(this.value, $max)' $id class='form-input content__main__form__goal' name='$keyword"."1' >";
  1053. echo '<option value=""></option>';
  1054. $count=1;
  1055. foreach ($arr as $res1) {
  1056. if ($c_action ==0 || $res1->action == $c_action)
  1057. {
  1058. $tasktype_id = $res1->id;
  1059. $taskname = $res1->name;
  1060. if (!isset($taskname)) {
  1061. $type = $res1->type;
  1062. $name = GetTaskNameAndDesc($type)[0];
  1063. $taskname = "$tasktype_id. $name [$type]";
  1064. }
  1065. echo "<option value='$tasktype_id'>$count. $taskname</option>";
  1066. $count++;
  1067. }
  1068. }
  1069. echo '</select><br>';
  1070. if ($alg) {
  1071. echo "<select style='margin-left:20px ' class='form-input content__main__form__goal' id='alg' name='alg' >";
  1072. echo '<option value="">Собрать результат выполнения задачи</option>';
  1073. echo '<option value="">Составить промежуточную таблицу</option>';
  1074. echo '<option value="">Алгоритм3</option>';
  1075. echo '<option value="">Алгоритм4</option>';
  1076. echo '</select><br>';
  1077. }
  1078. }
  1079. function GetJobtypes($companyID)
  1080. {
  1081. global $link;
  1082. $query1 = mysqli_query($link, "select * from jobtypes where company=$companyID");
  1083. $jobtypes = array();
  1084. while ($res1 = mysqli_fetch_array($query1))
  1085. {
  1086. array_push($jobtypes, $res1);
  1087. }
  1088. return $jobtypes;
  1089. }
  1090. function GetAccountFromTask($task_id)
  1091. {
  1092. global $link;
  1093. $str = "select assignees_arr from tasks where id = ".$task_id;
  1094. $query1 = mysqli_query($link, $str);
  1095. if ($res1 = mysqli_fetch_row($query1)) {
  1096. return $res1[0];
  1097. }
  1098. return null;
  1099. }
  1100. function GetVagrantTagID($acc_id)
  1101. {
  1102. global $link;
  1103. $str = "select tagid from vagrant_log where acc_id = $acc_id ORDER BY id DESC limit 1";
  1104. $query1 = mysqli_query($link, $str);
  1105. if ($res1 = mysqli_fetch_row($query1)) {
  1106. return $res1[0];
  1107. }
  1108. return null;
  1109. }
  1110. function GetAccount($acc_id)
  1111. {
  1112. global $link;
  1113. $str = "select * from accounts where id = ".$acc_id;
  1114. $query1 = mysqli_query($link, $str);
  1115. if ($res1 = mysqli_fetch_array($query1)) {
  1116. return $res1;
  1117. }
  1118. return null;
  1119. }
  1120. function GetAccountJobs($acc_id)
  1121. {
  1122. global $link;
  1123. // echo 'GetAccountJobs '.$acc_id;
  1124. //get free accs (without active tasks)
  1125. $str = "select * from accounts where id = ".$acc_id;
  1126. $query1 = mysqli_query($link, $str);
  1127. if ($res1 = mysqli_fetch_array($query1)) {
  1128. // echo 'jobs '.$res1['jobtypes'];
  1129. $jobtypes = explode(",",$res1['jobtypes']);
  1130. return $jobtypes;
  1131. }
  1132. }
  1133. function GetCMDName($cmdlevel)
  1134. {
  1135. global $link;
  1136. $str = "select name from accounttypes where type = ".$cmdlevel;
  1137. $query1 = mysqli_query($link, $str);
  1138. if ($res1 = mysqli_fetch_array($query1))
  1139. return $res1['name'];
  1140. }
  1141. function GetTasksFromProjectString($projectid)
  1142. {
  1143. global $link;
  1144. $str = "select tasks from projects_locotech where id = $projectid";
  1145. $query1 = mysqli_query($link, $str);
  1146. $ret = array();
  1147. if ($res1 = mysqli_fetch_row($query1))
  1148. {
  1149. $ret = $res1[0];
  1150. }
  1151. return $ret;
  1152. }
  1153. function GetTasksForProject($projectid, $status=0, $inactiveproject=0, $subs = 0)
  1154. {
  1155. global $link;
  1156. $taskstring = GetTasksFromProjectString($projectid);
  1157. if ($inactiveproject != 0)
  1158. {
  1159. $str = "select COUNT(id) from tasks where id in ($taskstring) and (status=2 or status=3)";
  1160. $query1 = mysqli_query($link, $str);
  1161. if ($res1 = mysqli_fetch_row($query1))
  1162. {
  1163. $count = intval($res1[0]);
  1164. if ($count > 0) {
  1165. echo "Found started tasks!";
  1166. return;
  1167. }
  1168. }
  1169. }
  1170. if ($subs > 0) {
  1171. //echo "subss!";
  1172. $tasksarr = explode(",", $taskstring);
  1173. foreach ($tasksarr as $task_id)
  1174. {
  1175. $parent = GrabTask($task_id);
  1176. if ($parent['status'] == $status) {
  1177. return GrabSubTasks($task_id);
  1178. }
  1179. }
  1180. }
  1181. $statusstr = '';
  1182. if ($status != 0)
  1183. $statusstr .= " and status=$status";
  1184. // $str = "select * from tasks where input_id = ".$projectid." and parent_id=0";
  1185. $str = "select * from tasks where id in ($taskstring)$statusstr";
  1186. $query1 = mysqli_query($link, $str);
  1187. $ret = array();
  1188. while ($res1 = mysqli_fetch_array($query1))
  1189. array_push($ret, $res1);
  1190. return $ret;
  1191. }
  1192. function GetJobNames($jobtypes)
  1193. {
  1194. global $link;
  1195. $jobnames = array();
  1196. foreach ($jobtypes as $jobid)
  1197. {
  1198. // echo ' jobid '.$jobid;
  1199. $str = "select name from jobtypes where id = ".$jobid;
  1200. $query1 = mysqli_query($link, $str);
  1201. if ($res1 = mysqli_fetch_array($query1)) {
  1202. $jobname = $res1['name'];
  1203. // echo ' jobname '.$jobname;
  1204. //$jobnames[$jobid] = $jobname;
  1205. array_push($jobnames, $jobname);
  1206. }
  1207. }
  1208. return $jobnames;
  1209. }
  1210. function TaskReopen($tid)
  1211. {
  1212. global $link;
  1213. mysqli_query($link, "update tasks set status=1, assignees_arr=0 where id=".$tid);
  1214. }
  1215. function FindUrgentAccounts()
  1216. {
  1217. global $link;
  1218. $str ="select DISTINCT a.id, p.id from accounts a join tasks t on t.assignees_arr= a.id join projects_locotech p on p.id = t.input_id where p.urgent=1 and p.status<5";
  1219. $query = mysqli_query($link, $str);
  1220. $retarr = array();
  1221. while ($res = mysqli_fetch_row($query))
  1222. {
  1223. $retarr[] = $res[0];
  1224. }
  1225. return $retarr;
  1226. }
  1227. function CheckPreferredAssignee(&$opentasks, $echo)
  1228. {
  1229. global $link;
  1230. $pids = array();
  1231. $prefs = array();
  1232. foreach ($opentasks as &$opentask)
  1233. {
  1234. $tid = $opentask['id'];
  1235. $pref = intval($opentask['preferred_assignee']);
  1236. if ($pref > 0) {
  1237. if ($echo)
  1238. echo ("CheckPreferredAssignee pref>0: $tid");
  1239. $opentask['status'] = 2;
  1240. $str = "update tasks set status = 2, assigned=NOW(), assignees_arr=$pref where id=$tid";
  1241. mysqli_query($link, $str);
  1242. $pid = intval($opentask['parent_id']);
  1243. if ($pid > 0 && !in_array($pid, $pids)) {
  1244. $pids[] = $pid;
  1245. $prefs[$pid] = $pref;
  1246. }
  1247. }
  1248. }
  1249. if ($echo) {
  1250. $plen = sizeof($pids);
  1251. echo("pids len: $plen");
  1252. }
  1253. foreach ($pids as $pid)
  1254. {
  1255. $str = "update tasks set status = 2, assigned=NOW(), assignees_arr=".$prefs[$pid]." where id=$pid";
  1256. mysqli_query($link, $str);
  1257. }
  1258. }
  1259. function TasksAssignCore($freeaccounts, $task_id, $execute, $project_id, $echo = false)
  1260. {
  1261. global $link, $companyID;
  1262. $assigned_tasks = array();
  1263. $accsused = array();
  1264. $project = null;
  1265. if ($task_id =='' || !isset($task_id))
  1266. {
  1267. if ($project_id == 0)
  1268. $opentasks = GrabOpenTasks('subtasks'); //array of mysql res, tasks status=1
  1269. else {
  1270. $project = Project::Find($project_id);
  1271. $opentasks = GetTasksForProject($project_id, 1, 0, 1);
  1272. }
  1273. }
  1274. else
  1275. $opentasks = GrabTasksFromGlobal($task_id);
  1276. //select * from accounts a left outer join tasks t on t.assignees_arr= a.id left outer join projects_locotech p on p.id = t.input_id where p.urgent=1 and a.id=1
  1277. CheckPreferredAssignee($opentasks, $echo);
  1278. if ($echo)
  1279. {
  1280. echo "<br>opentasks:<br>";
  1281. var_dump($opentasks);
  1282. echo "<br>freeaccounts:<br>";
  1283. var_dump($freeaccounts);
  1284. }
  1285. $assigned_accs = array();
  1286. // if ($echo) {
  1287. // echo "<br>freeaccounts";
  1288. // var_dump($freeaccounts);
  1289. // }
  1290. foreach ($freeaccounts as $acc_id=>$jobtypesIds)
  1291. {
  1292. $parent_id = 0;
  1293. $assigned_accs[$acc_id] = array();
  1294. if (!in_array($acc_id, $accsused))
  1295. {
  1296. $tasktypesJob = array();
  1297. foreach ($jobtypesIds as $job_type) {
  1298. $tasktypesJob = array_merge($tasktypesJob, JobTaskTypesIDs($job_type));
  1299. }
  1300. foreach ($opentasks as $opentask)
  1301. {
  1302. $taskid = $opentask['id'];
  1303. if (intval($opentask['status']) > 1)
  1304. continue;
  1305. $exists = array_key_exists($taskid, $assigned_tasks);
  1306. if ($echo)
  1307. echo ' key exists '.$taskid.' '.($exists == true).'<br>';
  1308. if (!$exists) {
  1309. // echo '!exists';
  1310. if (in_array($opentask['type'], $tasktypesJob)) {
  1311. if ($echo)
  1312. echo ' job available task type '.$opentask['type'].' ';
  1313. $pid = intval($opentask['parent_id']);
  1314. if ($pid != $parent_id && in_array($acc_id, $accsused)) {//parent change = stop for this acc
  1315. if ($echo)
  1316. echo "cont1";
  1317. continue;
  1318. }
  1319. else
  1320. $parent_id = $pid;
  1321. $parent = GrabTask($parent_id);
  1322. $parenttype = $parent['type'];
  1323. $tgrab = GrabTasktype($parenttype);
  1324. $tsize = sizeof($tgrab);
  1325. if ($tsize == 0)
  1326. DeleteTasksByType($parenttype);
  1327. //фикс блуждающих подзадач без парента и тасктипа парента
  1328. if (($parent_id > 0 && GrabTask($parent_id) == null) || $tsize == 0)
  1329. {
  1330. if ($echo)
  1331. echo "skip2 id $parent_id<br>";
  1332. continue;
  1333. }
  1334. Assign($accsused, $assigned_tasks, $assigned_accs, $acc_id, $taskid, $execute);
  1335. if ($echo) {
  1336. echo "assigned_tasks:<br>";
  1337. var_dump($assigned_tasks);
  1338. echo "assigned_accs: <br>";
  1339. var_dump($assigned_accs);
  1340. }
  1341. }
  1342. }
  1343. }
  1344. if ($execute)
  1345. {
  1346. $parent_updated = false;
  1347. foreach ($assigned_accs as $acc)
  1348. {
  1349. if (sizeof($assigned_accs[$acc_id]) == 0)
  1350. continue;
  1351. $tasks = implode(',', $acc); //taskarr
  1352. foreach ($acc as $tsk) {
  1353. if (in_array($tsk, $assigned_accs[$acc_id])) {
  1354. if ($echo) {
  1355. echo '<br>updating task ' . $tsk . ' setting ass ' . $acc_id;
  1356. }
  1357. // var_dump($acc_id);
  1358. OCStaskstatus($tsk, 2, $acc_id);
  1359. $str = "update tasks set status = 2, assigned=NOW(), assignees_arr=$acc_id where id=$tsk";
  1360. require_once 'tmc/yiiInit_once.php';
  1361. \app\models\ElasticLog::command((int)$tsk, 'Назначение');
  1362. //echo '<br>'.$str;
  1363. mysqli_query($link, $str); //создание подзадач
  1364. }
  1365. }
  1366. if ($parent_id != 0)
  1367. $tasks = $parent_id.','.$tasks;
  1368. // mysqli_query($link, "update accounts set active_task_ids = '$tasks' where id=".$acc_id); //создание подзадач
  1369. if ($parent_id != 0 && !$parent_updated) {
  1370. $parent_updated = true;
  1371. OCStaskstatus($parent_id, 2, $acc_id);
  1372. mysqli_query($link, "update tasks set status = 2, assigned=NOW(), assignees_arr=$acc_id where id=" . $parent_id);
  1373. $proj = getProjectByTask($parent_id);
  1374. mysqli_query($link, "update projects_locotech set status = 2 where id=".$proj['id']);
  1375. }
  1376. }
  1377. }
  1378. }
  1379. }
  1380. return $assigned_accs;
  1381. }
  1382. function CheckPush($accounts, $echo=false)
  1383. {
  1384. foreach ($accounts as $account)
  1385. {
  1386. // if ($echo)
  1387. // \Doctrine\Common\Util\Debug::dump($account);
  1388. $lastpush = TimeString($account->last_push_message_sent);
  1389. $time = (time()-strtotime($lastpush));
  1390. if ($echo)
  1391. echo $account->name." time $time";
  1392. if ($time > 30)
  1393. SendPush($account->id, "Check your SMoPP application!", "");
  1394. }
  1395. }
  1396. function TasksAssign($task_id, $execute, $project_id = 0, $echo = false, $source = 0)
  1397. {
  1398. //1 ищем онлайн акки без тасков
  1399. //2 определяем основные должности акков
  1400. //3 определяем замещяющие должности акков
  1401. //4 определяем доступные задачи по должностям
  1402. //5 берем активные (невыданные) задачи
  1403. //6 выдаем подходящим основным аккам их подзадачи
  1404. //7 выдаем подходящим замещающим аккам их подзадачи
  1405. global $companyID;
  1406. $freeaccountsPrimary = array();
  1407. $freeaccountsSecondary = array();
  1408. /**
  1409. * @var $company Company
  1410. */
  1411. $company = Company::Find($companyID);
  1412. // $last_assign = strtotime(TimeString($company->last_assign));
  1413. // $time = (time()-$last_assign);
  1414. // if ($echo)
  1415. // {
  1416. // var_dump($last_assign);
  1417. // var_dump($time);
  1418. // }
  1419. //
  1420. // if ($time < 10)
  1421. // {
  1422. // if ($echo)
  1423. // echo "часто";
  1424. // return null;
  1425. // }
  1426. $companyID = $company->id;
  1427. $company->last_assign = new \DateTime("now");
  1428. $company->Save();
  1429. if ($company == null)
  1430. return array();
  1431. $project = null;
  1432. $urgent = 0;
  1433. if ($project_id > 0)
  1434. {
  1435. $project = Project::Find($project_id);
  1436. if ($project != null && intval($project->getStatus()) < 5 )
  1437. {
  1438. $urgent = $project->urgent;
  1439. }
  1440. }
  1441. if ($urgent >0)
  1442. $accs = $company->GetOnlineAccounts(true, true);
  1443. else
  1444. $accs = $company->GetIdleAccounts();
  1445. if ($echo) {
  1446. var_dump($urgent);
  1447. if ($urgent >0)
  1448. echo "urgent accs: ";
  1449. else
  1450. echo "idle accs: ";
  1451. \Doctrine\Common\Util\Debug::dump($accs);
  1452. echo "<br>";
  1453. }
  1454. $online_counter = sizeof($accs);
  1455. foreach ($accs as $acc)
  1456. {
  1457. $jobtypesIdsPrimary = array();
  1458. $jobtypesIdsSecondary = array();
  1459. /**
  1460. * @var $acc Account
  1461. */
  1462. // $last_seen_mobile = TimeString($acc->getLastSeenMobile());
  1463. // $online_mobile = OnlineAccountCheck($last_seen_mobile);
  1464. // if (!$online_mobile)
  1465. // continue;
  1466. // else
  1467. // $online_counter++;
  1468. $acc_id = $acc->getId();
  1469. $jobtypes = $acc->getJobtypesExtended();
  1470. foreach ($jobtypes[0] as $jobtype)
  1471. {
  1472. $jobtypesIdsPrimary[] = $jobtype->id;
  1473. }
  1474. foreach ($jobtypes[1] as $jobtype)
  1475. {
  1476. $jobtypesIdsSecondary[] = $jobtype->id;
  1477. }
  1478. $freeaccountsPrimary[$acc_id] = $jobtypesIdsPrimary;
  1479. $freeaccountsSecondary[$acc_id] = $jobtypesIdsSecondary;
  1480. }
  1481. if ($online_counter == 0)
  1482. {
  1483. if ($echo)
  1484. echo "<h3><span style='color:red'>Задачи не выданы в работу! Нет подходящих исполнителей онлайн</span></h3>";
  1485. return array();
  1486. }
  1487. $assigned_accs1 = TasksAssignCore($freeaccountsPrimary, $task_id, $execute, $project_id, $echo);
  1488. if ($echo) {
  1489. echo "<br> assigned_accs1: ";
  1490. var_dump($assigned_accs1);
  1491. }
  1492. // $assigned_accs2 = array();
  1493. $accs1str = "";
  1494. foreach ($assigned_accs1 as $id=>$taskids)
  1495. {
  1496. if (sizeof($taskids) > 0) {
  1497. $acstr = implode(',',$taskids);
  1498. $accs1str .= " $id: $acstr | ";
  1499. SendPush($id, "You have a new task!", $acstr);
  1500. }
  1501. // var_dump($taskids);echo "<br>";
  1502. // foreach ($taskids as $tid)
  1503. // {
  1504. // $task = Task::Find($tid);
  1505. // if ($task != null)
  1506. // {
  1507. // $tt = $task->type;
  1508. // }
  1509. // }
  1510. // if (sizeof($freeaccountsSecondary[$id]) > 0 && sizeof($taskids)>0) {
  1511. // $task = Task::Find($taskids[0]);
  1512. // if ($task != null) {
  1513. // $proj_id = $task->input_id;
  1514. //// var_dump($proj_id);echo "<br>";
  1515. // $freeaccs = array($id => $freeaccountsSecondary[$id]);
  1516. //// var_dump($freeaccs);echo "<br>";
  1517. // $assigned_accs2 = TasksAssignCore($freeaccs, '', true, $proj_id);
  1518. //// var_dump($assigned_accs2);echo "<br>";
  1519. // }
  1520. // }
  1521. if (sizeof($taskids) > 0)
  1522. unset($freeaccountsSecondary[$id]);
  1523. }
  1524. $assigned_accs3 = TasksAssignCore($freeaccountsSecondary, $task_id, $execute, $project_id, $echo);
  1525. foreach ($assigned_accs3 as $id=>$taskids)
  1526. {
  1527. if (sizeof($taskids) > 0) {
  1528. $acstr = implode(',',$taskids);
  1529. $accs1str .= " $id: $acstr | ";
  1530. SendPush($id, "You have a new task!", $acstr);
  1531. }
  1532. }
  1533. if ($accs1str != '')
  1534. LogTaskAssign("Account: $source $accs1str");
  1535. // if ($echo) {
  1536. // echo "<br> assigned_accs3: ";
  1537. // var_dump($assigned_accs3);
  1538. // }
  1539. $retarr = array_merge($assigned_accs1, $assigned_accs3);
  1540. // var_dump($retarr);
  1541. return $retarr;
  1542. }
  1543. function LogTaskAssign($text)
  1544. {
  1545. global $link;
  1546. mysqli_query($link, "insert into task_assign_log (msg, created) values ('$text', NOW())");
  1547. }
  1548. function SendPush($accid, $text, $tskid)
  1549. {
  1550. global $link;
  1551. $acc = Account::Find($accid);
  1552. if ($acc != null) {
  1553. $android_token_id = $acc->android_token_id;
  1554. if ($android_token_id) {
  1555. //$f = file_get_contents("http://corp.prmsys.net/?act=staff");
  1556. $text = "AccountId $accid taskids $tskid ".$text;
  1557. $text = urlencode($text);
  1558. require_once "fcm/SendNotification.php";
  1559. $oldKey = ($acc->getCompany()->id == 1);
  1560. Send($text, $android_token_id, $oldKey);
  1561. $str = "update accounts set last_push_message_sent = NOW() where id=$accid";
  1562. mysqli_query($link, $str);
  1563. // $f = file_get_contents("http://corp.prmsys.net/fcm/SendNotification.php?text=$text&token=$android_token_id");
  1564. // echo $f;
  1565. }
  1566. // else
  1567. // echo "invalid token";
  1568. }
  1569. }
  1570. function SetAccordNum($num)
  1571. {
  1572. echo '<div style="display: none" id="accordnum">'.$num.'</div>';
  1573. }
  1574. function GetTaskNameAndDesc($type)
  1575. {
  1576. global $link;
  1577. $str = "select name, description from tasktypes where id = $type";
  1578. $query1 = mysqli_query($link, $str);
  1579. if ($res1 = mysqli_fetch_row($query1)) {
  1580. return $res1;
  1581. }
  1582. return '';
  1583. }
  1584. function GetAccountTasksStatus()
  1585. {
  1586. }
  1587. function Assign(&$accsused, &$assigned_tasks, &$assigned_accs, $acc_id, $taskid, $execute=false)
  1588. {
  1589. global $link;
  1590. //echo '<br>foundacc ' . $acc_id .' task type '.$opentask['type'].' task id '.$opentask['id'].'<br>';
  1591. // echo '<br>foundacc ' . $acc_id;
  1592. if (!in_array($acc_id, $accsused)) {
  1593. array_push($accsused, $acc_id);
  1594. }
  1595. $req = "select account_id from refuses where created > date_sub(NOW(), interval 2 minute) and account_id = "
  1596. .$acc_id
  1597. ." and main_task_id = (select parent_id from tasks where id = "
  1598. .$taskid
  1599. .")";
  1600. //echo '<pre>'; var_dump($req);
  1601. $taskrefused = mysqli_query($link, $req);
  1602. //echo '<pre>'; var_dump($taskrefused);
  1603. $isrefusedthistask = mysqli_fetch_array($taskrefused);/**/
  1604. //echo '<pre>'; var_dump($isrefusedthistask);
  1605. //die();
  1606. if (count($isrefusedthistask) == 0)
  1607. {
  1608. $assigned_tasks[$taskid] = $acc_id;
  1609. array_push($assigned_accs[$acc_id],$taskid);
  1610. }
  1611. //echo '<br>Assigned opentask type '.$opentask['type'].' id '.$opentask['id'].'<br>';
  1612. return false;
  1613. }
  1614. function GrabTasksForAccount($acc_id, $status=0)
  1615. {
  1616. global $link;
  1617. $str = "select * from tasks where assignees_arr = $acc_id";
  1618. if ($status != 0)
  1619. $str .= " and status=".$status;
  1620. $str .= " and status < 5";
  1621. //$str = "select *,name from tasks,tasktypes where tasks.id = $task_id and tasktypes.id = tasks.type";
  1622. $query1 = mysqli_query($link, $str);
  1623. $tasks = array();
  1624. while ($res1 = mysqli_fetch_array($query1)) {
  1625. array_push($tasks, $res1);
  1626. }
  1627. return $tasks;
  1628. }
  1629. function GrabTasksFromGlobal($task_id)
  1630. {
  1631. // echo 'GrabTask '.$task_id;
  1632. global $link;
  1633. $str = "select * from tasks where parent_id = $task_id and status=1";
  1634. //$str = "select *,name from tasks,tasktypes where tasks.id = $task_id and tasktypes.id = tasks.type";
  1635. $query1 = mysqli_query($link, $str);
  1636. $tasks = array();
  1637. while ($res1 = mysqli_fetch_array($query1)) {
  1638. array_push($tasks, $res1);
  1639. }
  1640. return $tasks;
  1641. }
  1642. function GrabTask($task_id)
  1643. {
  1644. global $link;
  1645. $str = "select * from tasks where id = ".$task_id;
  1646. //$str = "select *,name from tasks,tasktypes where tasks.id = $task_id and tasktypes.id = tasks.type";
  1647. $query1 = mysqli_query($link, $str);
  1648. if ($res1 = mysqli_fetch_array($query1)) {
  1649. $result = sizeof($res1);
  1650. //echo 'GrabTask '.$task_id.' size '.$result;
  1651. return $res1;
  1652. }
  1653. //echo 'GrabTask res null';
  1654. return null;
  1655. }
  1656. function GrabTasks($taskstring)
  1657. {
  1658. global $link;
  1659. $tasks = array();
  1660. $task_ids = explode(',',$taskstring);
  1661. // echo 'taskstring '.$taskstring;
  1662. foreach ($task_ids as $task_id)
  1663. {
  1664. $str = "select * from tasks where id = $task_id";
  1665. $query1 = mysqli_query($link, $str);
  1666. if ($res1 = mysqli_fetch_array($query1)) {
  1667. array_push($tasks, $res1);
  1668. }
  1669. }
  1670. return $tasks;
  1671. }
  1672. function GrabSubTasks($parent_id)
  1673. {
  1674. global $link;
  1675. $subtasks = array();
  1676. $str = "select * from tasks where parent_id = $parent_id";
  1677. $query1 = mysqli_query($link, $str);
  1678. while ($res1 = mysqli_fetch_array($query1)) {
  1679. array_push($subtasks, $res1);
  1680. }
  1681. return $subtasks;
  1682. }
  1683. function GrabOpenTasks($flag = 'all')
  1684. {
  1685. if ($flag == 'subtasks')
  1686. $add = ' and parent_id > 0';
  1687. else
  1688. $add = ' and parent_id = 0';
  1689. global $link, $companyID;
  1690. //$str = "select * from tasks where status = 1";
  1691. $str = "select t.* from tasks t join projects_locotech p on t.input_id = p.id and p.company=$companyID where t.status = 1";
  1692. // echo $str;
  1693. //echo "opentasks $str<br>";
  1694. $query1 = mysqli_query($link, $str.$add);
  1695. $alltasks = array();
  1696. while ($res1 = mysqli_fetch_assoc($query1)) {
  1697. $id = $res1['id'];
  1698. $parent_id = $res1['parent_id'];
  1699. //echo "parent_id $parent_id ";
  1700. if ($flag == 'subtasks' && GrabTask($parent_id) == null)
  1701. {
  1702. echo "parent_id skip $parent_id<br>";
  1703. continue;
  1704. }
  1705. array_push($alltasks, $res1);
  1706. if ($flag == 'all') { //subtasks in main select
  1707. $subs = GrabSubTasks($id);
  1708. $alltasks = array_merge($alltasks, $subs);
  1709. }
  1710. }
  1711. // var_dump($alltasks);
  1712. return $alltasks;
  1713. }
  1714. function GrabTasktype($id)
  1715. {
  1716. global $link;
  1717. $str = "select * from tasktypes where id=$id";
  1718. $query1 = mysqli_query($link, $str);
  1719. if ($res1 = mysqli_fetch_array($query1)) {
  1720. return $res1;
  1721. }
  1722. return array();
  1723. }
  1724. function GetListFromDB($class, $key, $value, $sortby="id", $sort="ASC")
  1725. {
  1726. global $entityManager;
  1727. return $entityManager->getRepository($class)->findBy(array($key => $value), array($sortby => $sort));
  1728. }
  1729. function GetArrayFromDB($class, $array, $sortby="id", $sort="ASC")
  1730. {
  1731. global $entityManager;
  1732. return $entityManager->getRepository($class)->findBy($array, array($sortby => $sort));
  1733. }
  1734. function GrabActions($id)
  1735. {
  1736. $actions = array();
  1737. return $actions;
  1738. }
  1739. function CreateTasks($tasktypesarr, $input_id=0)
  1740. {
  1741. global $link;
  1742. //echo "CreateTasks sizetask ".sizeof($tasktypesarr);
  1743. $maintasks = array();
  1744. foreach ($tasktypesarr as $tasktype)
  1745. {
  1746. /**
  1747. * @var Tasktype $tasktype
  1748. */
  1749. if ($tasktype->main_task == '1')
  1750. {
  1751. $tid = $tasktype->id;
  1752. $subtaskarr = explode(",", $tasktype->subtasks);
  1753. // $subtaskarr = $tasktype->getTasktypes();
  1754. $str = "INSERT INTO tasks (type, status, priority, created, input_id) VALUES ($tid, 1, 0, NOW(), $input_id)";
  1755. // echo $str;
  1756. $result = mysqli_query($link, $str); //создание глобальной задачи
  1757. if (mysqli_affected_rows($link) >0 )
  1758. {
  1759. $parent_id = mysqli_insert_id($link);
  1760. array_push($maintasks, $parent_id);
  1761. $priority = 1;
  1762. foreach ($subtaskarr as $subid) {
  1763. $str = "insert into tasks (type, parent_id, priority, status, created, input_id) values ($subid, $parent_id, $priority, 1, NOW(), $input_id)";
  1764. $sub_id = mysqli_insert_id($link);
  1765. require_once 'tmc/yiiInit_once.php';
  1766. \app\models\ElasticLog::command((int)$sub_id);
  1767. //создаем парентов
  1768. $types = \CheckPointTypes\CheckPointType::GetCheckPointTypesByTask($subid);
  1769. if (sizeof($types) > 0) {
  1770. $q = mysqli_query($link, "select MAX(id) from tasks");
  1771. if ($res = mysqli_fetch_row($q))
  1772. {
  1773. $myid = intval($res[0]);
  1774. foreach ($types as $typeID) {
  1775. // echo "create type " . $typeID['cp_type_id'];
  1776. //var_dump($typeID['cp_type_id']);die();
  1777. $cpt = \CheckPointTypes\CheckPointType::CreateFromID($typeID['cp_type_id']);
  1778. if ($cpt != null)
  1779. $cp = \CheckPoints\CheckPoint::CreateFromType($cpt, null, $myid+1);
  1780. }
  1781. }
  1782. }
  1783. mysqli_query($link, $str); //создание подзадач
  1784. $priority++;
  1785. }
  1786. }
  1787. }
  1788. }
  1789. if (sizeof($maintasks) > 0) {
  1790. //echo " <span style='color: green'>Задачи созданы для проекта $input_id!</span>";
  1791. $taskstring = implode(",",$maintasks);
  1792. AddTasksToProject($taskstring, $input_id);
  1793. }
  1794. // else
  1795. // echo '<span style="color: red;"> Нет ни одной основной задачи!</span><br>';
  1796. }
  1797. function AddTasksToProject($taskstring, $input_id)
  1798. {
  1799. global $link;
  1800. $str = "update projects_locotech set tasks = '$taskstring' where id= $input_id";
  1801. mysqli_query($link, $str);
  1802. }
  1803. function GrabTasktypesStringFromAction($actionid)
  1804. {
  1805. global $link;
  1806. $str = "select tasktypes from project_types where id=$actionid";
  1807. $query1 = mysqli_query($link, $str);
  1808. $ret = array();
  1809. if ($res1 = mysqli_fetch_row($query1))
  1810. {
  1811. $ret = $res1[0];
  1812. }
  1813. return $ret;
  1814. }
  1815. //получить сабтаски по компании
  1816. //получить таски по компании
  1817. //получить и таски и сабтаски по компании
  1818. function GrabTasktypes($chooseSubtasks = "all")
  1819. {
  1820. global $link, $companyID, $entityManager;
  1821. //$list = GetListFromDB('Tasktype', 'company', $companyID, 'id', 'DESC');
  1822. $str = "SELECT t FROM Tasktype t"; //DOCTRINE
  1823. $str .= " WHERE t.company=$companyID";
  1824. if ($chooseSubtasks == "subs")
  1825. $str .= " and t.main_task = 0";
  1826. else if ($chooseSubtasks == "tasks")
  1827. $str .= " and t.main_task = 1";
  1828. //$str .= ' ORDER BY t.name ASC';
  1829. $str .= ' ORDER BY t.id DESC';
  1830. $query = $entityManager->createQuery($str);
  1831. $list = $query->getResult();
  1832. return $list;
  1833. }
  1834. function GrabTasktypesIDs($chooseSubtasks = "all")
  1835. {
  1836. global $link, $companyID, $entityManager;
  1837. //$list = GetListFromDB('Tasktype', 'company', $companyID, 'id', 'DESC');
  1838. $str = "SELECT t.id FROM Tasktype t"; //DOCTRINE
  1839. $str .= " WHERE t.company=$companyID";
  1840. if ($chooseSubtasks == "subs")
  1841. $str .= " and t.main_task = 0";
  1842. else if ($chooseSubtasks == "tasks")
  1843. $str .= " and t.main_task = 1";
  1844. $str .= ' ORDER BY t.id DESC';
  1845. $query = $entityManager->createQuery($str);
  1846. $list = $query->getResult();
  1847. $ids = array();
  1848. foreach ($list as $el)
  1849. array_push($ids, $el['id']);
  1850. return $ids;
  1851. }
  1852. function getCurrentDeviceId($accountId)
  1853. {
  1854. global $link;
  1855. $did = 0;
  1856. $query = mysqli_query($link,"select active_device_id from accounts where id = $accountId");
  1857. if ($query && $res = mysqli_fetch_row($query))
  1858. {
  1859. $did = intval($res[0]);
  1860. }
  1861. return $did;
  1862. }
  1863. function LogOff()
  1864. {
  1865. }
  1866. function getActiveSession($accountId)
  1867. {
  1868. global $link;
  1869. $sid = 0;
  1870. $query0 = mysqli_query($link,"select MAX (id) from sessions where account_id = ". $accountId);
  1871. if ($query0 && $res = mysqli_fetch_row($query0))
  1872. {
  1873. $sid = intval($res[0]);
  1874. }
  1875. if ($sid)
  1876. {
  1877. $query = mysqli_query($link,"select start, device_id from sessions where id=".$sid);
  1878. if ($query && $res = mysqli_fetch_row($query))
  1879. {
  1880. $start = $res[0];
  1881. $did = intval($res[1]);
  1882. }
  1883. }
  1884. return array("id"=>$sid, "start"=>$start, "device_id"=>$did);
  1885. }
  1886. function getProjectByTask($taskId)
  1887. {
  1888. global $link;
  1889. $query = mysqli_query($link,"select input_id from tasks where id = ".$taskId);
  1890. if ($query && $res = mysqli_fetch_array($query))
  1891. {
  1892. return GetProject($res['input_id']);
  1893. }
  1894. return null;
  1895. }
  1896. function getProjectsByAction($actionId)
  1897. {
  1898. global $link;
  1899. $str = "select * from projects_locotech where action = $actionId";
  1900. $query1 = mysqli_query($link, $str);
  1901. $projarr = array();
  1902. while ($res1 = mysqli_fetch_array($query1)) {
  1903. array_push($projarr, $res1);
  1904. }
  1905. return $projarr;
  1906. }
  1907. function getProjectIDByTask($taskId)
  1908. {
  1909. global $link;
  1910. //$query = mysqli_query($link,"select * from tasktypes tt INNER JOIN tasks t ON t.type = tt.id");
  1911. $query = mysqli_query($link,"select input_id from tasks where id = ".$taskId);
  1912. $pid = 0;
  1913. if ($query && $res = mysqli_fetch_array($query))
  1914. {
  1915. $pid = intval($res['input_id']);
  1916. }
  1917. return $pid;
  1918. }
  1919. function getCompanyByTask($taskId)
  1920. {
  1921. global $link;
  1922. //$query = mysqli_query($link,"select * from tasktypes tt INNER JOIN tasks t ON t.type = tt.id");
  1923. $query = mysqli_query($link,"select * from tasktypes tt, tasks t where t.type = tt.id and t.id = ".$taskId);
  1924. if ($query && $res = mysqli_fetch_array($query))
  1925. {
  1926. $companyid = intval($res['company']);
  1927. }
  1928. return getCompanyByID($companyid);
  1929. }
  1930. function getCompanyByAccount($accountId)
  1931. {
  1932. global $link;
  1933. $query = mysqli_query($link,"select company from accounts where id = $accountId");
  1934. if ($query && $res = mysqli_fetch_array($query)) {
  1935. $companyid = intval($res['company']);
  1936. }
  1937. return getCompanyByID($companyid);
  1938. }
  1939. function getCompanyByID($companyid)
  1940. {
  1941. global $link;
  1942. $query = mysqli_query($link,"select name, logo from companies where id = $companyid");
  1943. if ($query && $res = mysqli_fetch_array($query))
  1944. {
  1945. $mycompany = $res['name'];
  1946. $mycompanylogo = $res['logo'];
  1947. }
  1948. return array($companyid, $mycompany, $mycompanylogo);
  1949. }
  1950. $oses = "WinPhoneWinXPMacOSLinuxUbuntuiPhoneiPodiPadAndroidBlackBerryMobile";
  1951. function getOS()
  1952. {
  1953. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  1954. //echo "user_agent ".$user_agent;
  1955. $os_platform = "Unknown OS Platform";
  1956. $os_array = array(
  1957. '/ARM/i' => 'WinPhone',
  1958. '/windows nt 5.2/i' => 'WinXP',
  1959. '/windows nt 5.1/i' => 'WinXP',
  1960. '/windows xp/i' => 'WinXP',
  1961. '/windows/i' => 'Windows',
  1962. '/macintosh|mac os x/i' => 'MacOS',
  1963. '/mac_powerpc/i' => 'MacOS',
  1964. '/linux/i' => 'Linux',
  1965. '/ubuntu/i' => 'Ubuntu',
  1966. '/iphone/i' => 'iPhone',
  1967. '/ipod/i' => 'iPod',
  1968. '/ipad/i' => 'iPad',
  1969. '/android/i' => 'Android',
  1970. '/blackberry/i' => 'BlackBerry',
  1971. '/webos/i' => 'Mobile'
  1972. // '/windows nt 10/i' => 'Windows 10',
  1973. // '/windows nt 6.3/i' => 'Windows 8.1',
  1974. // '/windows nt 6.2/i' => 'Windows 8',
  1975. // '/windows nt 6.1/i' => 'Windows 7',
  1976. // '/windows nt 6.0/i' => 'Windows Vista',
  1977. // '/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
  1978. // '/windows nt 5.1/i' => 'Windows XP',
  1979. // '/windows xp/i' => 'Windows XP',
  1980. // '/windows nt 5.0/i' => 'Windows 2000',
  1981. // '/windows me/i' => 'Windows ME',
  1982. // '/win98/i' => 'Windows 98',
  1983. // '/win95/i' => 'Windows 95',
  1984. // '/win16/i' => 'Windows 3.11',
  1985. // '/macintosh|mac os x/i' => 'Mac OS X',
  1986. // '/mac_powerpc/i' => 'Mac OS 9',
  1987. // '/linux/i' => 'Linux',
  1988. // '/ubuntu/i' => 'Ubuntu',
  1989. // '/iphone/i' => 'iPhone',
  1990. // '/ipod/i' => 'iPod',
  1991. // '/ipad/i' => 'iPad',
  1992. // '/android/i' => 'Android',
  1993. // '/blackberry/i' => 'BlackBerry',
  1994. // '/webos/i' => 'Mobile'
  1995. );
  1996. foreach ($os_array as $regex => $value)
  1997. {
  1998. if (preg_match($regex, $user_agent))
  1999. {
  2000. $os_platform = $value;
  2001. return $os_platform;
  2002. }
  2003. }
  2004. }
  2005. function GetTaskStatusFromID($taskid)
  2006. {
  2007. $task = GrabTask($taskid);
  2008. $parent = intval($task['parent_id']);
  2009. if ($parent > 0)
  2010. return intval($task['status']);
  2011. else
  2012. {
  2013. $tasks = GrabSubTasks($taskid);
  2014. $assigned = 0;
  2015. $accepted = 0;
  2016. $hold = 0;
  2017. $done = 0;
  2018. $lentasks = sizeof($tasks);
  2019. foreach ($tasks as $task)
  2020. {
  2021. $status = intval($task['status']);
  2022. switch ($status) {
  2023. case 2:
  2024. $assigned++;
  2025. break;
  2026. case 3:
  2027. $accepted++;
  2028. break;
  2029. case 4:
  2030. $hold++;
  2031. break;
  2032. case 5:
  2033. $done++;
  2034. break;
  2035. }
  2036. }
  2037. if ($done == $lentasks && $lentasks > 0)
  2038. {
  2039. return 5;
  2040. }
  2041. elseif ($accepted > 0 || $assigned > 0)
  2042. {
  2043. return 2;
  2044. }
  2045. else
  2046. return 1;
  2047. }
  2048. }
  2049. function GetTaskStatus($taskid)
  2050. {
  2051. $task = GrabTask($taskid);
  2052. $parent = intval($task['parent_id']);
  2053. if ($parent > 0)
  2054. return intval($task['status']);
  2055. else
  2056. {
  2057. $tasks = GrabSubTasks($taskid);
  2058. $assigned = 0;
  2059. $accepted = 0;
  2060. $hold = 0;
  2061. $done = 0;
  2062. $lentasks = sizeof($tasks);
  2063. foreach ($tasks as $task)
  2064. {
  2065. $status = intval($task['status']);
  2066. switch ($status) {
  2067. case 2:
  2068. $assigned++;
  2069. break;
  2070. case 3:
  2071. case 6:
  2072. case 7:
  2073. $accepted++;
  2074. break;
  2075. case 4:
  2076. $hold++;
  2077. break;
  2078. case 5:
  2079. $done++;
  2080. break;
  2081. }
  2082. }
  2083. if ($done == $lentasks && $lentasks > 0)
  2084. {
  2085. return 5;
  2086. }
  2087. elseif ($accepted > 0)
  2088. {
  2089. return 2;
  2090. }
  2091. elseif ($assigned > 0)
  2092. return 2;
  2093. else
  2094. return 1;
  2095. }
  2096. }
  2097. function GetProjectStatus($projid)
  2098. {
  2099. //$proj = GetProject($projid);
  2100. /**
  2101. * @var $proj Project
  2102. */
  2103. $proj = Project::Find($projid);
  2104. $tasks = $proj->getTasks();
  2105. //$tasks = GetTasksForProject($projid);
  2106. $assigned = 0;
  2107. $accepted = 0;
  2108. $hold = 0;
  2109. $done = 0;
  2110. $numcommands = 0;
  2111. $lentasks = 0;
  2112. foreach ($tasks as $task)
  2113. {
  2114. // if ($task['parent_id']=='0') {
  2115. if ($task->parent_id==0) {
  2116. $lentasks++;
  2117. $numcommands++;
  2118. //$status = intval($task['status']);
  2119. // $status = GetTaskStatus($task['id']);
  2120. switch ($task->status) {
  2121. case 2:
  2122. $assigned++;
  2123. break;
  2124. case 3:
  2125. $accepted++;
  2126. break;
  2127. case 4:
  2128. $hold++;
  2129. break;
  2130. case 5:
  2131. $done++;
  2132. break;
  2133. }
  2134. }
  2135. }
  2136. //echo $lentasks;
  2137. if ($done == $lentasks && $lentasks > 0)
  2138. {
  2139. return 5;
  2140. }
  2141. elseif ($done > 0)
  2142. {
  2143. return 2;
  2144. }
  2145. elseif ($accepted > 0 || $assigned > 0)
  2146. {
  2147. return 2;
  2148. }
  2149. else
  2150. return 1;
  2151. }
  2152. function ASUSG($asusg_job_mapped_id)
  2153. {
  2154. global $link;
  2155. $query = mysqli_query($link, "select * from asusg_job2launch where id=$asusg_job_mapped_id");
  2156. $taskarr = array();
  2157. while ($query && $res = mysqli_fetch_assoc($query))
  2158. {
  2159. array_push($taskarr, $res);
  2160. }
  2161. return $taskarr;
  2162. }
  2163. function TaskStatusSet($taskid, $status, $confirmdata = '', $main = 0)
  2164. {
  2165. global $link;
  2166. if ($status == '5') {
  2167. $finished = ", finished_time=NOW()";
  2168. }
  2169. if ($confirmdata != '')
  2170. $conf = ", confirm_data ='$confirmdata'";
  2171. mysqli_query($link, "update tasks set status = $status$finished$conf where id=$taskid");
  2172. $proj = getProjectByTask($taskid);
  2173. $project_id = intval($proj['id']);
  2174. if (($main && $status == '5') || $status == '2' || $status == '3')
  2175. {
  2176. /**
  2177. * @var $proj Project
  2178. */
  2179. if ($project_id > 0) {
  2180. $proj = Project::Find($project_id);
  2181. if ($proj != null) {
  2182. OCStaskstatus($taskid, $status, 0);
  2183. $proj->setStatus($status);
  2184. $proj->Save();
  2185. if ($status == 5)
  2186. $proj->AddCompletedWork();
  2187. }
  2188. }
  2189. }
  2190. // mysqli_query($link, "update projects_locotech set status = $status where id=".$proj['id']);
  2191. }
  2192. function WriteLog($accid, $text='')
  2193. {
  2194. global $link;
  2195. $text = urldecode($text);
  2196. $str = "INSERT into text_log (msg, stamp) values ('$accid: $text',NOW())";
  2197. mysqli_query($link, $str);
  2198. }
  2199. //0 = неудача основная причина, 1 - успех, 2 - неудача по зоне, 3 - неудача таймаут, 4 - неудача по ТМЦ (объект)
  2200. function TaskConfirmCheck(Task $task, $zoneId)
  2201. {
  2202. global $link;
  2203. if (!$task) {
  2204. WriteLog("TaskConfirmCheck task not found", "");
  2205. return 0;
  2206. }
  2207. /**
  2208. * @var $tasktype Tasktype
  2209. */
  2210. $tasktype = Tasktype::Find($task->type);
  2211. try {
  2212. $company = Company::Find($tasktype->company);
  2213. if ($company)
  2214. {
  2215. $timeout = $company->GetConfirmTimeout();
  2216. $accepted = TimeString($task->accepted_time);
  2217. $time = ($timeout+strtotime($accepted));
  2218. if (time() < $time) {
  2219. WriteLog("TaskConfirmCheck task $task->id timeout fail, time:", $time);
  2220. return 3;
  2221. }
  2222. }
  2223. } catch (\Throwable $e) {
  2224. echo $e->getMessage();
  2225. }
  2226. $objtype = $tasktype->object_type;
  2227. $tmcId = FindTMCId($objtype);
  2228. $proj = $task->project;//getProjectByTask($tid);
  2229. $taskid = $task->GetId();
  2230. $confirmtype = getConfirmTypebyTask($taskid);
  2231. $result = 1;
  2232. switch ($confirmtype)
  2233. {
  2234. case 2: //Скан QR кода, пришедшего с объектом - доверяем клиенту
  2235. break;
  2236. case 8: //picture
  2237. $imgpath = GetImagePathFromTask($task);
  2238. $files1 = scandir($imgpath);
  2239. $len = sizeof($files1);
  2240. if ($len <= 2) //dots
  2241. {
  2242. //echo "TaskConfirmCheck images false";
  2243. WriteLog("TaskConfirmCheck task $task->id failed image: ", $len);
  2244. $result = 0;
  2245. }
  2246. break;
  2247. case 9: //text or audio note
  2248. $notes = FindTaskNotes($taskid);
  2249. if (sizeof($notes) == 0)
  2250. {
  2251. //echo "TaskConfirmCheck notes false";
  2252. WriteLog("TaskConfirmCheck task $task->id failed notes: ", sizeof($notes));
  2253. $result = 0;
  2254. }
  2255. break;
  2256. case 12: //control map
  2257. require_once "server.php";
  2258. $task->control_map_checked = TaskControlMapCheck($taskid);
  2259. $task->save();
  2260. // var_dump($task->control_map_checked);
  2261. if (intval($task->control_map_checked) != 1) {
  2262. WriteLog("TaskConfirmCheck task $task->id failed control map: ",intval($task->control_map_checked));
  2263. $result = 0;
  2264. }
  2265. break;
  2266. case 13: //масломер
  2267. if (intval($tmcId) > 0 && isset($proj)) {
  2268. $section = $task->getSection();
  2269. // WriteLog("TaskConfirmCheck request sec id $section->id ", isset($proj));
  2270. if ($section) {
  2271. require_once("curlexec.php");
  2272. $str = "http://oiltest.prmsys.net/api/session/finish?deviceId=$tmcId&sectionId=$section->id";
  2273. // WriteLog("TaskConfirmCheck request string ", $str);
  2274. $response = CURLrequestGET($str, ["uuid-key: 07a13c8907d1-6a7bdba1-a2fz-aatgu4j"]);
  2275. WriteLog("TaskConfirmCheck request response ", $response);
  2276. if (intval($response) > 0) {
  2277. WriteLog("TaskConfirmCheck task $task->id failed with oil tmc, api response: ", $response);
  2278. return 4;
  2279. }
  2280. }
  2281. }
  2282. break;
  2283. case 14:
  2284. $zone_req= $tasktype->zone_required_id;
  2285. if ($zone_req && $zoneId != $zone_req)
  2286. $result = 2;
  2287. break;
  2288. case 17: //AR object recognized
  2289. $str = "select ar_object_id from tasks where id=$taskid";
  2290. $query = mysqli_query($link, $str);
  2291. if ($result = mysqli_fetch_object($query)) {
  2292. if (!$result->ar_object_id)
  2293. $result = 0;
  2294. }
  2295. break;
  2296. case 18: //smart contract
  2297. global $host, $port;
  2298. WriteLog(666, "18!!!");
  2299. if (CheckConnection())
  2300. readfile("http://$host:$port/WebAPI/1");
  2301. break;
  2302. }
  2303. //WriteLog("workToExecute =>1", 'start'.$taskid);
  2304. $exec = \app\models\MappingworksModel::workToExecute($taskid);
  2305. //WriteLog("workToExecute =>2", $exec);
  2306. //if ( false == $exec) {
  2307. // $result = 0;
  2308. //}
  2309. //echo "TaskConfirmCheck tid $taskid ctype $confirmtype result $result path $imgpath fileslen $len ";
  2310. return $result;
  2311. }
  2312. //SERVER FUNCTIONS
  2313. function GetLastZoneId($accId, $echo=false)
  2314. {
  2315. global $link;
  2316. $str = "SELECT * from user_positions where acc_id=$accId and DATE_ADD(ts, INTERVAL 1 minute) > now() order by id desc limit 1";
  2317. $result_pos = mysqli_query($link, $str);
  2318. if ($obj = mysqli_fetch_object($result_pos)) {
  2319. $location_id = $obj->location_id;
  2320. $x = $obj->coord_x;
  2321. $y = $obj->coord_y;
  2322. }
  2323. //scale 1 зоны = 10 клеткам x1 z1 - position, x2 z2 - scale
  2324. //координаты юзеров сейчас увеличены в
  2325. //x/10 < x1+x2 && x/10 > x1-x2 &&
  2326. $str = "SELECT * from zones where ($x < x1+x2*5) and ($x > x1-x2*5) and ($y < z1+z2*5) and ($y > z1-z2*5) and location_id=$location_id limit 1";
  2327. WriteLog($accId, $str);
  2328. if ($echo)
  2329. {
  2330. echo $str;
  2331. }
  2332. $result_zones = mysqli_query($link, $str);
  2333. if ($obj = mysqli_fetch_object($result_zones)) {
  2334. $zone_id = $obj->id;
  2335. $desc = $obj->description;
  2336. return $zone_id;
  2337. }
  2338. return 0;
  2339. }
  2340. function GetZoneName($zone_id)
  2341. {
  2342. global $link;
  2343. $str = "SELECT description from zones where id=$zone_id";
  2344. $result_pos = mysqli_query($link, $str);
  2345. if ($obj = mysqli_fetch_object($result_pos)) {
  2346. return $obj->description;
  2347. }
  2348. return "";
  2349. }
  2350. function IsMeasurement($task_id)
  2351. {
  2352. global $link;
  2353. $str = "SELECT * from asusg_measurements where smopp_task_id=$task_id order by id desc limit 1";
  2354. $result_pos = mysqli_query($link, $str);
  2355. if ($obj = mysqli_fetch_object($result_pos)) {
  2356. //WriteLog("IsMeasurement task $task_id", "true");
  2357. return $obj;
  2358. }
  2359. WriteLog("IsMeasurement task $task_id", "false");
  2360. return null;
  2361. }
  2362. function Measurements2JSON($proj_id)
  2363. {
  2364. global $link;
  2365. $work_id = 0;
  2366. $user_id = 0;
  2367. $jsonStringReturn = array();
  2368. $measurements = array();
  2369. $str = "SELECT mes.* from tasks as t join asusg_measurements as mes on mes.smopp_task_id=t.id where t.input_id=$proj_id";
  2370. $result_pos = mysqli_query($link, $str);
  2371. while ($obj = mysqli_fetch_object($result_pos)) {
  2372. if (!$work_id)
  2373. $work_id = $obj->work_id;
  2374. if (!$user_id)
  2375. $user_id = json_decode($obj->worker)->id;
  2376. $measurement = [];
  2377. $measurement['measurement_id'] = $obj->measurement_id;
  2378. $measurement['characteristic_id'] = $obj->characteristic_id;
  2379. $measurement['measurement_stage'] = $obj->measurement_stage;
  2380. $measurement['measurement_value'] = $obj->measurement_value;
  2381. $measurement['comment'] = json_decode($obj->measurement_comment)->text;
  2382. $measurements[] = $measurement;
  2383. }
  2384. $jsonStringReturn['user_id'] = $user_id;
  2385. $jsonStringReturn['work_id'] = $work_id;
  2386. $jsonStringReturn['measurements'] = $measurements;
  2387. return $jsonStringReturn;
  2388. }
  2389. function Measurements2JSONTask($task_id, $user_id, $ignore_hardware = true)
  2390. {
  2391. global $link;
  2392. $work_id = 0;
  2393. $jsonStringReturn = array();
  2394. $measurements = array();
  2395. $str = "SELECT mes.* from tasks as t join asusg_measurements as mes on mes.smopp_task_id=t.id where t.id=$task_id";
  2396. $result_pos = mysqli_query($link, $str);
  2397. while ($obj = mysqli_fetch_object($result_pos)) {
  2398. if ($ignore_hardware && intval($obj->is_hw_measurement)>0)
  2399. continue;
  2400. if (!$work_id)
  2401. $work_id = $obj->work_id;
  2402. if (!$user_id)
  2403. {
  2404. $user_id = json_decode($obj->worker)->id;
  2405. }
  2406. if ($obj->value_type == 'boolean')
  2407. {
  2408. $obj->measurement_value = $obj->measurement_value == 1 ?true:false;
  2409. }
  2410. $measurement = [];
  2411. $measurement['measurement_id'] = $obj->measurement_id;
  2412. $measurement['characteristic_id'] = $obj->characteristic_id;
  2413. $measurement['measurement_stage'] = $obj->measurement_stage;
  2414. $measurement['measurement_value'] = $obj->measurement_value;
  2415. $measurement['comment'] = json_decode($obj->measurement_comment)->text;
  2416. $measurements[] = $measurement;
  2417. }
  2418. $jsonStringReturn['user_id'] = $user_id;
  2419. $jsonStringReturn['work_id'] = $work_id;
  2420. $jsonStringReturn['measurements'] = $measurements;
  2421. return $jsonStringReturn;
  2422. }
  2423. function WriteMeasurementsToTWX($dict)
  2424. {
  2425. require_once 'curlexec.php';
  2426. //$url = "http://devplatform.digitaldepot.ru:8085/Thingworx/Things/2050UserLibraryExp/Services/write_work_measurements_v2";
  2427. //$result = CURLrequestPOST($url, ["AppKey: 6a7bdbaa-6bc1-4159-a2f4-07a13c8907d1"], $dict);
  2428. $url = "http://qaplatform.digitaldepot.ru:8085/Thingworx/Things/2050UserLibraryExp/Services/write_work_measurements_v2";
  2429. $result = CURLrequestPOST($url, ["AppKey: 33cd23bb-3b03-4638-afef-7104a13e9211"], $dict);
  2430. WriteLog("WriteMeasurementsToTWX input ".json_encode($dict), $result);
  2431. }
  2432. function TaskConfirm($num, $id, $tid, $confirm_data, $verbose=false)
  2433. {
  2434. // try {received
  2435. //TODO брать сабтаски из их таблицы по исполнителю
  2436. ob_start();
  2437. global $link, $companyID;
  2438. /**
  2439. * @var $task Task
  2440. */
  2441. $task = Task::Find($tid);
  2442. if ($task != null) {
  2443. $accid = intval($task->assignees_arr);
  2444. if ($accid != intval($id))
  2445. {
  2446. TaskConfirmResult($num, 0, $tid);
  2447. EnqueueCMD($id, "21");
  2448. WriteLog("TaskConfirm task $tid failed account id $id != ",$accid);
  2449. return;
  2450. }
  2451. if (intval($task->status) == 5)
  2452. {
  2453. TaskConfirmResult($num, 1, $tid);
  2454. WriteLog("TaskConfirm task $tid failed status already ",$task->status);
  2455. return;
  2456. }
  2457. $zoneId = GetLastZoneId($id);
  2458. $checkresult = TaskConfirmCheck($task, $zoneId);
  2459. if ($verbose)
  2460. echo "result $checkresult";
  2461. if ($checkresult != 1) {
  2462. TaskConfirmResult($num, $checkresult, $tid);
  2463. return;
  2464. }
  2465. /**
  2466. * @var $account Account
  2467. */
  2468. $account = Account::Find($id);
  2469. if ($account != null) {
  2470. $tasks = $account->tasks;
  2471. $account->last_action = new \DateTime("now");
  2472. $account->Save();
  2473. $companyID = $account->getCompany()->id;
  2474. $measurement = IsMeasurement($tid);
  2475. if ($measurement)
  2476. {
  2477. //TODO понять что таск записан - тогда слать тру
  2478. $task_hw = $task->asusg_task_hw_measurement_id;
  2479. if ($task_hw)
  2480. {
  2481. if (intval($task->status) != 7) {
  2482. TaskConfirmResult($num, 0, $tid);
  2483. WriteLog("TaskConfirm task $tid failed status is ", $task->status);
  2484. return;
  2485. }
  2486. }
  2487. $json = Measurements2JSONTask($tid, $account->uuid);
  2488. \app\models\entity\Metrics::log(2, $num, 'write_work_measurements_v2, workId = ' . ($json['work_id'] ?? 0));
  2489. WriteMeasurementsToTWX($json);
  2490. \app\models\entity\Metrics::log(3, $num, 'write_work_measurements_v2, workId = ' . ($json['work_id'] ?? 0));
  2491. }
  2492. else
  2493. {
  2494. $subs = explode(" ",$task->name);
  2495. if ($subs[0] === "Замер")
  2496. {
  2497. TaskConfirmResult($num, 0, $tid);
  2498. return;
  2499. }
  2500. }
  2501. mysqli_query($link, "update tasks set status=5, zone_id = $zoneId, finished_time = NOW() where id=$tid");
  2502. \app\models\ElasticLog::command((int)$task->id, 'Завершение');
  2503. $parenttask = Task::Find($task->parent_id);
  2504. $subtasks = GrabSubTasks($parenttask->id);
  2505. $numconfirmed = 0;
  2506. foreach ($subtasks as $sub) {
  2507. $status = intval($sub['status']);
  2508. $subtask = Task::Find($sub['id']);
  2509. // \Doctrine\Common\Util\Debug::dump($subtask);
  2510. if ($status == 5 && $tasks->contains($subtask)) {
  2511. $numconfirmed++;
  2512. }
  2513. }
  2514. if ($verbose)
  2515. {
  2516. var_dump($numconfirmed);
  2517. var_dump(sizeof($subtasks));
  2518. }
  2519. if ($numconfirmed == sizeof($subtasks)) {
  2520. $parenttask->status = 5;
  2521. $parenttask->Save();
  2522. $proj = $parenttask->project;
  2523. if ($verbose)
  2524. \Doctrine\Common\Util\Debug::dump($proj);
  2525. if ($proj != null) {
  2526. //write entire project
  2527. // if (IsMeasurement($tid))
  2528. // {
  2529. // $json = Measurements2JSON($proj->id);
  2530. // WriteMeasurementsToTWX($json);
  2531. // }
  2532. $proj->finished_time = new \DateTime("now");;
  2533. $proj->setStatus(GetProjectStatus($proj->id));
  2534. if ($verbose)
  2535. var_dump($proj->getStatus());
  2536. $proj->Save();
  2537. //временный хардкод - ПРИЕМКА создает опись
  2538. TempStartProject($proj);
  2539. }
  2540. TasksAssign('', true, 0, false);
  2541. }
  2542. WriteLog("TaskConfirm success $tid account id $accid","");
  2543. OCStaskstatus($tid, 5, $accid);
  2544. TaskConfirmResult($num, 1, $tid);
  2545. // $buf = pack("C", $num);
  2546. // $buf .= pack("Cl*", 1, $tid);
  2547. // ob_get_clean();
  2548. // echo base64_encode($buf);
  2549. }
  2550. }
  2551. // } catch (\Throwable $e) {
  2552. // echo $e->getMessage();
  2553. // }
  2554. }
  2555. function TaskConfirmResult($num, $res, $tid)
  2556. {
  2557. \app\models\entity\Metrics::log(4, $num, 'taskId = ' . $tid);
  2558. $buf = pack("C", $num);
  2559. $buf .= pack("Cl*", $res, $tid);
  2560. ob_get_clean();
  2561. echo base64_encode($buf);
  2562. }
  2563. /**
  2564. * Проверяет есть ли секция с заданными параметрами, если нет, то создаёт её.
  2565. * Обновляет диагностическую карту
  2566. *
  2567. * @param $letter
  2568. * @param $series
  2569. * @param $number
  2570. * @param $subnumber
  2571. */
  2572. function CheckSection($letter, $series, $number, $subnumber)
  2573. {
  2574. if ($subnumber) {
  2575. global $entityManager;
  2576. $sec = $entityManager->getRepository('Section')->findBy([
  2577. 'locomotive_series' => $series,
  2578. 'section_number' => $number,
  2579. 'section_subnumber' => $subnumber,
  2580. "letter" => $letter
  2581. ]);
  2582. if (sizeof($sec) > 0) {
  2583. $section = $sec[0];
  2584. } else {
  2585. $series = LocoSeries::Find("$series");
  2586. if ($series != null) {
  2587. $section = new Section();
  2588. $section->letter = $letter;
  2589. $section->series = $series;
  2590. $section->setSectionSubnumber($subnumber);
  2591. $section->setSectionNumber($number);
  2592. }
  2593. }
  2594. if ($section != null) {
  2595. UpdateDiagnosticMap($section, true);
  2596. }
  2597. }
  2598. }
  2599. function UpdateDiagnosticMap(Section $section, $save = false)
  2600. {
  2601. $params['subnum_section'] = $section->getSectionSubnumber();
  2602. $locomotiveModel = new app\models\LocomotiveModel();
  2603. $result = $locomotiveModel->getSectionInfo($params);
  2604. $json = json_decode($result);
  2605. if ($json != null && $json->diagnosticMap != null) {
  2606. $uuid = $json->diagnosticMap;
  2607. $section->uuid = $json->section_id;
  2608. $mynum = $json->section_num; //letter == last symbol
  2609. $letter = substr($mynum, -1);
  2610. if (intval($letter) <= 0)
  2611. $section->letter = $letter;
  2612. $existed = DiagnosticMap::Find($uuid);
  2613. if ($existed == null) {
  2614. $dm = new DiagnosticMap();
  2615. $dm->created = new DateTime("now");
  2616. $dm->uuid = $uuid;
  2617. $section->addDiagnosticMap($dm);
  2618. $section->diagnostic_map = $uuid;
  2619. }
  2620. }
  2621. if ($save)
  2622. $section->Save();
  2623. }
  2624. function CreateProject($projecttype, $loco_number, $loco_type, $А, $Б, $В, $Г)
  2625. {
  2626. global $link, $companyID;
  2627. CheckSection("А", $loco_type, $loco_number, $А);
  2628. CheckSection("Б", $loco_type, $loco_number, $Б);
  2629. CheckSection("В", $loco_type, $loco_number, $В);
  2630. CheckSection("Г", $loco_type, $loco_number, $Г);
  2631. $qstr = "insert into projects_locotech (action, company, status, loco_type,loco_number,depo,depo_service, created, urgent) values ($projecttype, $companyID,1,'$loco_type',$loco_number,'','', NOW(), 0)";
  2632. mysqli_query($link, $qstr);
  2633. $activeid = mysqli_insert_id($link);
  2634. if ($activeid) {
  2635. if (StartProject($projecttype, $activeid))
  2636. TasksAssign('', true, $activeid);
  2637. }
  2638. }
  2639. function TempStartProject($proj = null)
  2640. {
  2641. global $link, $companyID;
  2642. $projecttype = $proj->getAction();
  2643. // var_dump($projecttype);
  2644. if ($projecttype == 187 || $projecttype == 185 || $projecttype == 170 || $projecttype == 178) {
  2645. if ($proj->getStatus() == 5) {
  2646. $loco_number = $proj->loco_number;
  2647. $loco_type = $proj->getLocoType();
  2648. $qstr = "insert into projects_locotech (action, company, status, loco_type,loco_number,depo,depo_service, created, urgent) values (" . 214 . "," . 3 . ",1,'$loco_type','$loco_number','','', NOW(), 0)";
  2649. mysqli_query($link, $qstr);
  2650. $activeid = mysqli_insert_id($link);
  2651. // var_dump($activeid);
  2652. if ($activeid) {
  2653. $project = Project::Find($activeid);
  2654. if ($project != null) {
  2655. /**
  2656. * @var $project Project
  2657. */
  2658. if ($proj->section) {
  2659. $project->section = $proj->section;
  2660. $project->Save();
  2661. }
  2662. }
  2663. if (StartProject(214, $activeid))
  2664. TasksAssign('', true, $activeid);
  2665. }
  2666. //временный хардкод - ПРИЕМКА создает опись
  2667. }
  2668. }
  2669. }
  2670. // if (StartProject($action_num, $activeid))
  2671. // TasksAssign('', true, $assign_id);
  2672. function GrabReadyTasksForAccount($accid, $typeid)
  2673. {
  2674. global $link;
  2675. $query = mysqli_query($link, "select * from tasks where status = 5 and type = $typeid and assignees_arr=".$accid);
  2676. $taskarr = array();
  2677. while ($query && $res = mysqli_fetch_array($query))
  2678. {
  2679. array_push($taskarr, $res);
  2680. }
  2681. return $taskarr;
  2682. }
  2683. function GetAverageTime($taskarr)
  2684. {
  2685. $sum = 0;
  2686. foreach ($taskarr as $res)
  2687. {
  2688. $time = TimeSpentForTaskFromArray($res);
  2689. $sum += $time;
  2690. }
  2691. $sum /= sizeof($taskarr);
  2692. $sum = round($sum, 0, PHP_ROUND_HALF_UP);
  2693. if ($sum > 120)
  2694. $sum = '---';
  2695. return $sum;
  2696. }
  2697. function EfficiencyReport($accid)
  2698. {
  2699. global $link;
  2700. $query = mysqli_query($link, "select * from tasks where status = 5 and assignees_arr=".$accid);
  2701. $taskarr = array();
  2702. $retarr = array();
  2703. while ($query && $res = mysqli_fetch_array($query))
  2704. {
  2705. $timespent = TimeSpentForTaskFromArray($res);
  2706. $typeid = $res['type'];
  2707. if (sizeof($taskarr[$typeid]) == 0) {
  2708. $taskarr[$typeid] = array();
  2709. }
  2710. array_push($taskarr[$typeid], $timespent);
  2711. }
  2712. foreach ($taskarr as $type_id=>$timesspent)
  2713. {
  2714. $sum = 0;
  2715. foreach ($timesspent as $time) {
  2716. $sum += $time;
  2717. }
  2718. //echo "time $time";
  2719. $sum /= sizeof($time);
  2720. if ($sum > 120)
  2721. $sum = '---';
  2722. $retarr[$type_id] = $sum;
  2723. }
  2724. return $retarr;
  2725. }
  2726. /**
  2727. * @param string $action Acceptable values are `encrypt` or `decrypt`.
  2728. * @param string $string The string value to encrypt or decrypt.
  2729. * @return string
  2730. */
  2731. function encrypt_decrypt($action, $string)
  2732. {
  2733. $output = false;
  2734. $encrypt_method = "AES-256-CBC";
  2735. $secret_key = '202cb962ac59075b964b07152d234b70';
  2736. $secret_iv = '289dff07669d7a23de0ef88d2f7129e7';
  2737. // hash
  2738. $key = hash('sha256', $secret_key);
  2739. // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a
  2740. // warning
  2741. $iv = substr(hash('sha256', $secret_iv), 0, 16);
  2742. if ($action == 'encrypt') {
  2743. $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
  2744. $output = base64_encode($output);
  2745. } elseif ($action == 'decrypt') {
  2746. $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
  2747. }
  2748. return $output;
  2749. }