Advertisement
Guest User

Untitled

a guest
May 23rd, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.31 KB | None | 0 0
  1. import { Component, OnInit, group, Directive } from '@angular/core';
  2. import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
  3. import { Url } from 'url';
  4. import { Router, ActivatedRoute } from '@angular/router';
  5. import { TranslateService } from '@ngx-translate/core';
  6. import { Http, RequestOptions, RequestOptionsArgs } from '@angular/http';
  7. import { Headers } from '@angular/http';
  8. import { Observable } from 'rxjs/Observable';
  9. import { routerTransition } from '../../../router.animations';
  10. import { SystemUsersService } from '../../../shared/services/system-users.service';
  11. import { MaskService } from '../../../shared/services/mask-forms.service';
  12. import { UsersDocuments } from '../../../shared/models/system-users-documents';
  13. import { SystemUserUniversityTransportation } from '../../../shared/models/system-users-university-transportation.model';
  14. import { UniversityTransportation } from '../../../shared/models/universityTransportation.model';
  15. import { Institution } from '../../../shared/models/institution.model';
  16. import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
  17.  
  18.  
  19. @Component({
  20. selector: 'app-university-transportation',
  21. templateUrl: './university-transportation-new.component.html',
  22. styleUrls: ['./university-transportation-new.component.scss'],
  23. animations: [routerTransition()]
  24. })
  25.  
  26.  
  27. /**
  28. * @class UniversityTransportationNewComponente
  29. * @description componente utilizado para cadastrar um novo usuário universitário
  30. */
  31. export class UniversityTransportationNewComponent implements OnInit {
  32.  
  33.  
  34. public token: string = localStorage.getItem('token');
  35.  
  36. public daysOfTheWeek: Array<Object>;
  37. public institutions: String[] = ["Escolha uma instituição", "UFMS", "IFMS", "AEMS", "FUNEC", "FEA", "FIU", "FIRB"];
  38. public bloodTypes: String[] = ["Não sei informar", "A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"];
  39. public citysInstitution: String[] = ["Escolha uma cidade", "TRÊS LAGOAS - MS", "PEREIRA BARRETO - SP", "ANDRADINA - SP", "SANTA FÉ DO SUL - SP"];
  40. public phoneTypes: String[] = ["Tipo", "RESIDENCIAL", "CELULAR"];
  41. public timeToGoInstitution;
  42. public timeToBackInstitution;
  43. public visualizationPessoais: boolean = false;
  44. public visualizationEnd: boolean = false;
  45. public visualizationInsti: boolean = false;
  46. public visualizationDoc: boolean = true;
  47. public closeView: string;
  48. public localUrlRg;
  49. public localUrlCpf;
  50. public localUrlRes;
  51. public localUrlMat;
  52. public localUrlCad;
  53. public localUrlPhoto;
  54.  
  55. public formNewUser;
  56. public classPersonalData = "is-current";
  57. public classAddress = "";
  58. public classInstitution = "";
  59. public classDocuments = "";
  60. public classSave = "";
  61. public textPersonalData = "Passo Atual:";
  62. public textAddress = "";
  63. public textInstitution = "";
  64. public textDocuments = "";
  65.  
  66.  
  67. public timeGoValid: number;
  68. public timeBackValid: number;
  69. public errorTable: boolean = false;
  70.  
  71.  
  72. constructor(private translate: TranslateService, public route: ActivatedRoute, private router: Router, private systemUsersService: SystemUsersService
  73. , private maskService: MaskService, private http: Http, private modalService: NgbModal, ) {
  74.  
  75. const inputs = document.querySelectorAll('.js-photo_submit-input');
  76.  
  77. for (var i = 0; i < inputs.length; i++) {
  78. inputs[i].addEventListener('change', this.uploadImage);
  79. }
  80.  
  81.  
  82. /*
  83. * -> variável daysOfTheWeek : valores que são utilizados para exibir de forma dinâmica uma tabela
  84. * no html, referente ao período de ida e volta do aluno a universidade.
  85. *
  86. * -> variável institutions: os valores são usados no html no #selectInstitution para que possa se exibir de forma
  87. * dinâmica as opções de instituições. Ex: <option *ngFor="let institution of institutions">
  88. * O mesmo acontece para variáveis:
  89. * -> bloodTypes referente ao select #selectBlood
  90. * -> citysInstitution referente ao select #selectCity
  91. * -> phoneTypes referente ao select #selectPhone
  92. *
  93. * -> variáveis timeToGoInstitution e timeToBackInstitution:
  94. * São instaciadas como arrays na função ngOnInit().Suas posições possuem valores booleanos inicialmente falsos.
  95. * Os valores são utilizados no htm em uma tabela que possui inputs do tipo checkbox
  96. *
  97. * -> Variáveis visualizationPessoais, visualizationEnd, visualizationInsti, visualizationDoc, visualizationSave:
  98. * Variáveis booleanas utilizadas em *ngIf no html para controlar que parte do formulário é exibida
  99. *
  100. * Variáveis classPersonalData, classAddress, classInstitution, classDocuments, classSave:
  101. * Controlam o status dos passos da lista: passo atual, passo completo ou passo com erro.
  102. */
  103.  
  104. }
  105.  
  106.  
  107. ngOnInit() {
  108.  
  109. /* ############ Instanciando Arrays ################# */
  110. this.daysOfTheWeek = [{ index: 0, name: "Segunda-Feira" },
  111. { index: 1, name: "Terça-Feira" },
  112. { index: 2, name: "Quarta-Feira" },
  113. { index: 3, name: "Quinta-Feira" },
  114. { index: 4, name: "Sexta-Feira" },
  115. { index: 5, name: "Sábado" }];
  116.  
  117.  
  118. this.timeToGoInstitution = new Array(6);
  119. this.timeToBackInstitution = new Array(6);
  120.  
  121.  
  122. for (var i = 0; i < 6; i++) {
  123. this.timeToGoInstitution[i] = new Array(4);
  124. this.timeToBackInstitution[i] = new Array(4);
  125. for (var j = 0; j < 4; j++) {
  126. this.timeToGoInstitution[i][j] = false;
  127. this.timeToBackInstitution[i][j] = false;
  128. }
  129. }
  130.  
  131. /* ############ ################################ ################# */
  132.  
  133.  
  134. // Instacionando o formulário que fará o controle dos valores passados aos input
  135. this.formNewUser = new FormGroup({
  136.  
  137. personalData: new FormGroup({
  138. student: new FormControl(true),
  139. teacher: new FormControl(false),
  140. name: new FormControl(null, [Validators.required, Validators.minLength(5), Validators.maxLength(150), Validators.pattern(/^[a-z\u00C0-\u00ff A-Z]+$/)]),
  141. email: new FormControl(null, [Validators.required, Validators.minLength(5), Validators.maxLength(65), Validators.pattern(/\S+@\S+\.\S+/)], ),
  142. cpf: new FormControl(null, [Validators.required, Validators.minLength(11), Validators.maxLength(11), Validators.pattern(/^[0-9]{11}$/)]),
  143. rg: new FormGroup({
  144. number: new FormControl(null, [Validators.required, Validators.minLength(2), Validators.maxLength(15)]),
  145. date: new FormControl(null, Validators.required),
  146. state: new FormControl(null, [Validators.required, Validators.minLength(2), Validators.maxLength(2), Validators.pattern(/\b[A-Za-z][A-Za-z]/)]),
  147. }),
  148. bloodType: new FormControl(null, Validators.required),
  149. motherSname: new FormControl(null, [Validators.required, Validators.minLength(5), Validators.maxLength(150), Validators.pattern(/^[a-z\u00C0-\u00ff A-Z]+$/)]),
  150. phone: new FormGroup({
  151. name: new FormControl(null, Validators.required),
  152. numberPhone: new FormControl(null, Validators.required),
  153. })
  154. }),
  155.  
  156. address: new FormGroup({
  157. street: new FormControl(null, Validators.required),
  158. number: new FormControl(null, [Validators.required, Validators.maxLength(5)]),
  159. neighborhood: new FormControl(null, [Validators.required, Validators.minLength(2), Validators.maxLength(30), Validators.pattern(/^[a-z\u00C0-\u00ff A-Z]+$/)])
  160. }),
  161.  
  162. institution: new FormGroup({
  163. name: new FormControl(null, Validators.required),
  164. city: new FormControl(null, Validators.required),
  165. course: new FormControl(null, Validators.required),
  166. startYear: new FormControl(null, Validators.required),
  167. yearTermination: new FormControl(null, Validators.required),
  168.  
  169.  
  170. }),
  171.  
  172. files: new FormGroup({
  173. rg: new FormControl(null, Validators.required),
  174. cpf: new FormControl(null, Validators.required),
  175. comprovanteR: new FormControl(null, Validators.required),
  176. comprovanteM: new FormControl(null, Validators.required),
  177. cadM: new FormControl(null, Validators.required),
  178. foto: new FormControl(null, Validators.required),
  179. })
  180.  
  181. });
  182.  
  183.  
  184.  
  185. }
  186.  
  187. /**
  188. * @function getMask chamada pelo html para solicitar uma máscara para o service
  189. * @param typeField tipo do campo que necessita da máscara
  190. */
  191. getMask(typeField): string {
  192.  
  193. return this.maskService.getMask(typeField);
  194. }
  195.  
  196. /**
  197. * @function openVisualizationForms Controla qual parte do html está sendo exibida
  198. * e faz a validação dos passos a partir dos formGroups do formNewUser ( personalData, address ou institution).
  199. * @param step passo que ativou a ação
  200. * @param action ação previous ou next corresponde a qual botão foi clicado anterior ou próximo
  201. * @example var pD = this.formNewUser.get('personalData'); -> recupera o formGroup.
  202. * Verifica se pD é valido, se válido : classListaPasso = is-complete, se não classListaPasso = has-error.
  203. * Essa verficação ocorre na transição dos passos, o passo pode ser is-current (atual), mas só será passo atual
  204. * na primeira vez que o usuário entrar nele, ou seja, se houver uma transição entre esse passo e outro
  205. * e ele necessitar de validação já se tornará has-error e a única mudança possível a partir dai é que ele
  206. * se torne is-complete.
  207. */
  208. public openVisualizationForms(step, action) {
  209.  
  210. if (step == 'personalData' && action == 'next') {
  211.  
  212. var pD = this.formNewUser.get('personalData');
  213.  
  214. if (pD.valid) {
  215. this.textPersonalData = "Completo: ";
  216. this.classPersonalData = "is-complete";
  217.  
  218. } else {
  219. this.textPersonalData = "Erro: ";
  220. this.classPersonalData = "has-error";
  221.  
  222. }
  223. this.textAddress = "Passo Atual: ";
  224. this.classAddress = "is-current";
  225.  
  226. this.visualizationPessoais = false;
  227. this.visualizationEnd = true;
  228.  
  229. } else if (step == 'address') {
  230.  
  231. var pA = this.formNewUser.get('address');
  232.  
  233. this.visualizationEnd = false;
  234.  
  235. if (pA.valid) {
  236. this.textAddress = "Completo: ";
  237. this.classAddress = "is-complete";
  238.  
  239. } else {
  240. this.textAddress = "Erro: ";
  241. this.classAddress = "has-error";
  242.  
  243. }
  244.  
  245. if (action == 'previous') {
  246.  
  247. this.visualizationPessoais = true;
  248. this.textPersonalData = "Passo Atual: ";
  249. this.classPersonalData = "is-current";
  250.  
  251. } else if (action == 'next') {
  252.  
  253. this.visualizationInsti = true;
  254. this.textInstitution = "Passo Atual: ";
  255. this.classInstitution = "is-current";
  256.  
  257. }
  258.  
  259.  
  260.  
  261. } else if (step == 'institution') {
  262. var pI = this.formNewUser.get('institution');
  263.  
  264. this.visualizationInsti = false;
  265.  
  266. this.timeBackValid = 0;
  267. this.timeGoValid = 0;
  268.  
  269. /** interação do array do periodo de ida e volta para descobrir se está valido
  270. * se ele possuir ao menos 1 elemento selecionado por linha no final o contador é igual a 6
  271. * e o array é valido e será válido somente se o contador for exatamente 6
  272. * se for mais (mais de uma coluna selecionada por linha)
  273. * ou menos já estará inválido.
  274. */
  275. for (var i = 0; i < 6; i++) {
  276. for (var j = 0; j < 4; j++) {
  277. if (this.timeToGoInstitution[i][j]) this.timeGoValid++;
  278. if (this.timeToBackInstitution[i][j]) this.timeBackValid++;
  279.  
  280. }
  281. }
  282.  
  283. if (pI.valid) {
  284. if ((this.timeGoValid >= 6) && (this.timeBackValid >= 6)) {
  285. this.textInstitution = "Completo: ";
  286. this.classInstitution = "is-complete"
  287.  
  288. } else {
  289. this.errorTable = true;
  290. this.textInstitution = "Erro: ";
  291. this.classInstitution = "has-error";
  292.  
  293. }
  294.  
  295.  
  296. }
  297. else {
  298.  
  299. if ((this.timeGoValid < 6) && (this.timeBackValid < 6)) {
  300. this.errorTable = true;
  301. }
  302. this.textInstitution = "Erro: ";
  303. this.classInstitution = "has-error";
  304.  
  305. }
  306.  
  307. if (action == 'previous') {
  308.  
  309. this.visualizationEnd = true;
  310. this.textAddress = "Passo Atual: ";
  311. this.classAddress = "is-current";
  312.  
  313. } else if (action == 'next') {
  314.  
  315. this.visualizationDoc = true;
  316. this.textDocuments = "Passo Atual: ";
  317. this.classDocuments = "is-current";
  318. }
  319.  
  320. } else if (step == 'documents') {
  321.  
  322.  
  323. this.visualizationDoc = false;
  324.  
  325. if (action == 'previous') {
  326. this.visualizationInsti = true;
  327. this.textInstitution = "Passo Atual: ";
  328. this.classInstitution = "is-current";
  329. }
  330. }
  331. }
  332. /**
  333. * @function setValueBloodType utilizada para setar no formControl de tipo sanguíneo, o valor que o usuário informou
  334. * @param blood contém o valor do input de tipo sanguíneo
  335. * @description Ela existe, pois da maneira que foi implementado o controle dos valores com um formControl(formNewUser)
  336. * não é possível setar de maneira automática o valor do formControl correspondente a tipo sanguíneo, nome da instituição..
  337. * com o valor que é atribuido no select no html, então é preciso passar o valor por parâmetro e setar no .ts
  338. * @example O controle corresponde é recuperado.
  339. * var form = this.formNewUser.get('personalData').get('bloodType');
  340. *
  341. * O valor do select é setado no valor do controle.
  342. * form.value = blood;
  343. *
  344. * form.markAsTouched() -> essa linha existe para marcar que o controle foi "tocado", ou seja que o usuário setou um valor nele
  345. * para que o Validators.required seja válido
  346. *
  347. * form.updateValueAndValidity(); -> lança um evento para alteração de valores ou validação, pois o formNewUser
  348. * não consegue fazer esse update de forma automática.
  349. */
  350. public setValueBloodType(blood) {
  351.  
  352. // todos tipos sao validos, pq "NÃO SEI INFORMAR" também é um tipo valido.
  353. var form = this.formNewUser.get('personalData').get('bloodType');
  354.  
  355. if (blood != 'Não sei informar') {
  356. form.value = blood;
  357. } else {
  358. form.value = null;
  359. }
  360.  
  361. form.markAsTouched();
  362. form.updateValueAndValidity();
  363.  
  364.  
  365.  
  366. }
  367. /**
  368. * @function setValueInstitution utilizada para setar no formControl do nome da instituição, o valor que o usuário informou
  369. * @param inst contém o valor do input do nome da instituição
  370. */
  371. public setValueInstitution(inst) {
  372.  
  373. var form = this.formNewUser.get('institution').get('name');
  374.  
  375. if (inst != 'Escolha uma instituição') {
  376.  
  377. form.value = inst;
  378.  
  379. } else {
  380. form.value = null;
  381. }
  382.  
  383. form.markAsTouched();
  384. form.updateValueAndValidity();
  385.  
  386. }
  387.  
  388. /**
  389. * @function setValueCity utilizada para setar no formControl de cidade da instituição, o valor que o usuário informou
  390. * @param city contém o valor do input do nome da cidade
  391. */
  392. public setValueCity(city) {
  393.  
  394. var form = this.formNewUser.get('institution').get('city')
  395. if (city != 'Escolha uma cidade') {
  396.  
  397. form.value = city;
  398.  
  399. }
  400. else {
  401. form.value = null;
  402. }
  403. form.markAsTouched();
  404. form.updateValueAndValidity();
  405. }
  406.  
  407. /**
  408. * @function setValuePhoneType utilizada para setar no formControl do tipo de telefone, o valor que o usuário informou
  409. * @param phone contém o valor do input do tipo de telefone
  410. */
  411. public setValuePhoneType(phone) {
  412.  
  413. var form = this.formNewUser.get('personalData').get('phone').get('name');
  414.  
  415. if (phone != 'Tipo') {
  416.  
  417. form.value = phone;
  418.  
  419. }
  420. else {
  421. form.value = null;
  422. }
  423. form.markAsTouched();
  424. form.updateValueAndValidity();
  425.  
  426. }
  427.  
  428.  
  429. /**
  430. * @function setValuetimeToGoInstitution utiliza para mudar o valor booleano do array correspondente ao período de ida a universidade
  431. * @param i linha correspondente ao dia da semana que precisa ter o valor trocado
  432. * @param j coluna correspondente ao período que precisa ter o valor trocado
  433. */
  434. public setValuetimeToGoInstitution(i, j) {
  435. this.timeToGoInstitution[i][j] = !this.timeToGoInstitution[i][j];
  436.  
  437. }
  438.  
  439. /**
  440. * @function setValuetimeToBackInstitution utiliza para mudar o valor booleano do array correspondente ao período de retorno da universidade
  441. * @param i linha correspondente ao dia da semana que precisa ter o valor trocado
  442. * @param j coluna correspondente ao período que precisa ter o valor trocado
  443. */
  444. public setValuetimeToBackInstitution(i, j) {
  445. this.timeToBackInstitution[i][j] = !this.timeToBackInstitution[i][j];
  446.  
  447. }
  448.  
  449.  
  450.  
  451. /**
  452. * @function onFileChange utilizada para recuperar o arquivo que usuário fez upload no input e atribuí-lo ao FileControl do formNewUser,
  453. * pois é preciso guardar esses arquivo no controle para mandar para o backend.
  454. * @param event evento contém os dados do momento que a função foi disparada
  455. */
  456. public onFileChange(event) {
  457. /*
  458. * a função de fileChange é chamada cada vez que há uma mudança de valores em algum input do file
  459. * que estão no html. Como em cada input estamos fazendo o upload de apenas 1 arquivo
  460. * no array de arquivos que o evento retorna sempre haverá apenas 1 arquivo
  461. * por isso utilizamos event.target.files[0], se houvesse mais de um arquivo por input seria preciso tratar.
  462. */
  463.  
  464. //nome do campo que lançou o evento
  465. var id = event.target.id;
  466.  
  467. // Controle do formNewUser para arquivos
  468. var fileControl = this.formNewUser.controls.files;
  469.  
  470. var file = event.target.files[0];
  471. var extensao = file.name.split('.').pop();
  472. var date = new Date;
  473.  
  474. /* A atribuição de valor é feita de forma específica
  475. * se o arquivo que lançou o evento veio do input de rg,
  476. * o fileControl do rg que receberá seu valor. Se veio do input de cpf, o fileControl do cpf que receberá seu valor.
  477. */
  478. if (id == 'inputFileRg') {
  479.  
  480. fileControl.get('rg').value = new File([file], 'rg' + '.' + extensao, { type: file.type });
  481.  
  482. /*
  483. * new File([file], 'rg' + '.' + extensao, { type: file.type });
  484. * Utilizamos esse tipo de construtor apenas para que fosse possível renomear o arquivo
  485. * poderia ser feita a atribuição : fileControl.get('rg').value = file
  486. * só que ele conteria todas as informações originais dos arquivo.
  487. */
  488. } if (id == 'inputFileCpf') {
  489.  
  490. fileControl.get('cpf').value = new File([file], 'cpf' + '.' + extensao, { type: file.type });
  491. } if (id == 'inputFileComprovanteR') {
  492.  
  493. fileControl.get('comprovanteR').value = new File([file], 'comprovante_residencia' + '.' + extensao, { type: file.type });
  494. } if (id == 'inputFileComprovanteM') {
  495.  
  496. /* Nesse if é feito um tratamento de data, pois ele é referente ao comprovante de matrícula
  497. * então é preciso saber se ele é do primeiro ou segundo semestre.
  498. */
  499. if (date.getMonth() < 6) {
  500. fileControl.get('comprovanteM').value = new File([file], date.getFullYear() + '_1' + '_' + 'comprovante_matricula' + '.' + extensao, { type: file.type });
  501. } else {
  502. fileControl.get('comprovanteM').value = new File([file], date.getFullYear() + '_2' + '_' + 'comprovante_matricula' + '.' + extensao, { type: file.type });
  503. }
  504. } if (id == 'inputFileCM') {
  505.  
  506. fileControl.get('cadM').value = new File([file], 'cadastro_municipal' + '.' + extensao, { type: file.type });
  507. } if (id == 'inputFileFoto') {
  508.  
  509. fileControl.get('foto').value = new File([file], '3x4' + '.' + extensao, { type: file.type });
  510. }
  511. fileControl.updateValueAndValidity();
  512.  
  513. }
  514.  
  515. /**
  516. * @function downloadArquivo utizada para fazer download de um arquivo
  517. * @param file arquivo a ser baixado
  518. */
  519. public downloadArquivo(file): void {
  520.  
  521. /*Cria um novo objeto URL, cujo tempo de vida está ligado ao document na janela na qual este objeto foi criado.
  522. O novo objeto URL representa o objeto File ou o objeto Blob passado como argumento.*/
  523. var url = window.URL.createObjectURL(file);
  524.  
  525. var a = document.createElement("a");
  526. a.setAttribute("href", url);
  527.  
  528. //propriedade que precisa ser instaciada para que seja possível fazer o dowload do arquivo
  529. a.setAttribute("download", file.name);
  530.  
  531. a.click();
  532.  
  533. }
  534.  
  535. /**
  536. * @function onSubmit utilizada para submeter os dados informados pelo o usuário para cadastro
  537. */
  538. public onSubmit() {
  539.  
  540. var documents: Array<UsersDocuments> = new Array();
  541. const phonesControl = this.formNewUser.controls.personalData.controls.phone; // controle dos telefones
  542. const addressControl = this.formNewUser.controls.address; // controle dos endereços
  543. var personalDataControl = this.formNewUser.controls.personalData;
  544. var institutionControl = this.formNewUser.controls.institution;
  545. var profession;
  546.  
  547. // adicionando no array de documentos os valores passados nos inputs
  548. documents.push({ name: "CPF", value: personalDataControl.get('cpf').value, expeditionDate: null, state: null });
  549. documents.push({ name: "RG", value: personalDataControl.get('rg').get('number').value, expeditionDate: personalDataControl.get('rg').get('date').value, state: personalDataControl.get('rg').get('state').value });
  550.  
  551. // recuperando o valor do input de profissão e setando na variável profession
  552. // personalDataControl.get('teacher').value retorna um valor verdadeiro (true) ou falso (false)
  553.  
  554. if (personalDataControl.get('teacher').value) {
  555. profession = "PROFESSOR";
  556. }
  557. if (personalDataControl.get('student').value) {
  558. profession = "ESTUDANTE";
  559. }
  560.  
  561.  
  562. //construindo o objeto com as informações do novo usuário para mandar para o backend
  563. var newUserU: SystemUserUniversityTransportation = new SystemUserUniversityTransportation(
  564.  
  565. personalDataControl.get('name').value,
  566. personalDataControl.get('email').value,
  567. '',
  568. '',
  569. // personalDataControl.get('login').value,
  570. //personalDataControl.get('password').value,
  571. '',
  572. documents,
  573. [{ //ADDRESS
  574. name: 'RESIDENCIAL',
  575. street: addressControl.get('street').value,
  576. number: addressControl.get('number').value,
  577. complement: null,
  578. neighborhood: addressControl.get('neighborhood').value,
  579. zip_code: '15385000',
  580. city: 'Ilha Solteira',
  581. state: 'SP'
  582. }],
  583. [{ //PHONE
  584. name: phonesControl.get('name').value,
  585. number_phone: phonesControl.get('numberPhone').value
  586. }],
  587. this.formNewUser.active,
  588. new UniversityTransportation(
  589. profession,
  590. personalDataControl.value.bloodType,
  591. personalDataControl.value.motherSname,
  592. new Institution(
  593. institutionControl.get('name').value,
  594. institutionControl.get('city').value,
  595. institutionControl.get('course').value,
  596. institutionControl.get('startYear').value,
  597. institutionControl.get('yearTermination').value,
  598. this.timeToGoInstitution,
  599. this.timeToBackInstitution
  600. )
  601. )
  602. );
  603.  
  604.  
  605.  
  606. this.systemUsersService.registerUsersAdmTransporte(newUserU, this.token)
  607. .subscribe((apiResponse: string) => {
  608.  
  609. var id: string = apiResponse;
  610. const fileControl = this.formNewUser.get('files');
  611. const formData: any = new FormData();
  612. var teste = this.formNewUser.controls.files.controls;
  613.  
  614. formData.append('userId', id);
  615.  
  616.  
  617. for (const control in this.formNewUser.get('files').controls) {
  618.  
  619. var file = fileControl.get(control).value;
  620.  
  621.  
  622. if (file != null) {
  623.  
  624. formData.append("uploads[]", file, file['name']);
  625. }
  626. }
  627.  
  628. this.systemUsersService.filesUpload(formData, this.token).
  629. subscribe((apiResponse: Object) => {
  630.  
  631. alert('Usuário Cadastrado com sucesso!');
  632. this.router.navigateByUrl('/university-transportation/UniversityTransportationHome'); //ROTEAMENTO
  633.  
  634. }, (error: any) => {
  635.  
  636. alert('erro na submissão do cadastro de usuário')
  637. if (error._body === '{"errors":["Usuário já cadastrado."]}') {
  638. alert('Já cadastrado')
  639. }
  640.  
  641. });
  642. });
  643. }
  644.  
  645. public openRg(contentRg): void {
  646. this.modalService.open(contentRg).result.then((result) => {
  647. this.closeView = `Closed with: ${result}`;
  648. }, (reason) => {
  649. this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
  650. });
  651. }
  652.  
  653. public openCpf(contentCpf): void {
  654. this.modalService.open(contentCpf).result.then((result) => {
  655. this.closeView = `Closed with: ${result}`;
  656. }, (reason) => {
  657. this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
  658. });
  659. }
  660.  
  661. public openRes(contentRes): void {
  662. this.modalService.open(contentRes).result.then((result) => {
  663. this.closeView = `Closed with: ${result}`;
  664. }, (reason) => {
  665. this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
  666. });
  667. }
  668.  
  669. public openMat(contentMat): void {
  670. this.modalService.open(contentMat).result.then((result) => {
  671. this.closeView = `Closed with: ${result}`;
  672. }, (reason) => {
  673. this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
  674. });
  675. }
  676.  
  677. public openCad(contentCad): void {
  678. this.modalService.open(contentCad).result.then((result) => {
  679. this.closeView = `Closed with: ${result}`;
  680. }, (reason) => {
  681. this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
  682. });
  683. }
  684.  
  685. public openPhoto(contentPhoto): void {
  686. this.modalService.open(contentPhoto).result.then((result) => {
  687. this.closeView = `Closed with: ${result}`;
  688. }, (reason) => {
  689. this.closeView = `Dismissed ${this.getDismissReason(reason)}`;
  690. });
  691. }
  692.  
  693. private getDismissReason(reason: any): string {
  694. if (reason === ModalDismissReasons.ESC) {
  695. return 'by pressing ESC';
  696. } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
  697. return 'by clicking on a backdrop';
  698. } else {
  699. return `with: ${reason}`;
  700. }
  701. }
  702.  
  703. showPreviewRg(event) {
  704. var reader = new FileReader();
  705. reader.onload = (event: any) => {
  706. this.localUrlRg = event.target.result;
  707. }
  708. reader.readAsDataURL(event);
  709. }
  710.  
  711. showPreviewCpf(event) {
  712. var reader = new FileReader();
  713. reader.onload = (event: any) => {
  714. this.localUrlCpf = event.target.result;
  715. }
  716. reader.readAsDataURL(event);
  717. }
  718.  
  719. showPreviewRes(event) {
  720. var reader = new FileReader();
  721. reader.onload = (event: any) => {
  722. this.localUrlRes = event.target.result;
  723. }
  724. reader.readAsDataURL(event);
  725. }
  726.  
  727. showPreviewMat(event) {
  728. var reader = new FileReader();
  729. reader.onload = (event: any) => {
  730. this.localUrlMat = event.target.result;
  731. }
  732. reader.readAsDataURL(event);
  733. }
  734.  
  735. showPreviewCad(event) {
  736. var reader = new FileReader();
  737. reader.onload = (event: any) => {
  738. this.localUrlCad = event.target.result;
  739. }
  740. reader.readAsDataURL(event);
  741. }
  742.  
  743. showPreviewPhoto(event) {
  744. var reader = new FileReader();
  745. reader.onload = (event: any) => {
  746. this.localUrlPhoto = event.target.result;
  747. }
  748. reader.readAsDataURL(event);
  749. }
  750.  
  751. /**
  752. * @function changeLang utilizada para traduzir a página
  753. * @param language linguagem para qual a página deve ser traduzida
  754. * @description palavras usadas na tradução : assets/i18n
  755. */
  756. changeLang(language: string) {
  757. this.translate.use(language);
  758. }
  759.  
  760.  
  761.  
  762.  
  763.  
  764.  
  765.  
  766.  
  767. uploadImage(e) {
  768. const fileInput = e.target;
  769. const uploadBtn = e.target.parentNode;
  770. const deleteBtn = e.target.parentNode.childNodes[7];
  771.  
  772. const reader = new FileReader();
  773. //console.log(e.target.files[0].type)
  774.  
  775.  
  776. reader.onload = function (e: any) {
  777. uploadBtn.setAttribute('style', `background-image: url('${e.target.result}');`);
  778. uploadBtn.classList.add('photo_submit--image');
  779. fileInput.setAttribute('disabled', 'disabled');
  780. };
  781.  
  782. reader.readAsDataURL(e.target.files[0]);
  783.  
  784. deleteBtn.addEventListener('click', () => {
  785. uploadBtn.removeAttribute('style');
  786. uploadBtn.classList.remove('photo_submit--image');
  787.  
  788. setTimeout(() => {
  789. fileInput.removeAttribute('disabled', 'disabled');
  790. }, 200);
  791. });
  792. }
  793.  
  794.  
  795.  
  796.  
  797.  
  798.  
  799.  
  800.  
  801.  
  802.  
  803.  
  804.  
  805.  
  806. }
  807.  
  808.  
  809.  
  810.  
  811.  
  812.  
  813.  
  814.  
  815.  
  816.  
  817.  
  818.  
  819.  
  820.  
  821.  
  822.  
  823.  
  824.  
  825.  
  826.  
  827.  
  828.  
  829.  
  830.  
  831.  
  832.  
  833.  
  834.  
  835.  
  836. /*
  837.  
  838. public erroRg: boolean = false;
  839. public erroCpf: boolean = false;
  840. public erroFoto: boolean = false;
  841. public erroCpr: boolean = false;
  842. public erroCpm: boolean = false;
  843. public erroCdm: boolean = false;
  844.  
  845. verificaDocs() {
  846. const fileControl = this.formNewUser.get('files');
  847.  
  848. if (fileControl.get('rg').value == null) {
  849. this.erroRg = true;
  850. } else {
  851. this.erroRg = false;
  852. }
  853. if (fileControl.get('cpf').value == null) {
  854. this.erroCpf = true;
  855. } else {
  856. this.erroCpf = false;
  857. }
  858. if (fileControl.get('foto').value == null) {
  859. this.erroFoto = true;
  860. } else {
  861. this.erroFoto = false;
  862. }
  863. if (fileControl.get('comprovanteR').value == null) {
  864. this.erroCpr = true;
  865. } else {
  866. this.erroCpr = false;
  867. }
  868. if (fileControl.get('comprovanteM').value == null) {
  869. this.erroCpm = true;
  870. } else {
  871. this.erroCpm = false;
  872. }
  873. if (fileControl.get('cadM').value == null) {
  874. this.erroCdm = true;
  875. } else {
  876. this.erroCdm = false;
  877. }
  878. }
  879. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement