Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2020
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.51 KB | None | 0 0
  1. import {Component, OnInit, OnDestroy, ViewEncapsulation, NgZone} from '@angular/core';
  2. import {ActivatedRoute, Router} from "@angular/router";
  3. import {TaskService} from "../../services/task.service";
  4. import { DomSanitizer } from "@angular/platform-browser";
  5. import {ReferencesService} from "../../services/references.service";
  6. import {RouterService} from "../../services/router.service";
  7. import {HelperService} from "../../services/helper.service";
  8. import {FileService} from "../../services/file.service";
  9.  
  10. @Component({
  11. selector: 'app-blocks',
  12. templateUrl: './blocks.page.html',
  13. styleUrls: ['./blocks.page.scss'],
  14. encapsulation: ViewEncapsulation.None
  15. })
  16. export class BlocksPage implements OnInit, OnDestroy {
  17.  
  18. emptyField = '-';
  19.  
  20. inProcess = false;
  21.  
  22. currentGroup: any = {};
  23.  
  24. groupIcons;
  25.  
  26. informationString: any = {};
  27.  
  28. categoryIcons;
  29.  
  30. resultBlocks: any[] = [];
  31.  
  32. encodeSymbols = {
  33. '/': '#SLASH#'
  34. };
  35.  
  36. compSubscribtion;
  37.  
  38. noTasksMessage = 'Задания отсутствуют';
  39.  
  40. initialised = false;
  41.  
  42. countTaskPage = 2; //кол-во задач на одной странице
  43.  
  44. pages: any[] = [];
  45.  
  46. currentPage;
  47.  
  48. constructor(
  49. private route: ActivatedRoute,
  50. private routerService: RouterService,
  51. private router: Router,
  52. private taskService: TaskService,
  53. private sanitizer: DomSanitizer,
  54. private zone: NgZone,
  55. private helperService: HelperService,
  56. private fileService: FileService,
  57. private refService: ReferencesService,
  58. ) {
  59. }
  60.  
  61. ngOnInit() {
  62. this.compSubscribtion = this.taskService.thereIsChanges.subscribe((res) => {
  63. if (res) {
  64. this.updateStatuses();
  65. }
  66. });
  67. this.makeBlocks();
  68.  
  69. this.taskService.onTasksUpdates().subscribe((tasksUpdated:any) => {
  70. if (!this.inProcess) {
  71. this.makeBlocks();
  72. this.updateStatuses();
  73. }
  74. });
  75. }
  76.  
  77. ngOnDestroy() {
  78. this.compSubscribtion.unsubscribe();
  79. }
  80.  
  81. makeBlocks() {
  82. this.inProcess = true;
  83. this.getBlockCodes().then(() => this.getBlocks());
  84. }
  85.  
  86. updateStatuses() {
  87. let currentTasks = [];
  88. if (this.resultBlocks.length) {
  89. this.taskService.getTasks().then((tasks:any) => {
  90. if (tasks && tasks.length) {
  91. this.resultBlocks.forEach(block => {
  92. currentTasks = tasks.filter(storedTask => block.tasks.map(task => task.ID).includes(storedTask.ID));
  93. block.isNew = currentTasks.some(it => it.isNew);
  94. currentTasks.every(task => +task.UF_STATUS === this.taskService.statuses.COMPLETE_SUCCESS) ? block.status = 'success' : (currentTasks.some(task => [this.taskService.statuses.COMPLETE_INCORRECT,this.taskService.statuses.NOT_COMPLETE].includes(+task.UF_STATUS)) ? block.status = 'unsuccess' : block.status = 'wait');
  95. currentTasks.every(task => +task.UF_STATUS === this.taskService.statuses.COMPLETE_SUCCESS) ? block.statusSort = 3 : (currentTasks.some(task => [this.taskService.statuses.COMPLETE_INCORRECT,this.taskService.statuses.NOT_COMPLETE].includes(+task.UF_STATUS)) ? block.statusSort = 2 : block.statusSort = 1);
  96. });
  97. this.sortBlocks();
  98. }
  99.  
  100. this.zone.run(() => {});
  101. this.taskService.unsetUpdateEvent();
  102. });
  103. }
  104. }
  105.  
  106. getBlockCodes() {
  107. return new Promise(resolve => {
  108. this.refService.getRefs('categories').then((categories:any) => {
  109. this.categoryIcons = categories.map(category => {
  110. return {
  111. id: category.ID,
  112. name: category.UF_NAME,
  113. icon: category.UF_PICTOGRAM_CAT_SVG_XML
  114. }
  115. });
  116. }).then(() => {
  117. this.refService.getRefs('informationString').then((informationString:any)=>{
  118. if (informationString.length > 0)
  119. {
  120. this.informationString = informationString.map(informationStr => {
  121. return {
  122. id: informationStr.ID,
  123. color: informationStr.UF_COLOR,
  124. field: informationStr.UF_FIELD_NAME,
  125. text: informationStr.UF_TASK_LOG
  126. }
  127. });
  128.  
  129. }
  130.  
  131. })
  132. })
  133. .then(() => {
  134. return this.refService.getRefs('taskGroups')
  135. })
  136. .then((groups:any) => {
  137. this.currentGroup.id = this.route.snapshot.params['blockFirstCode'];
  138.  
  139. if (this.currentGroup.id === 'unsorted') {
  140. this.currentGroup.name = 'Прочее';
  141. }
  142. else {
  143. this.currentGroup.name = groups.find(group => group.ID === this.currentGroup.id).UF_NAME;
  144. this.currentGroup.infostring = groups.find(group => group.ID === this.currentGroup.id).UF_INFO_STRING;
  145. this.currentGroup.categoryId = groups.find(group => group.ID === this.currentGroup.id).UF_CATEGORY;
  146. this.currentGroup.categoryName = this.categoryIcons.find(cat => cat.id === this.currentGroup.categoryId).name;
  147. this.currentGroup.groupingCodeFirst = groups.find(group => group.ID === this.currentGroup.id).UF_GR_FIELD_CODE ;
  148. this.currentGroup.groupingCodeFirstValue = this.route.snapshot.params['blockSecondCode'] || false;
  149. if (this.currentGroup.groupingCodeFirstValue) {
  150. for (let key in this.encodeSymbols) {
  151. this.currentGroup.groupingCodeFirstValue = this.currentGroup.groupingCodeFirstValue.replace(this.encodeSymbols[key], key);
  152. }
  153. }
  154. this.currentGroup.groupingCodeFirstValue = this.currentGroup.groupingCodeFirstValue === this.emptyField ? '' : this.currentGroup.groupingCodeFirstValue;
  155. this.currentGroup.groupingCodeSecond = groups.find(group => group.ID === this.currentGroup.id).UF_GR_FIELD_CODE2 || false;
  156. this.currentGroup.isNextSecondLevel = (this.route.snapshot.params['blockSecondCode'] === undefined) && !!this.currentGroup.groupingCodeSecond;
  157. this.groupIcons = groups.map(group => {
  158. return {
  159. id: group.ID,
  160. categoryId: group.UF_CATEGORY,
  161. icon: group.UF_PICTOGRAM_GROUP_SVG_XML
  162. }
  163. });
  164. }
  165. resolve(this.currentGroup);
  166. })
  167. })
  168. }
  169. //проверка объекта на пустоту
  170. isEmpty(obj) {
  171. for (let key in obj) {
  172. // если тело цикла начнет выполняться - значит в объекте есть свойства
  173. return false;
  174. }
  175. return true;
  176. }
  177.  
  178. getBlocks(page = 0) {
  179. this.currentPage = page+1;
  180. let tasks;
  181. let tasksFullFilter;
  182. let blocks: any[] = [];
  183. let blockGroupsFull = {};
  184. let infostring_group = null;
  185. let infostring_values = [];
  186. this.taskService.getTasks().then((tasksFull:any) => {
  187. if (this.currentGroup.infostring !== null && this.informationString && !this.isEmpty(this.informationString))
  188. {
  189. infostring_group = this.informationString.filter(infostr => infostr.id == this.currentGroup.infostring);
  190. }
  191.  
  192. if (this.currentGroup.id === 'unsorted') {
  193. this.resultBlocks = tasksFull.filter(task => !task.GROUPS).map(task => {
  194. return {
  195. link: task.ID,
  196. groupsIcons: ['<svg xmlns="http://www.w3.org/2000/svg" width="21.294" height="5.691" viewBox="0 0 21.294 5.691">' +
  197. '<g transform="translate(-10.2 -35.5)">' +
  198. '<path d="M13.045,35.5A2.845,2.845,0,1,1,10.2,38.345,2.86,2.86,0,0,1,13.045,35.5" transform="translate(0)" fill="#168ec8"/>' +
  199. '<path d="M38.545,35.5A2.845,2.845,0,1,1,35.7,38.345,2.86,2.86,0,0,1,38.545,35.5" transform="translate(-17.698)" fill="#168ec8"/>' +
  200. '<path d="M64.045,35.5A2.845,2.845,0,1,1,61.2,38.345,2.86,2.86,0,0,1,64.045,35.5" transform="translate(-35.397)" fill="#168ec8"/></g></svg>'],
  201. categoryIcons: task.UF_CATEGORY ? this.categoryIcons.find(cat => cat.id === task.UF_CATEGORY).icon : '',
  202. count: 1,
  203. priority: task.UF_PRIORITY,
  204. status: +task.UF_STATUS === this.taskService.statuses.COMPLETE_SUCCESS ? 'success' : ([this.taskService.statuses.COMPLETE_INCORRECT,this.taskService.statuses.NOT_COMPLETE].includes(+task.UF_STATUS) ? 'unsuccess' : 'wait'),
  205. statusSort: +task.UF_STATUS === this.taskService.statuses.COMPLETE_SUCCESS ? 3 : ([this.taskService.statuses.COMPLETE_INCORRECT,this.taskService.statuses.NOT_COMPLETE].includes(+task.UF_STATUS) ? 2 : 1),
  206. title: 'Задача №' + task.ID,
  207. comment: (task.UF_COMMENT) ? task.UF_COMMENT : '',
  208. isNew: task.isNew,
  209. importantCount: +(task.UF_COMMENT !== '' || task.UF_TIME_START !== '' && task.UF_TIME_FINISH !== ''),
  210. finishDate: task.UF_DATE_FINISH,
  211. finishTime: task.UF_TIME_FINISH,
  212. tasks: [task]
  213. }
  214. });
  215.  
  216. } else {
  217. if (tasksFull && tasksFull.length) {
  218. /**
  219. * для второго уровня фильтруем по групе
  220. * но считаем без группы
  221. */
  222. if (this.currentGroup.groupingCodeFirstValue) { // 2 level
  223. tasks = tasksFull.filter(task => !!task && !!task.GROUPS && task.GROUPS.includes(this.currentGroup.id));
  224. if (this.currentGroup.groupingCodeFirstValue !== false) {
  225. tasks = tasks.filter(task => task[this.currentGroup.groupingCodeFirst] === this.currentGroup.groupingCodeFirstValue);
  226. }
  227. if (this.currentGroup.groupingCodeFirstValue !== false) {
  228. tasksFullFilter = tasksFull.filter(task => task[this.currentGroup.groupingCodeFirst] === this.currentGroup.groupingCodeFirstValue);
  229. }
  230.  
  231. } else { // 1 level
  232. tasks = tasksFull.filter(task => !!task && !!task.GROUPS && task.GROUPS.includes(this.currentGroup.id));
  233. if (this.currentGroup.groupingCodeFirstValue !== false) {
  234. tasks = tasks.filter(task => task[this.currentGroup.groupingCodeFirst] === this.currentGroup.groupingCodeFirstValue);
  235. }
  236. }
  237.  
  238.  
  239.  
  240. let blockGroups = {};
  241. if (!this.currentGroup.groupingCodeFirstValue) { // 1 level
  242. for (let alsoTask of tasks) {
  243. if (
  244. (this.currentGroup.groupingCodeFirst
  245. && alsoTask[this.currentGroup.groupingCodeFirst])
  246. || !alsoTask[this.currentGroup.groupingCodeFirst]
  247. ) {
  248. let val = alsoTask[this.currentGroup.groupingCodeFirst];
  249. if (blockGroups[val]) {
  250. blockGroups[val].push(alsoTask);
  251. } else {
  252. blockGroups[val] = [alsoTask];
  253. }
  254. }
  255. }
  256.  
  257. } else { // 2 level
  258. for (let alsoTask of tasks) {
  259. if (
  260. (this.currentGroup.groupingCodeFirst
  261. && alsoTask[this.currentGroup.groupingCodeFirst])
  262. || !alsoTask[this.currentGroup.groupingCodeFirst]
  263. && (this.currentGroup.groupingCodeSecond
  264. && alsoTask[this.currentGroup.groupingCodeSecond])
  265. || !alsoTask[this.currentGroup.groupingCodeSecond]
  266. ) {
  267. let val1 = alsoTask[this.currentGroup.groupingCodeFirst];
  268. let val2 = alsoTask[this.currentGroup.groupingCodeSecond];
  269. if (blockGroups[val1+val2]) {
  270. blockGroups[val1+val2].push(alsoTask);
  271. } else {
  272. blockGroups[val1+val2] = [alsoTask];
  273. }
  274. }
  275. }
  276.  
  277.  
  278. /**
  279. * чтобы посчитать количество задач всего в деталке, т.к. они группируются без учета групп
  280. */
  281. for (let alsoTask of tasksFullFilter) {
  282. if (
  283. (this.currentGroup.groupingCodeFirst
  284. && alsoTask[this.currentGroup.groupingCodeFirst])
  285. || !alsoTask[this.currentGroup.groupingCodeFirst]
  286. && (this.currentGroup.groupingCodeSecond
  287. && alsoTask[this.currentGroup.groupingCodeSecond])
  288. || !alsoTask[this.currentGroup.groupingCodeSecond]
  289. ) {
  290. let val1 = alsoTask[this.currentGroup.groupingCodeFirst];
  291. let val2 = alsoTask[this.currentGroup.groupingCodeSecond];
  292. if (blockGroupsFull[val1+val2]) {
  293. blockGroupsFull[val1+val2].push(alsoTask);
  294. } else {
  295. blockGroupsFull[val1+val2] = [alsoTask];
  296. }
  297. }
  298. }
  299. }
  300.  
  301. for (let code in blockGroups) {
  302. if (blockGroups.hasOwnProperty(code)) {
  303. blocks.push(blockGroups[code]);
  304. }
  305. }
  306. }
  307.  
  308.  
  309. this.resultBlocks = blocks.map(block => {
  310.  
  311. let taskGroupsIcons = [],
  312. status = 'wait',
  313. statusSort = 1;
  314. if (block.filter(task => +task.UF_STATUS === this.taskService.statuses.COMPLETE_SUCCESS).length === block.length) {
  315. status = 'success';
  316. statusSort = 3;
  317. }
  318. if (block.map(task => task.UF_STATUS).some(status => [this.taskService.statuses.COMPLETE_INCORRECT,this.taskService.statuses.NOT_COMPLETE].includes(+status))) {
  319. status = 'unsuccess';
  320. statusSort = 2;
  321. }
  322. let commentsList = [];
  323. block.forEach(task => {
  324. /* собираем значения инфостроки для второго уровня если она не пустая (значения поля задачи указанного в инфостроке) */
  325. if (infostring_group !== null && !!this.currentGroup.groupingCodeFirstValue){
  326. if (task.hasOwnProperty(infostring_group[0].field) && task[infostring_group[0].field].length > 0 &&infostring_values.indexOf(task[infostring_group[0].field]) < 0){
  327. infostring_values.push(task[infostring_group[0].field]);
  328. }
  329. }
  330. taskGroupsIcons = Array.from(new Set(taskGroupsIcons.concat(task.GROUPS)));
  331. if (!commentsList.includes(task.UF_COMMENT)) {
  332. commentsList.push(task.UF_COMMENT);
  333. }
  334. });
  335.  
  336. if (infostring_group !== null)
  337. {
  338. infostring_group[0]["infostring_value"] = "";
  339. if(infostring_values.length > 0){
  340. infostring_group[0]["infostring_value"] = infostring_values;
  341. }
  342.  
  343. }
  344. let codeFirst:string = block[0][this.currentGroup.groupingCodeFirst];
  345. if (codeFirst) {
  346. for (let key in this.encodeSymbols) {
  347. codeFirst = codeFirst.replace(key, this.encodeSymbols[key]);
  348. }
  349. }
  350. let link = this.currentGroup.isNextSecondLevel ? (codeFirst === '' ? this.emptyField : codeFirst) + '/second-level' : block.map(task => task.ID).join('-');
  351.  
  352.  
  353. /**
  354. * Заголовок: адрес или номер квартиры
  355. */
  356. let title = '';
  357. /**
  358. * если второй уровень
  359. */
  360. if (!!this.currentGroup.groupingCodeFirstValue) {
  361. /**
  362. * если нет значения, ставим пробел
  363. */
  364. if (block[0][this.currentGroup.groupingCodeSecond] === '') {
  365. title = this.emptyField;
  366. } else {
  367. /**
  368. * если это номер квартира, обрезаем ведущие нули
  369. */
  370. if (this.currentGroup.groupingCodeSecond == 'UF_APARTMENT_NUMBER') {
  371. title = block[0][this.currentGroup.groupingCodeSecond].replace(/^0+/, '');
  372. } else {
  373. title = block[0][this.currentGroup.groupingCodeSecond];
  374. }
  375. }
  376.  
  377. /**
  378. * если первый уровень
  379. */
  380. } else {
  381.  
  382. /**
  383. * если нет значения, ставим пробел
  384. */
  385. if (block[0][this.currentGroup.groupingCodeFirst] === '') {
  386. title = this.emptyField;
  387. } else {
  388. /**
  389. * если это номер квартира, обрезаем ведущие нули
  390. */
  391. if (this.currentGroup.groupingCodeFirst == 'UF_APARTMENT_NUMBER') {
  392. title = block[0][this.currentGroup.groupingCodeFirst].replace(/^0+/, '');
  393. } else {
  394. title = block[0][this.currentGroup.groupingCodeFirst];
  395. }
  396. }
  397. }
  398.  
  399. /**
  400. * считаем всего количество задач
  401. */
  402. let count = block.length;
  403. let importantCount = block.filter(task => (task.UF_COMMENT !== '' || !!task.UF_TIME_FINISH && task.UF_TIME_FINISH !== '')).length;
  404. let val1Group = block[0][this.currentGroup.groupingCodeFirst];
  405. let val2Group = block[0][this.currentGroup.groupingCodeSecond];
  406.  
  407. if (blockGroupsFull) {
  408. for (let code in blockGroupsFull) {
  409. if (!blockGroupsFull.hasOwnProperty(code)) {
  410. continue;
  411. }
  412.  
  413. if (code == val1Group+val2Group) {
  414. let tasksFullByCode = blockGroupsFull[code];
  415. if (tasksFullByCode && typeof tasksFullByCode === 'object' && tasksFullByCode.length) {
  416. count = tasksFullByCode.length;
  417. importantCount = tasksFullByCode.filter(task => (task.UF_COMMENT !== '' || !!task.UF_TIME_FINISH && task.UF_TIME_FINISH !== '')).length;
  418. break;
  419. }
  420. }
  421. }
  422. }
  423.  
  424. return {
  425. link: link,
  426. groupsIcons: taskGroupsIcons.map(id => {
  427. return this.groupIcons.find(group => group.id === id).icon;
  428. }),
  429. categoryIcon: this.categoryIcons.find(cat => cat.id === this.currentGroup.categoryId).icon,
  430. count: count,
  431. priority: Math.min.apply(null, block.map(task => task.UF_PRIORITY)),
  432. status,
  433. statusSort,
  434. title: title,
  435. comment: commentsList.join('; '),
  436. isNew: block.some(item => item.isNew),
  437. importantCount: importantCount,
  438. finishDate: Math.min.apply(null, block.filter(task => !!task.UF_DATE_FINISH).map(task => +(task.UF_DATE_FINISH).split('-').join(''))),
  439. finishTime: Math.min.apply(null, block.filter(task => !!task.UF_TIME_FINISH).map(task => +task.UF_TIME_FINISH)),
  440. infostring: infostring_group !== null ? infostring_group[0] : null,
  441. tasks: block
  442. }
  443. });
  444. }
  445.  
  446. this.sortBlocks();
  447.  
  448. this.setPagination(page);
  449.  
  450. console.log("result blocks");
  451. console.log(this.resultBlocks);
  452.  
  453. this.inProcess = false;
  454. })
  455. }
  456. sortBlocks() {
  457. this.resultBlocks.sort( (a,b) => {
  458. return (parseInt(a.title) - parseInt(b.title)) // 6 по названию (квартира)
  459. });
  460. this.initialised = true;
  461. return;
  462. this.resultBlocks.sort( (a,b) => {
  463. return (a.statusSort - b.statusSort) // 1 по статусу
  464. || (a.finishDate - b.finishDate) // 2 по дате завершения
  465. || (b.importantCount - a.importantCount) // 3 с не пустыми комментариями
  466. || (a.finishTime - b.finishTime) // 4 по времени завершения
  467. || (a.priority - b.priority) // 5 по приоритету
  468. || (a.title - b.title) // 6 по названию (квартира)
  469. });
  470.  
  471. }
  472.  
  473. /**
  474. * @param page
  475. */
  476. setPagination(page) {
  477. this.pages = [];
  478. if (!!this.currentGroup.groupingCodeFirstValue && this.resultBlocks.length > this.countTaskPage){
  479. this.pages.push('Все');
  480. for (let i = 0;i< Math.ceil(this.resultBlocks.length/this.countTaskPage);i++){
  481. this.pages.push(i+1);
  482. }
  483.  
  484. if (page != -1){
  485. this.resultBlocks = this.resultBlocks.filter((elem,index)=>{
  486. if (index >= page*this.countTaskPage && index < page*this.countTaskPage + this.countTaskPage){
  487. return elem;
  488. }
  489. });
  490. }
  491. }
  492. }
  493. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement