gdel.component.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. import { HttpErrorResponse } from '@angular/common/http';
  2. import {
  3. Component,
  4. ViewChild,
  5. OnInit,
  6. AfterViewInit,
  7. ElementRef,
  8. Inject,
  9. } from '@angular/core';
  10. import { MatDialog } from '@angular/material/dialog';
  11. import { MatPaginator } from '@angular/material/paginator';
  12. import { MatSort } from '@angular/material/sort';
  13. import { MatTableDataSource } from '@angular/material/table';
  14. import { Router } from '@angular/router';
  15. import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
  16. import { AlertData } from 'src/app/interfaces/alert.interface';
  17. import { EncService } from 'src/app/services/enc/enc.service';
  18. import { ResourcesService } from 'src/app/services/resources/resources.service';
  19. import { lastValueFrom } from 'rxjs';
  20. import WebViewer from '@pdftron/webviewer';
  21. import { WebviewerComponent } from './webviewer/webviewer.component';
  22. import { DocumentManagementService } from 'src/app/services/document-management/document-management.service';
  23. import { MatSnackBar } from '@angular/material/snack-bar';
  24. import { GdelService } from 'src/app/services/document-management/gdel.service';
  25. import { docClassification, modules, supportedFiles } from 'src/environments/environment.prod';
  26. import { DateRangePickerComponent } from './date-range-picker/date-range-picker.component';
  27. import { FormControl } from '@angular/forms';
  28. import { FindedFile, FindedFilesResponse } from 'src/app/interfaces/finded-files.interface';
  29. import { UploadDialogComponent } from './upload-dialog/upload-dialog.component';
  30. import { DOCUMENT } from '@angular/common';
  31. import { ShareFileComponent } from './share-file/share-file.component';
  32. import { AccessDialogComponent } from './access-dialog/access-dialog.component';
  33. import { OrderAssociatonComponent } from './order-associaton/order-associaton.component';
  34. interface FoundedFiles{
  35. CODIGO: string;
  36. VERSION: string;
  37. NOMBRE: string;
  38. TAMANIO: string;
  39. USRREG: string;
  40. ACCESO: UsersAccess[];
  41. }
  42. export interface UsersAccess{
  43. userLabel: string;
  44. userName: string;
  45. userColor: string;
  46. isTrigger: boolean;
  47. }
  48. @Component({
  49. selector: 'app-gdel',
  50. templateUrl: './gdel.component.html',
  51. styleUrls: ['./gdel.component.css'],
  52. })
  53. export class GDELComponent implements OnInit {
  54. public btnSmall: boolean;
  55. isLoading: boolean;
  56. hasError: boolean;
  57. errorStr: string;
  58. category: string;
  59. modulesArr = modules;
  60. clasificationsArr = docClassification;
  61. supportedFilesArr = supportedFiles;
  62. startDate: Date | null;
  63. endDate: Date | null;
  64. @ViewChild('dateRange') dateRange?: ElementRef;
  65. @ViewChild(MatPaginator) paginator!: MatPaginator;
  66. @ViewChild(MatSort) sort!: MatSort;
  67. moduleControl: FormControl;
  68. clasificationControl: FormControl;
  69. fileNameControl: FormControl;
  70. fileTypeControl: FormControl;
  71. datesRangeControl: FormControl;
  72. files: FindedFile[];
  73. dataSource: MatTableDataSource<FoundedFiles>;
  74. displayedColumns = ['CODIGO', 'VERSION', 'NOMBRE', 'TAMANIO', 'USRREG', 'ACCESO', 'ACCIONES'];
  75. avatarColors = {
  76. A: 244, B: 67, C: 54, D: 233, E: 30, F: 99, G: 156, H: 39, I: 176,
  77. J: 103, K: 58, L: 58, M: 183, N: 63, Ñ: 81, O: 181, P: 33, Q: 150,
  78. R: 243, S: 3, T: 169, U: 244, V: 76, W: 175, X: 80, Y: 255, Z: 193
  79. };
  80. /*@ViewChild('viewer') viewRef: any;
  81. public displayedColumns: Array<string>;
  82. public dataSource: MatTableDataSource<any>;
  83. @ViewChild('download') a?: ElementRef;
  84. public isLoading: boolean;
  85. public isLoadingForm: boolean;
  86. public active: number = 0;
  87. public ulOptSmall: boolean;
  88. public txtBuscador: string;
  89. public clickedIndex: any = 0;
  90. public downloadLink: String;
  91. public options = [
  92. {
  93. id: 1,
  94. items: 'Mis documentos',
  95. icon: 'local_library',
  96. },
  97. {
  98. id: 2,
  99. items: 'Compartidos conmigo',
  100. icon: 'group_add',
  101. },
  102. {
  103. id: 3,
  104. items: 'Papelera',
  105. icon: 'delete',
  106. },
  107. ];
  108. public documents: Array<any> = [];*/
  109. constructor(
  110. @Inject(DOCUMENT) private _document: Document,
  111. private _encService: EncService,
  112. private _resourcesServices: ResourcesService,
  113. private _dialog: MatDialog,
  114. private _router: Router,
  115. private _gdelService: GdelService,
  116. private _snackBar: MatSnackBar,
  117. ) {
  118. this.btnSmall = false;
  119. this.isLoading = true;
  120. this.hasError = true;
  121. this.errorStr = '';
  122. this.category = 'my-files';
  123. this.startDate = null;
  124. this.endDate = null;
  125. this.moduleControl = new FormControl('');
  126. this.clasificationControl = new FormControl('');
  127. this.fileNameControl = new FormControl('');
  128. this.fileTypeControl = new FormControl('');
  129. this.datesRangeControl = new FormControl('');
  130. this.dataSource = new MatTableDataSource();
  131. this.files = [];
  132. /*this.displayedColumns = [
  133. 'ID',
  134. 'NAME',
  135. 'EXT',
  136. 'SIZE',
  137. 'VERSION',
  138. 'FRMOD',
  139. 'USMOD',
  140. 'ACTIONS',
  141. ];
  142. this.dataSource = new MatTableDataSource();
  143. this.isLoading = false;
  144. this.isLoadingForm = false;
  145. this.ulOptSmall = false;
  146. this.txtBuscador = '';
  147. this.downloadLink = '';*/
  148. }
  149. ngOnInit(): void {
  150. this.moduleControl.valueChanges.subscribe(mod => {
  151. let cla = this.clasificationControl.value;
  152. let sda = this.startDate;
  153. let eda = this.endDate;
  154. let dna = this.fileNameControl.value;
  155. let ext = this.fileTypeControl.value;
  156. this.getFiles(mod, cla, sda, eda, dna, ext);
  157. });
  158. this.clasificationControl.valueChanges.subscribe(cla => {
  159. let mod = this.moduleControl.value;
  160. let sda = this.startDate;
  161. let eda = this.endDate;
  162. let dna = this.fileNameControl.value;
  163. let ext = this.fileTypeControl.value;
  164. this.getFiles(mod, cla, sda, eda, dna, ext);
  165. });
  166. this.fileNameControl.valueChanges.subscribe(dna => {
  167. let mod = this.moduleControl.value;
  168. let cla = this.clasificationControl.value;
  169. let sda = this.startDate;
  170. let eda = this.endDate;
  171. let ext = this.fileTypeControl.value;
  172. this.getFiles(mod, cla, sda, eda, dna, ext);
  173. });
  174. this.fileTypeControl.valueChanges.subscribe(ext => {
  175. let mod = this.moduleControl.value;
  176. let cla = this.clasificationControl.value;
  177. let sda = this.startDate;
  178. let eda = this.endDate;
  179. let dna = this.fileNameControl.value;
  180. this.getFiles(mod, cla, sda, eda, dna, ext);
  181. });
  182. this.getFiles(
  183. this.moduleControl.value,
  184. this.clasificationControl.value,
  185. this.startDate,
  186. this.endDate,
  187. this.fileNameControl.value,
  188. this.fileTypeControl.value
  189. );
  190. /*this.onResize();
  191. this.dataSource.data = [
  192. {
  193. ID: '01-ADSI-CA-230120-000001=01',
  194. NAME: 'Test',
  195. EXT: '.doc',
  196. SIZE: '20MB',
  197. VERSION: '1',
  198. FRMOD: '22/02/13',
  199. USMOD: 'CAVA07',
  200. },
  201. {
  202. ID: '01-ADSI-CA-230100-000002=02',
  203. NAME: 'Test2',
  204. EXT: '.pdf',
  205. SIZE: '10MB',
  206. VERSION: '2',
  207. FRMOD: '22/02/12',
  208. USMOD: 'CAVA07',
  209. },
  210. ];
  211. this.getDocuments();*/
  212. }
  213. public onResize(): void {
  214. this.btnSmall = window.innerWidth <= 1573;
  215. }
  216. updateCategory(category: string){
  217. let mod = this.moduleControl.value;
  218. let cla = this.clasificationControl.value;
  219. let sda = this.startDate;
  220. let eda = this.endDate;
  221. let dna = this.fileNameControl.value;
  222. let ext = this.fileTypeControl.value;
  223. this.getFiles(mod, cla, sda, eda, dna, ext);
  224. this.category = category;
  225. }
  226. openDateRangePicker(){
  227. let dialogRef = this._dialog.open(DateRangePickerComponent, {
  228. disableClose: true,
  229. width: '480px',
  230. data: {
  231. startDate: this.startDate,
  232. endDate: this.endDate
  233. }
  234. });
  235. dialogRef.afterClosed().subscribe(res => {
  236. if(res != null && res != undefined && res != ''){
  237. let resObj = JSON.parse(res);
  238. let dateRange = "";
  239. if(resObj.startDate != null || resObj.endDate != null){
  240. if(resObj.startDate != null){
  241. let startDateTimeArr = resObj.startDate.split('T');
  242. let startDateArr = startDateTimeArr[0].split('-').reverse();
  243. let startDateStr = startDateArr.join('/');
  244. this.startDate = new Date(resObj.startDate);
  245. dateRange += `desde ${startDateStr}, `;
  246. }
  247. if(resObj.endDate != null){
  248. let endDateTimeArr = resObj.endDate.split('T');
  249. let endDateArr = endDateTimeArr[0].split('-').reverse();
  250. let endDateStr = endDateArr.join('/');
  251. this.endDate = new Date(resObj.endDate);
  252. dateRange += `hasta ${endDateStr}, `;
  253. }
  254. let fl = dateRange[0].toUpperCase();
  255. let dateRangeArr = dateRange.split("");
  256. dateRangeArr[0] = fl;
  257. dateRange = dateRangeArr.join("");
  258. dateRange = dateRange.substring(0, dateRange.length - 2);
  259. this.dateRange!.nativeElement.value = dateRange;
  260. this.getFiles(
  261. this.moduleControl.value,
  262. this.clasificationControl.value,
  263. this.startDate,
  264. this.endDate,
  265. this.fileNameControl.value,
  266. this.fileTypeControl.value,
  267. );
  268. }
  269. }
  270. });
  271. }
  272. async getFiles(module: string | undefined, clas: string | undefined, startDate: Date | null, endDate: Date | null, name: string | undefined, type: string | undefined){
  273. try{
  274. this.isLoading = true;
  275. this.hasError = false;
  276. this.errorStr = "";
  277. let mod = module == undefined || module == '' ? '-' : module;
  278. let cla = clas == undefined || clas == '' ? '-' : clas;
  279. let sda = startDate == null ? '-' : this.formatSearchDate(startDate);
  280. let eda = endDate == null ? '-' : this.formatSearchDate(endDate);
  281. let dna = name == undefined || name == '' ? '-' : name;
  282. let ext = type == undefined || type == '' ? '-' : JSON.stringify(type.split(','));
  283. let idUser = localStorage.getItem('idusuario');
  284. let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
  285. let files: FindedFilesResponse = await lastValueFrom(this._gdelService.getFiles(
  286. mod, cla, sda, eda, dna, ext, this.category, shortEnc.response.encrypted, 1
  287. ));
  288. this.hasError = files.error;
  289. this.errorStr = files.msg;
  290. if(!this.hasError){
  291. this.files = files.response;
  292. let filesFound: FoundedFiles[] = [];
  293. files.response.forEach(file => {
  294. let fileSize = this.formatBytes(file.TAMANIO);
  295. let fileAccess = this.getUsersAccess(file.ACCESO);
  296. let fileObj: FoundedFiles = {
  297. CODIGO: file.CODIGO,
  298. VERSION: file.VERSION,
  299. NOMBRE: file.NOMBRE,
  300. TAMANIO: fileSize,
  301. USRREG: file.USRREG,
  302. ACCESO: fileAccess,
  303. };
  304. filesFound.push(fileObj);
  305. });
  306. this.dataSource = new MatTableDataSource(filesFound);
  307. this.dataSource.paginator = this.paginator;
  308. this.dataSource.sort = this.sort;
  309. }
  310. this.isLoading = false;
  311. }catch(error: any){
  312. if(error.error == undefined){
  313. this.errorStr = 'Ocurrió un error inesperado.';
  314. }else if(error.error.msg == undefined){
  315. this.errorStr = 'Ocurrió un error inesperado.';
  316. }else{
  317. this.errorStr = error.error.msg;
  318. }
  319. this.hasError = true;
  320. this.isLoading = false;
  321. }
  322. }
  323. formatSearchDate(date: Date): string{
  324. let day = date.getDate() < 10 ? `0${date.getDate()}` : `${date.getDate()}`;
  325. let month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : `${date.getMonth() + 1}`;
  326. let fullYear = `${date.getFullYear()}`;
  327. let year = fullYear.substring(2);
  328. return `${year}${month}${day}`;
  329. }
  330. openSnackBar(msg: string){
  331. this._snackBar.open(msg, undefined, {
  332. duration: 2500,
  333. });
  334. }
  335. formatBytes(bytes: number, decimals = 2) {
  336. if (bytes === 0) return '0 Bytes';
  337. const k = 1024;
  338. const dm = decimals < 0 ? 0 : decimals;
  339. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  340. const i = Math.floor(Math.log(bytes) / Math.log(k));
  341. return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  342. }
  343. getUsersAccess(accessStr: string): UsersAccess[]{
  344. let accessArr = JSON.parse(accessStr);
  345. let arrFn: UsersAccess[] = [];
  346. for(const user of accessArr){
  347. let userNameArr = user.split(' ');
  348. let userLabel = '';
  349. for(let i = 0; i < 2; i++){
  350. userLabel += userNameArr[i][0];
  351. }
  352. let userColor = "rgb(";
  353. for(let i = 0; i < 3; i++){
  354. let char: never = user.charAt(i) as never;
  355. let code = this.avatarColors[char];
  356. userColor += `${code}, `;
  357. }
  358. userColor = userColor.substring(0, userColor.length - 2);
  359. userColor += ")";
  360. let userObj: UsersAccess = {
  361. userLabel: userLabel,
  362. userName: user,
  363. userColor: userColor,
  364. isTrigger: false,
  365. }
  366. arrFn.push(userObj);
  367. }
  368. let arrFnAux: UsersAccess[] = [];
  369. if(arrFn.length > 4){
  370. for(let i = 0; i < 3; i++){
  371. arrFnAux.push(arrFn[i]);
  372. }
  373. let moreUsers: UsersAccess = {
  374. userLabel: `${arrFn.length - 3}+`,
  375. userName: `Ver ${arrFn.length - 3} más...`,
  376. userColor: 'rgba(0,0,0,0.54)',
  377. isTrigger: true,
  378. };
  379. arrFnAux.push(moreUsers);
  380. return arrFnAux;
  381. }
  382. return arrFn;
  383. }
  384. clearDatesRange(){
  385. this.startDate = null;
  386. this.endDate = null;
  387. this.datesRangeControl.setValue('');
  388. this.getFiles(
  389. this.moduleControl.value,
  390. this.clasificationControl.value,
  391. this.startDate,
  392. this.endDate,
  393. this.fileNameControl.value,
  394. this.fileTypeControl.value
  395. );
  396. }
  397. openUploadDialog(){
  398. let dialogRef = this._dialog.open(UploadDialogComponent, {
  399. width: '480px',
  400. disableClose: true,
  401. });
  402. dialogRef.afterClosed().subscribe(res => {
  403. if(res == true){
  404. let mod = this.moduleControl.value;
  405. let cla = this.clasificationControl.value;
  406. let sda = this.startDate;
  407. let eda = this.endDate;
  408. let dna = this.fileNameControl.value;
  409. let ext = this.fileTypeControl.value;
  410. this.getFiles(mod, cla, sda, eda, dna, ext);
  411. }
  412. });
  413. }
  414. async downloadFile(code: string, version: string, name: string){
  415. try{
  416. let idFile = `${code}=${version}=${name}`;
  417. this.openSnackBar(`Iniciando la descarga del archivo ${idFile}...`);
  418. let idFileEnc = await this._encService.encrypt(idFile);
  419. let idFileShort = await lastValueFrom(this._encService.shortEncrypt(idFileEnc));
  420. let download = this._document.getElementById(`download`) as HTMLAnchorElement;
  421. let idUser = localStorage.getItem('idusuario');
  422. let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
  423. let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(
  424. idFileShort.response.encrypted,
  425. shortEnc.response.encrypted,
  426. 1
  427. ));
  428. download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/1`;
  429. download.download = idFile;
  430. download.click();
  431. }catch(error: any){
  432. if(error.error == undefined){
  433. this.openSnackBar('Ocurrió un error inesperado.');
  434. }else if(error.error.msg == undefined){
  435. this.openSnackBar('Ocurrió un error inesperado.');
  436. }else{
  437. this.openSnackBar(error.error.msg);
  438. }
  439. }
  440. }
  441. async openViewer(code: string, version: string, name: string) {
  442. try{
  443. let idFile = `${code}=${version}=${name}`;
  444. this.openSnackBar(`Abriendo el archivo ${idFile}...`);
  445. let idFileEnc = await this._encService.encrypt(idFile);
  446. let idFileShort = await lastValueFrom(this._encService.shortEncrypt(idFileEnc));
  447. let idUser = localStorage.getItem('idusuario');
  448. let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idUser!));
  449. let publicURL = await lastValueFrom(this._gdelService.getPublicDocumentUrl(
  450. idFileShort.response.encrypted,
  451. shortEnc.response.encrypted,
  452. 1
  453. ));
  454. let fileData = {
  455. url: publicURL.response.public_uri,
  456. };
  457. this._dialog.open(WebviewerComponent, {
  458. data: fileData,
  459. width: '100%',
  460. });
  461. }catch(error: any){
  462. if(error.error == undefined){
  463. this.openSnackBar('Ocurrió un error inesperado.');
  464. }else if(error.error.msg == undefined){
  465. this.openSnackBar('Ocurrió un error inesperado.');
  466. }else{
  467. this.openSnackBar(error.error.msg);
  468. }
  469. }
  470. }
  471. openShareDialog(code: string, version: string, name: string){
  472. let idFile = `${code}=${version}=${name}`;
  473. let dialogRef = this._dialog.open(ShareFileComponent, {
  474. width: '720px',
  475. disableClose: true,
  476. data: {
  477. idFile: idFile,
  478. }
  479. })
  480. dialogRef.afterClosed().subscribe((res) => {
  481. this.updateFilePermissions(idFile, res);
  482. })
  483. }
  484. async updateFilePermissions(idFile: string, permissions: string){
  485. try{
  486. this.openSnackBar(`Actualizando permisos del archivo ${idFile}`);
  487. this.isLoading = true;
  488. this.hasError = false;
  489. this.errorStr = '';
  490. let idFileEnc = await this._encService.encrypt(idFile);
  491. let idUser = localStorage.getItem('idusuario');
  492. let formData = new FormData();
  493. formData.append('id_user', idUser!);
  494. formData.append('id_file', idFileEnc);
  495. formData.append('linea', '1');
  496. formData.append('permissions', permissions);
  497. await lastValueFrom(this._gdelService.updateFilePermissions(formData));
  498. this.openSnackBar(`Los permisos se actualizaron correctamente`);
  499. let mod = this.moduleControl.value;
  500. let cla = this.clasificationControl.value;
  501. let sda = this.startDate;
  502. let eda = this.endDate;
  503. let dna = this.fileNameControl.value;
  504. let ext = this.fileTypeControl.value;
  505. this.getFiles(mod, cla, sda, eda, dna, ext);
  506. }catch(error: any){
  507. if(error.error == undefined){
  508. this.errorStr = 'Ocurrió un error inesperado.';
  509. }else if(error.error.msg == undefined){
  510. this.errorStr = 'Ocurrió un error inesperado.';
  511. }else{
  512. this.errorStr = error.error.msg;
  513. }
  514. this.hasError = true;
  515. this.isLoading = false;
  516. }
  517. }
  518. openAccessDialog(code: string, version: string, name: string, isTrigger: boolean, isDeleted: boolean){
  519. if(isTrigger){
  520. let file = this.files.filter(item => item.CODIGO == code && item.VERSION == version && item.NOMBRE == name)[0];
  521. let accessStr = file.ACCESO;
  522. let idFile = `${code}=${version}=${name}`;
  523. let dialogRef = this._dialog.open(AccessDialogComponent, {
  524. width: '720px',
  525. data: {
  526. idFile: idFile,
  527. accessStr: accessStr,
  528. isDeleted: isDeleted
  529. }
  530. });
  531. dialogRef.afterClosed().subscribe(res => {
  532. if(res == true){
  533. this.openShareDialog(code, version, name);
  534. }
  535. })
  536. }
  537. }
  538. confirmDelete(code: string, version: string, name: string){
  539. let idFile = `${code}=${version}=${name}`;
  540. let dialogRef = this._dialog.open(AlertComponent, {
  541. disableClose: true,
  542. width: '480px',
  543. data: {
  544. title: 'Confirmar acción',
  545. icon: 'warning',
  546. description: `¿Está seguro de querer eliminar el archivo ${idFile}?`,
  547. description2: 'Esta acción no se puede deshacer'
  548. }
  549. });
  550. dialogRef.afterClosed().subscribe(res => {
  551. if(res == true){
  552. this.deleteFile(idFile);
  553. }
  554. });
  555. }
  556. async deleteFile(idFile: string){
  557. try{
  558. let idUser = localStorage.getItem('idusuario');
  559. let idFileEnc = await this._encService.encrypt(idFile);
  560. let formData = new FormData();
  561. formData.append('id_user', idUser!);
  562. formData.append('id_file', idFileEnc);
  563. formData.append('linea', '1');
  564. await lastValueFrom(this._gdelService.deleteFile(formData));
  565. this.openSnackBar('El archivo se eliminó correctamente.');
  566. let mod = this.moduleControl.value;
  567. let cla = this.clasificationControl.value;
  568. let sda = this.startDate;
  569. let eda = this.endDate;
  570. let dna = this.fileNameControl.value;
  571. let ext = this.fileTypeControl.value;
  572. this.getFiles(mod, cla, sda, eda, dna, ext);
  573. }catch(error: any){
  574. if(error.error == undefined){
  575. this.openSnackBar('Ocurrió un error inesperado.');
  576. }else if(error.error.msg == undefined){
  577. this.openSnackBar('Ocurrió un error inesperado.');
  578. }else{
  579. this.openSnackBar(error.error.msg);
  580. }
  581. }
  582. }
  583. openAssociationDialog(code: string, version: string, name: string){
  584. let idFile = `${code}=${version}=${name}`;
  585. this._dialog.open(OrderAssociatonComponent, {
  586. width: '840px',
  587. disableClose: true,
  588. data: {
  589. idFile: idFile,
  590. }
  591. });
  592. }
  593. /*ngAfterViewInit(): void {
  594. this.dataSource.paginator = this.paginator;
  595. this.dataSource.sort = this.sort;
  596. }
  597. registerDocument() {
  598. this._router.navigate(['sam/GDEL/ADDO/nuevo']);
  599. }
  600. public async getShareDocuments() {
  601. this.dataSource.data = [];
  602. }
  603. public async getDocuments() {
  604. this.isLoading = true;
  605. let idEnc = localStorage.getItem('idusuario')!;
  606. let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc));
  607. let documents: any = await lastValueFrom(
  608. this._gdelService.getDocumentsByUser(shortEnc.response.encrypted, 1)
  609. );
  610. if (documents.error) {
  611. this.openSnackBar(documents.msg);
  612. } else {
  613. for (let index = 0; index < documents.response.length; index++) {
  614. let codeSAM =
  615. documents.response[index].NUMERO_LINEA +
  616. '-' +
  617. documents.response[index].MODULO +
  618. '-' +
  619. documents.response[index].CLASIFICACION +
  620. '-' +
  621. documents.response[index].FECHA_REGISTRO +
  622. '-' +
  623. documents.response[index].SECUENCIAL +
  624. '=' +
  625. documents.response[index].VERSION +
  626. '=' +
  627. documents.response[index].NOMBRE_ARC +
  628. '.' +
  629. documents.response[index].EXTENSION;
  630. let encript = await this._encService.encrypt(codeSAM);
  631. let short = await lastValueFrom(this._encService.shortEncrypt(encript));
  632. documents.response[index].ID = short.response.encrypted;
  633. documents.response[index].TAMANIO = this.formatBytes(
  634. documents.response[index].TAMANIO
  635. );
  636. }
  637. this.dataSource.data = documents.response;
  638. this.isLoading = false;
  639. }
  640. }
  641. async modifyDocument(idDocument: number) {
  642. let idDocEnc = await this._encService.encrypt(`${idDocument}`);
  643. this._router.navigate(['sam/GDEL/ADDO/editar'], {
  644. queryParams: {
  645. idDoc: idDocEnc,
  646. },
  647. });
  648. }
  649. // Método de filtrado de datos
  650. public applyFilter(event: any, type: string): void {
  651. let filterValue: string;
  652. if (type == 'INP') {
  653. filterValue = (event.target as HTMLInputElement).value;
  654. } else {
  655. this.txtBuscador = event;
  656. filterValue = event;
  657. }
  658. this.dataSource.filter = filterValue.trim().toLowerCase();
  659. if (this.dataSource.paginator) {
  660. this.dataSource.paginator.firstPage();
  661. }
  662. }
  663. public openViewer(url: string) {
  664. let dialogRef: any;
  665. let fileData = {
  666. url: url,
  667. };
  668. dialogRef = this.dialog.open(WebviewerComponent, {
  669. data: fileData,
  670. width: '100%',
  671. });
  672. dialogRef.afterClosed().subscribe((result: any) => {
  673. if (result) {
  674. console.log(result);
  675. }
  676. this.isLoadingForm = false;
  677. });
  678. }
  679. // Método para dar formato a las fechas y horas
  680. public formatDate(dateRegister: string, dateUpdate: string | null): string {
  681. let date: string = dateUpdate === null ? dateRegister : dateUpdate;
  682. let arrDateTime: Array<string> = date.split(' ');
  683. let arrDate: Array<string> = arrDateTime[0].split('-');
  684. return `${arrDate[2]}-${arrDate[1]}-${arrDate[0]} ${arrDateTime[1]}`;
  685. }
  686. public async alert(type: string, dataElement: any = null) {
  687. this.isLoadingForm = true;
  688. let dataDialog: AlertData = {} as AlertData;
  689. if (type === 'CANCEL') {
  690. dataDialog = {
  691. icon: 'warning',
  692. title: 'Cancelar Solicitud',
  693. description:
  694. '¿Está seguro de cancelar la línea de solicitud de compra?',
  695. };
  696. }
  697. // Se ejecuta la alerta
  698. const dialogRef = this._dialog.open(AlertComponent, {
  699. data: dataDialog,
  700. disableClose: true,
  701. width: '350px',
  702. });
  703. // Se obtiene la respuesta obtenida por la alerta
  704. dialogRef.afterClosed().subscribe((result) => {
  705. if (result && type === 'CANCEL') {
  706. console.log(result);
  707. }
  708. });
  709. this.isLoadingForm = false;
  710. }
  711. // Funcion para descargar archivos
  712. async downloadFile(idFile: any) {
  713. try {
  714. let idEnc = localStorage.getItem('idusuario');
  715. let shortEnc = await lastValueFrom(this._encService.shortEncrypt(idEnc!));
  716. let downloadToken = await lastValueFrom(
  717. this._gdelService.getDownloadToken(
  718. idFile,
  719. shortEnc.response.encrypted,
  720. 1
  721. )
  722. );
  723. //this.downloadL ink = "http://git.ittec.mx/sam/public/api/download-file///1";
  724. //this.downloadLink = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/1`;
  725. this.downloadLink = `http://192.168.1.2:8000/api/download-file/${downloadToken.response.TOKEN}/${shortEnc.response.encrypted}/1`;
  726. console.log(this.downloadLink );
  727. this.a?.nativeElement.click();
  728. } catch (error: any) {
  729. let msg = '';
  730. if (error.error == undefined) {
  731. msg = 'Ocurrió un error inesperado.';
  732. } else if (error.error.msg == undefined) {
  733. msg = 'Ocurrió un error inesperado.';
  734. } else {
  735. msg = error.error.msg;
  736. }
  737. this.openSnackBar(msg);
  738. }
  739. }
  740. public goBack(steps: number) {
  741. window.history.go(steps * -1);
  742. }
  743. openSnackBar(msg: string) {
  744. this._snackBar.open(msg, undefined, {
  745. duration: 2500,
  746. });
  747. }
  748. selectTab(index: number) {
  749. this.active = index;
  750. switch (index) {
  751. case 0:
  752. this.getDocuments();
  753. break;
  754. case 1:
  755. this.getShareDocuments();
  756. break;
  757. case 2:
  758. break;
  759. default:
  760. break;
  761. }
  762. }
  763. refreshDocuments() {
  764. switch (this.active) {
  765. case 0:
  766. this.getDocuments();
  767. break;
  768. case 1:
  769. this.getShareDocuments();
  770. break;
  771. case 2:
  772. break;
  773. default:
  774. break;
  775. }
  776. }*/
  777. }