UNPKG

catng

Version:

Angular Dynamic Form Input Component

1,360 lines (1,336 loc) 363 kB
import * as i0 from '@angular/core'; import { Injectable, inject, Component, EventEmitter, Output, Input, ViewChild, HostListener, Pipe, ViewEncapsulation, ViewChildren, ChangeDetectorRef } from '@angular/core'; import { throwError, Observable, BehaviorSubject, Subject, lastValueFrom, catchError, tap, finalize } from 'rxjs'; import { HttpClient, HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http'; import * as i1 from '@angular/router'; import { RouterModule, Router } from '@angular/router'; import * as i2 from 'primeng/api'; import * as i1$1 from '@angular/common'; import { DatePipe, CommonModule } from '@angular/common'; import * as i2$3 from '@ngx-translate/core'; import { TranslateService, TranslateModule } from '@ngx-translate/core'; import * as i2$1 from 'primeng/fileupload'; import { FileUploadModule } from 'primeng/fileupload'; import * as i2$2 from '@angular/forms'; import { FormBuilder, FormControl, FormGroup, Validators, NG_VALUE_ACCESSOR, FormsModule, ReactiveFormsModule } from '@angular/forms'; import * as i3 from 'primeng/autocomplete'; import { AutoCompleteModule } from 'primeng/autocomplete'; import * as i4 from 'primeng/datepicker'; import { DatePickerModule } from 'primeng/datepicker'; import * as i5 from 'primeng/checkbox'; import { CheckboxModule } from 'primeng/checkbox'; import { DragDropModule } from 'primeng/dragdrop'; import * as i11 from 'primeng/dropdown'; import { DropdownModule } from 'primeng/dropdown'; import * as i6 from 'primeng/inputmask'; import { InputMaskModule } from 'primeng/inputmask'; import * as i7 from 'primeng/inputnumber'; import { InputNumberModule } from 'primeng/inputnumber'; import { InputSwitchModule } from 'primeng/inputswitch'; import * as i8 from 'primeng/inputtext'; import { InputTextModule } from 'primeng/inputtext'; import { MessageModule } from 'primeng/message'; import { MessagesModule } from 'primeng/messages'; import * as i9 from 'primeng/multiselect'; import { MultiSelectModule } from 'primeng/multiselect'; import * as i10 from 'primeng/radiobutton'; import { RadioButtonModule } from 'primeng/radiobutton'; import * as i12 from 'primeng/rating'; import { RatingModule } from 'primeng/rating'; import * as i13 from 'primeng/tag'; import { TagModule } from 'primeng/tag'; import * as i6$1 from 'primeng/calendar'; import { CalendarModule } from 'primeng/calendar'; import { ChipModule } from 'primeng/chip'; import * as i18 from 'primeng/colorpicker'; import { ColorPickerModule } from 'primeng/colorpicker'; import * as i17 from 'primeng/editor'; import { EditorModule } from 'primeng/editor'; import * as i11$1 from 'primeng/textarea'; import { TextareaModule } from 'primeng/textarea'; import * as i15 from 'primeng/password'; import { PasswordModule } from 'primeng/password'; import * as i16 from 'primeng/tooltip'; import { TooltipModule } from 'primeng/tooltip'; import * as i1$2 from 'primeng/config'; import * as i5$1 from 'primeng/button'; import { ButtonModule } from 'primeng/button'; import { cloneDeep } from 'lodash'; import * as i4$1 from 'primeng/table'; import { TableModule } from 'primeng/table'; import * as i2$4 from 'primeng/tieredmenu'; import { TieredMenuModule } from 'primeng/tieredmenu'; import * as i7$1 from 'primeng/splitbutton'; import { SplitButtonModule } from 'primeng/splitbutton'; import * as i1$3 from 'primeng/dialog'; import { DialogModule } from 'primeng/dialog'; import * as i1$4 from 'primeng/toolbar'; import { ToolbarModule } from 'primeng/toolbar'; import * as i1$5 from 'primeng/selectbutton'; import { SelectButtonModule } from 'primeng/selectbutton'; import * as i1$6 from 'primeng/confirmdialog'; import { ConfirmDialogModule } from 'primeng/confirmdialog'; import * as i2$5 from 'primeng/toast'; import { ToastModule } from 'primeng/toast'; import * as i1$7 from 'primeng/fieldset'; import { FieldsetModule } from 'primeng/fieldset'; import * as i1$8 from 'primeng/drawer'; import { DrawerModule } from 'primeng/drawer'; import * as i1$9 from 'primeng/breadcrumb'; import { BreadcrumbModule } from 'primeng/breadcrumb'; import * as i1$a from 'ng2-pdf-viewer'; import { PdfViewerModule } from 'ng2-pdf-viewer'; class ApiPaths { getUrl; listUrl; addUrl; updateUrl; deleteUrl; } class Filter { field; value; matchMode; constructor(field, value, matchMode) { this.field = field; this.value = value; this.matchMode = matchMode; } } class Sort { field; order; } class FilterPageSort { first = 0; rows = 15; filter; sort; } class FormParameter { Id; Data; ParentId; //ParentItem:any; PrimaryKeyName = "Id"; ParentIdPropertyName; ResultProperty; IsReactive = false; } var Comp; (function (Comp) { Comp["dataType"] = "string"; Comp["dateFormat"] = "dd.mm.yy"; Comp[Comp["maxFileSize"] = 104857600] = "maxFileSize"; Comp["user"] = "portalErisim"; Comp["lsJwt"] = "portalAT"; Comp["lsRefresh"] = "portalRT"; Comp["lsLocale"] = "portalLocale"; Comp["lsSunucu"] = "portalSunucu"; })(Comp || (Comp = {})); var Icon; (function (Icon) { Icon["login"] = "pi pi-sign-in"; Icon["logining"] = "pi pi-spin pi-spinner"; Icon["actions"] = "pi pi-bars"; Icon["list"] = "pi pi-list"; Icon["edit"] = "pi pi-pencil"; Icon["save"] = "pi pi-check"; Icon["new"] = "pi pi-file-o"; Icon["assign"] = "pi pi-forward"; Icon["checkc"] = "pi pi-check-circle"; Icon["checks"] = "pi pi-check-square"; Icon["minusc"] = "pi pi-minus-circle"; Icon["timesc"] = "pi pi-times-circle"; Icon["times"] = "pi pi-times"; Icon["link"] = "pi pi-external-link"; Icon["folder"] = "pi pi-folder"; Icon["foldero"] = "pi pi-folder-open"; Icon["pdf"] = "pi pi-file-pdf"; Icon["excel"] = "pi pi-file-excel"; Icon["word"] = "fas fa-file-word"; Icon["send"] = "pi pi-send"; })(Icon || (Icon = {})); var InputTypeEnum; (function (InputTypeEnum) { InputTypeEnum["readonly"] = "readonly"; //form için elmanlar InputTypeEnum["form"] = "form"; InputTypeEnum["row"] = "row"; InputTypeEnum["column"] = "column"; InputTypeEnum["card"] = "card"; //inputlar InputTypeEnum["number"] = "number"; InputTypeEnum["int"] = "int"; InputTypeEnum["decimal"] = "decimal"; InputTypeEnum["display"] = "display"; InputTypeEnum["currency"] = "currency"; InputTypeEnum["textbox"] = "textbox"; InputTypeEnum["treeselect"] = "treeselect"; InputTypeEnum["editor"] = "editor"; InputTypeEnum["dropdown"] = "dropdown"; InputTypeEnum["multidropdown"] = "multidropdown"; InputTypeEnum["multiselect"] = "multiselect"; // boolean='boolean', InputTypeEnum["checkbox"] = "checkbox"; InputTypeEnum["checkboxgroup"] = "checkboxgroup"; InputTypeEnum["date"] = "date"; InputTypeEnum["dateTime"] = "datetime"; InputTypeEnum["time"] = "time"; InputTypeEnum["radiobutton"] = "radiobutton"; InputTypeEnum["switchbutton"] = "switchbutton"; InputTypeEnum["radiogroup"] = "radiogroup"; InputTypeEnum["password"] = "password"; InputTypeEnum["picklist"] = "picklist"; InputTypeEnum["selection"] = "selection"; InputTypeEnum["routerlink"] = "routerlink"; InputTypeEnum["profilephoto"] = "profilephoto"; InputTypeEnum["userphoto"] = "userphoto"; InputTypeEnum["icon"] = "icon"; InputTypeEnum["mask"] = "mask"; InputTypeEnum["textarea"] = "textarea"; InputTypeEnum["email"] = "email"; InputTypeEnum["phone"] = "phone"; InputTypeEnum["alphabetic"] = "alphabetic"; InputTypeEnum["pnum"] = "pnum"; InputTypeEnum["chips"] = "chips"; InputTypeEnum["tree"] = "tree"; InputTypeEnum["fileupload"] = "fileupload"; InputTypeEnum["autocomplete"] = "autocomplete"; InputTypeEnum["longDate"] = "longDate"; InputTypeEnum["shortDate"] = "shortDate"; InputTypeEnum["innerHTML"] = "innerHTML"; InputTypeEnum["link"] = "link"; InputTypeEnum["fileupload_yabancidil"] = "fileupload_yabancidil"; InputTypeEnum["contact"] = "contact"; InputTypeEnum["listitems"] = "listitems"; InputTypeEnum["yesNo"] = "yesNo"; InputTypeEnum["colorPicker"] = "colorPicker"; InputTypeEnum["rating"] = "rating"; InputTypeEnum["matrix"] = "matrix"; InputTypeEnum["tag"] = "tag"; })(InputTypeEnum || (InputTypeEnum = {})); var MessageStatusType; (function (MessageStatusType) { MessageStatusType["success"] = "success"; MessageStatusType["warning"] = "warning"; MessageStatusType["error"] = "error"; MessageStatusType["warn"] = "warn"; MessageStatusType["info"] = "info"; })(MessageStatusType || (MessageStatusType = {})); var SubmitType; (function (SubmitType) { SubmitType["insert"] = "insert"; SubmitType["update"] = "update"; SubmitType["delete"] = "delete"; SubmitType["login"] = "login"; })(SubmitType || (SubmitType = {})); var FileShowTypeEnum; (function (FileShowTypeEnum) { FileShowTypeEnum["upload"] = "upload"; FileShowTypeEnum["uploadAndShow"] = "uploadAndShow"; FileShowTypeEnum["list"] = "list"; FileShowTypeEnum["tableButton"] = "tableButton"; FileShowTypeEnum["profilePhoto"] = "profilePhoto"; FileShowTypeEnum["show"] = "show"; })(FileShowTypeEnum || (FileShowTypeEnum = {})); class FormControlTemplate { type; inputType = InputTypeEnum.textbox; key; label; value; explanation; placeholder; required; readonly = false; minLength; maxLength; autoComplete; //yeni item butonu ile ilgili alanlar newItemButton = false; newItemButtonLabel; newItemButtonClick; //yeni item butonu ile ilgili alanlar class; style; show = true; oneMore = false; disabled; //mask textbox mask; //number min; max; prefix; suffix; step; //select,dropdown,multiselect options; optionLabel; optionValue; showClear; autoDisplayFirst; virtualScroll; filter; editable; virtualScrollItemSize; grouped; display; selectionLimit; refUrl; refKey; queryParameter; //calendar minDate; maxDate; showTime = false; timeOnly = false; showSeconds = false; //texterea rows; cols; autoResize; //fileupload fileCanUpload = true; fileRefEntityId; //table id veri tabanında ki tablolara karşılık geliyor fileEntityId; fileUrl; fileDeleteUrl; fileUploadUrl; fileDownloadUrl; fileListUrl; fileShowType; fileShowName; fileName; fileBorder; fileRadius; fileMime; fileWidth; fileHeight; fileButtonText; picklistTarget = []; picklistSource = []; children = []; // Row and Column //row?: RowConfig[] = []; //defaultCol?: number = 1; showGrid = true; forceSelection = false; rowOrder = 0; } class FormGroupTemplate { refEntityId; //table id veri tabanında ki tablolara karşılık geliyor controls = []; formGroup; formSubmited = false; } class FormGroupControlTemplate { key; refEntityId; //table id veri tabanında ki tablolara karşılık geliyor control = {}; formGroup; formSubmited = false; } class ResponseModel { statusCode; errorCode; message; data; listOptions; // dyanmic bir list olacaksa //dynamic form oluşturmak için formControlTemplate = []; //pagination pageNo; pageSize; totalCount; totalPages; } class AppConfig { production; API_URL; baseurl; apiName; projects; projectsApi; constructor() { } } class InputControlCommand { key; command; } class ListOptions { dataList; //kayıtlar tableSize; columns; //kolonların adları columnsRowExpansion; //RowExpansion kolonların adları filterColumns = []; // hangi alanların filtreleneceğini bildirir tableName = "Liste"; //tablo adı dataKey = "Id"; pageSize = 50; loading = false; scrollable = true; scrollHeight = "400px"; formMode = "modal"; //modal,inline isHeader = true; isRowIndexVisible = false; isRowExpansion = false; rowIndexText = "No"; isRowClick = true; downloadExcel = false; isSearchableFilter = false; isLazyLoading = false; print = false; isComplexSearchEnabled = false; isSearchEnabled = false; isRefreshButton = true; isAddButton = true; isActionsButton = false; customButtons = []; styleClass; isRowEdit = false; showFooter = false; groupRowsBy; rowGroupMode; isReOrderableColumns = false; selectionMode = "single"; } class Column { refEntityId; field; header; routerLinkText; type = InputTypeEnum.textbox; filter = false; isMergeable = false; className; isEdit = false; isRowClick = false; index; columnName; columnIndex; fileCanUpload = false; width; height; border; // = '2px solid #d2d6de;'; radius; // = "50%"; class; style; pTooltip = false; tooltipText; tooltipPosition = "top"; command; isRowExpansion = false; options; optionlabel; optionvalue; readonly = false; showTotal = false; showButton = false; editField; tagField; backgroundColor = ""; } // tslint:disable:no-bitwise class JwtHelperService { urlBase64Decode(str) { let output = str.replace(/-/g, '+').replace(/_/g, '/'); switch (output.length % 4) { case 0: { break; } case 2: { output += '=='; break; } case 3: { output += '='; break; } default: { throw new Error('Illegal base64url string!'); } } return this.b64DecodeUnicode(output); } // credits for decoder goes to https://github.com/atk b64decode(str) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; let output = ''; str = String(str).replace(/=+$/, ''); if (str.length % 4 === 1) { throw new Error(`'atob' failed: The string to be decoded is not correctly encoded.`); } for ( // initialize result and counters let bc = 0, bs, buffer, idx = 0; // get next character (buffer = str.charAt(idx++)); // character found in table? initialize bit storage and add its ascii value; ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), // and if not first of each 4 characters, // convert the first 8 bits to one ascii character bc++ % 4) ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6)))) : 0) { // try to find character in table (0-63, not found => -1) buffer = chars.indexOf(buffer); } return output; } b64DecodeUnicode(str) { return decodeURIComponent(Array.prototype.map .call(this.b64decode(str), (c) => { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }) .join('')); } decodeToken(token) { if (!token || token === '') { return null; } const parts = token.split('.'); if (parts.length !== 3) { throw new Error(`The inspected token doesn't appear to be a JWT. Check to make sure it has three parts and see https://jwt.io for more.`); } const decoded = this.urlBase64Decode(parts[1]); if (!decoded) { throw new Error('Cannot decode the token.'); } return JSON.parse(decoded); } getTokenExpirationDate(token) { let decoded; decoded = this.decodeToken(token); if (!decoded || !decoded.hasOwnProperty('exp')) { return null; } const date = new Date(0); date.setUTCSeconds(decoded.exp); return date; } isTokenExpired(token, offsetSeconds) { if (!token || token === '') { return true; } const date = this.getTokenExpirationDate(token); offsetSeconds = offsetSeconds || 0; if (date === null) { return false; } return !(date.valueOf() > new Date().valueOf() + offsetSeconds * 1000); } getAuthScheme(authScheme, request) { if (typeof authScheme === 'function') { return authScheme(request); } return authScheme; } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: JwtHelperService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: JwtHelperService, providedIn: 'root' }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: JwtHelperService, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }] }); class GlobalService { router; confirmationService; messageService; jwtHelper; appConfig; http; constructor(router, confirmationService, messageService, jwtHelper) { this.router = router; this.confirmationService = confirmationService; this.messageService = messageService; this.jwtHelper = jwtHelper; this.appConfig = inject(AppConfig); this.http = inject(HttpClient); } getUserLocal() { let token = this.getTokenLocal(); if (!token) return null; let expirationDate = this.jwtHelper.getTokenExpirationDate(token); let user = this.jwtHelper.decodeToken(token); if (user && user.id && user.id != 0) { user.roles = user.roles ?? user['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']; } return user; } isAuthenticated() { return this.getUserLocal() ? true : false; } getApiName() { return this.appConfig.apiName ?? ""; } navigate(commands, extras) { this.router.navigate(commands, extras); } onError(error, cmp) { if (cmp) { cmp.blocked = false; cmp.success = false; } if ([401, 403].includes(error.status)) { if (this.getTokenLocal()) { // this.logout(); this.showMessage('warring', 'Oturum süreniz dolmuştur.'); } } else { this.onErrorMessage(error); } return throwError(() => error); //() => new Error(error); } onSuccess(cmp) { if (cmp) { cmp.success = true; } } showMessage(status, mesaj, konu) { let severity_, summary_; if (status == 'error' || status == false || status == 0 || status == 'hata') { severity_ = 'error'; summary_ = konu ?? 'Hata'; } else if (status == 'success' || status == true || status == 1 || status == 'başarılı' || status == 'basarili') { severity_ = 'success'; summary_ = konu ?? 'Başarılı'; } else if (status == 'warn' || status == 'warring' || status == 2 || status == 'uyarı' || status == 'uyari') { severity_ = 'warn'; summary_ = konu ?? 'Uyarı'; } else if (status == 'info' || status == 3 || status == 'bilgi') { severity_ = 'info'; summary_ = konu ?? 'Bilgi'; } this.messageService.add({ severity: severity_, summary: summary_, detail: mesaj, life: 5000, }); } onErrorMessage(event, mesaj, konu) { let severity_, summary_; severity_ = 'error'; summary_ = konu ?? 'Hata'; let error = event?.error?.Message ?? event.error; console.error(event); let hataIndex = -1; if (error && error.length > 0) { hataIndex = error?.indexOf('HATA!'); } if ((hataIndex || hataIndex == 0) && hataIndex > -1) { hataIndex += 5; let hataIndexSon = error?.indexOf('\r\n'); if (hataIndexSon < 0) { hataIndexSon = error.length; } mesaj = error?.substr(hataIndex, hataIndexSon - hataIndex); } else if (!mesaj) { let index; if (event.status == 400) { mesaj = error ?? event.error?.title ?? 'Bir veya daha fazla form doğrulama hatası oluştu.'; } else { mesaj = error; // if (event && event.error && event.error.length > 0) // index = event.error?.indexOf('\r\n') ?? -1; // mesaj = error ?? index > -1 ? hataIndex.error.substr(0, index) : hataIndex.message; } } this.messageService.add({ severity: severity_, summary: summary_, detail: mesaj, life: 5000, }); } showMessageData(data) { let detail, severity, summary; if (data == true) { detail = 'İşlem başarılı'; summary = 'Başarılı'; severity = 'success'; } else if (data instanceof HttpErrorResponse) { const body = data.error || ''; const err = (body.Data && body.Data.Hata) || data.statusText; severity = 'error'; summary = data.name; detail = err; } else { if (typeof data === 'string') { data = JSON.parse(data); } if (data.Success == false || (data.Data && data.Data.Success == false)) { severity = 'error'; summary = 'Hata'; if (data.Success == false) { detail = data.Mesaj || data.Data.Mesaj; } } else { detail = data.Mesaj || data?.Data?.Detail || data.Data?.Mesaj || ''; summary = 'Başarılı'; severity = 'success'; } } this.messageService.add({ severity: severity, summary: summary, detail: detail, }); } confirm(header, message, callback, icon, acceptLabel, rejectLabel) { this.confirmationService.confirm({ header: header, message: message, icon: icon, acceptLabel: acceptLabel, rejectLabel: rejectLabel, rejectButtonStyleClass: "p-button-danger mr-3", accept: () => { callback(); }, }); } getIpClient() { return this.http.get('https://api.ipify.org/?format=json', { responseType: 'json', }); } convertToDate(tarih) { if (tarih instanceof Date) return tarih; if (!tarih) { return null; } let gun = +tarih.substring(0, 2); let ay = +tarih.substring(3, 5); let yil = +tarih.substring(6, 10); let saat = 0; let dakika = 0; if (tarih.length > 10) { saat = +tarih.substring(11, 13); dakika = +tarih.substring(14, 16); } return new Date(yil, ay - 1, gun, saat, dakika); } convertToTime(saatInput) { let tarih = new Date(); let saat = +saatInput.split(":")[0]; let dakika = +saatInput.split(":")[1]; return new Date(tarih.getFullYear(), tarih.getMonth(), tarih.getDay(), saat, dakika); } convertToStringTime(tarih) { if (typeof tarih != "string") return tarih.getHours() + ":" + (tarih.getMinutes().length == 1 ? "0" + tarih.getMinutes() : tarih.getMinutes()); else if (tarih.toString().length < 10) { return tarih; } else { let saat = tarih.substring(11, 13); let dakika = tarih.substring(14, 16); return saat + ":" + dakika; } } convertToDatetoString(tarih) { if (!tarih) { return null; } let gun = +tarih.substring(0, 2); let ay = +tarih.substring(3, 5); let yil = +tarih.substring(6, 10); let saat = 0; let dakika = 0; if (tarih.length > 10) { saat = +tarih.substring(11, 13); dakika = +tarih.substring(14, 16); } return yil + "-" + ay + "-" + gun + " " + saat + ":" + dakika; } convertToLocalDate(responseDate) { try { if (responseDate != null) { if (typeof responseDate === 'string') { if (String(responseDate.indexOf('T') >= 0)) { responseDate = responseDate.split('T')[0]; } if (String(responseDate.indexOf('+') >= 0)) { responseDate = responseDate.split('+')[0]; } } responseDate = new Date(responseDate); const newDate = new Date(responseDate.getFullYear(), responseDate.getMonth(), responseDate.getDate(), 0, 0, 0); const userTimezoneOffset = newDate.getTimezoneOffset() * 60000; const finalDate = new Date(newDate.getTime() - userTimezoneOffset); return finalDate; } else { return null; } } catch (error) { return responseDate; } } //#region localstorce getCookieValue(cookieName) { const allCookies = decodeURIComponent(document.cookie).split("; "); for (let i = 0; i < allCookies.length; i++) { const cookie = allCookies[i]; if (cookie.startsWith(cookieName + "=")) { return cookie.substring(cookieName.length + 1); } } return ""; } getTokenLocal() { return localStorage.getItem('auth-token'); } setTokenLocal(token) { localStorage.removeItem('auth-token'); localStorage.setItem('auth-token', token); } setRefreshTokenLocal(token) { localStorage.removeItem('auth-token'); localStorage.setItem('auth-token', token); } removeToken() { localStorage.removeItem('auth-token'); localStorage.removeItem('menu-list'); } setLocalStorage(key, value) { localStorage.setItem(key, value); } removeLocalStorage(key) { localStorage.removeItem(key); } getLocalStorage(key) { return localStorage.getItem(key); } removeMenuList() { localStorage.removeItem('menu-list'); } //#endregion //#region kontroller isEmpty(deger, bosGecilebilir) { return deger == null || deger == undefined || deger == 'null' || deger == 'undefined' || ((deger instanceof Array) && (!deger.length || deger.length == 0)) || (!bosGecilebilir ? deger === '' : false); } isNumber(deger) { return typeof deger === 'number' || Object.prototype.toString.call(deger) === '[object Number]'; } isDate(data) { if (data instanceof Date) { return true; } return false; } isTckn(tckn) { let deger = new String(tckn); let sonuc = true; if (deger) { if (deger.substring(0, 1) == "0" || deger.length > 11 || deger.length < 11) { sonuc = false; } if (sonuc == true) { var i = 9; let md = ''; let mc = ''; let digit; let mr = ''; while (digit = deger.charAt(--i)) { i % 2 == 0 ? md += digit : mc += digit; } if ((((+(md.split('').join('+')) * 7) - +(mc.split('').join('+'))) % 10) != parseInt(deger.slice(9, 1), 10)) { sonuc = false; } if (sonuc == true) { for (var c = 0; c <= 9; c++) { mr += deger.charAt(c); } if (+(mr.split('').join('+')) % 10 != parseInt(deger.slice(10, 1), 10)) { sonuc = false; } } } } return sonuc; } isIban(deger) { let sonuc = true; if (deger) { sonuc = /^([a-zA-Z0-9]{4} ){2,8}[a-zA-Z0-9]{1,4}|[a-zA-Z0-9]{12,34}$/.test(deger); } return sonuc; } iban(control) { if (this.isEmpty(control.value) || this.isIban(control.value)) { return null; } return { iban: true }; } tckn(control) { if (this.isEmpty(control.value) || this.isTckn(control.value)) { return null; } return { tckn: true }; } //#endregion handleBlobResponse(event) { let blob = event.body; var contentDispositionHeader = event.headers.get('Content-Disposition'); if (contentDispositionHeader) { var result = contentDispositionHeader .split(';')[1] .trim() .split('=')[1]; if (result) { var fileName = result.replace(/"/g, ''); let link = document.createElement('a'); link.style.display = 'none'; document.body.appendChild(link); if (link.getAttribute('download') !== undefined) { link.setAttribute('href', URL.createObjectURL(blob)); link.setAttribute('download', fileName); link.click(); } document.body.removeChild(link); } } } getBodyHeight() { return document.body.clientHeight - 50; } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: GlobalService, deps: [{ token: i1.Router }, { token: i2.ConfirmationService }, { token: i2.MessageService }, { token: JwtHelperService }], target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: GlobalService }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: GlobalService, decorators: [{ type: Injectable }], ctorParameters: () => [{ type: i1.Router }, { type: i2.ConfirmationService }, { type: i2.MessageService }, { type: JwtHelperService }] }); class BaseService { _baseApiUrl; // base url (proje url) http; globalService; constructor(apiName) { this.http = inject(HttpClient); this.globalService = inject(GlobalService); this._baseApiUrl = this.globalService.appConfig.projectsApi[apiName ?? this.globalService.appConfig.apiName]; } get baseApiUrl() { return this._baseApiUrl; } //#region get,post,put,delete get(url, ...params) { //örnek: http://localhost:89/api/auth/login //örnek: http://turnaprojectapi.ua.gov.tr/api/auth/login let _url = url.includes("http") ? url : this._baseApiUrl + (url.indexOf('/') !== 0 ? '/' : '') + url; if (params.length > 0 && typeof params[0] === 'string') { //route parametrelerini almak için _url += `/${params.join('/')}`; } else if (params.length > 0 && typeof params[0] === 'object') { //query parametrelerini almak için return this.http.get(_url, { params: params[0] }); } //parametre almayacak şekilde ayarlandı. return this.http.get(_url); } post(url, model) { if (!url || !model) { return new Observable((subscriber) => { subscriber.next(new ResponseModel()); }); } let _url = url.includes("http") ? url : this._baseApiUrl + (url.indexOf('/') !== 0 ? '/' : '') + url; let _model = JSON.stringify(model); return this.http.post(_url, _model); } put(url, model) { if (!url || !model) { return new Observable((subscriber) => { subscriber.next(new ResponseModel()); }); } let _url = url.includes("http") ? url : this._baseApiUrl + (url.indexOf('/') !== 0 ? '/' : '') + url; let _model = JSON.stringify(model); return this.http.put(_url, _model); } delete(url, ...params) { let _url = url.includes("http") ? url : this._baseApiUrl + (url.indexOf('/') !== 0 ? '/' : '') + url; if (params.length > 0 && typeof params[0] === 'string') { //route parametrelerini almak için _url += `/${params.join('/')}`; } else if (params.length > 0 && typeof params[0] === 'object') { //query parametre yada model almak için return this.http.delete(_url, { params: params[0] }); } return this.http.delete(_url); } //#endregion list(httpParam = {}) { if (!httpParam.url) { return throwError(() => new Error(`CATNG BaseService => Url not found`)); } let _url = httpParam.url.includes("http") ? httpParam.url : this._baseApiUrl + (httpParam.url.indexOf('/') !== 0 ? '/' : '') + httpParam.url; if (httpParam.method != 'POST') { if (httpParam.page && httpParam.pageSize) { _url += `/${httpParam.page}/${httpParam.pageSize}`; } if (httpParam.sortBy && httpParam.sortBy.length > 0) { _url += `/${httpParam.sortBy.join('/')}`; } return this.http.get(_url); } if (!httpParam.filters || (httpParam.filters && httpParam.filters instanceof Filter)) { return this.http.post(_url, httpParam); } else { return this.http.post(_url, httpParam.filters); } } download(url, ...params) { let _url = url.includes("http") ? url : this._baseApiUrl + (url.indexOf('/') !== 0 ? '/' : '') + url; if (params.length > 0 && typeof params[0] === 'string') { //route parametrelerini almak için _url += `/${params.join('/')}`; } else if (params.length > 0 && typeof params[0] === 'object') { //query parametrelerini almak için return this.http.get(_url, { params: params[0] }); } return this.http.get(_url, { responseType: 'blob' }); } getRef(refName, fkId, fk2Id, fk3Id, fk4Id) { return this.http.post(this._baseApiUrl + "/ref/list", { refName: refName, fkId: fkId, fk2Id: fk2Id, fk3Id: fk3Id, fk4Id: fk4Id }); } getRefUrl(url, refName, fkId, fk2Id, fk3Id, fk4Id) { return this.http.post(url, { refName: refName, fkId: fkId, fk2Id: fk2Id, fk3Id: fk3Id, fk4Id: fk4Id }); } downloadWithModel(url, model) { if (!url || !model) { throw new Error('URL ve model zorunludur.'); } const _url = url.includes("http") ? url : this._baseApiUrl + (url.indexOf('/') !== 0 ? '/' : '') + url; return this.http.post(_url, model, { responseType: 'blob' }); } } class LoadingService { loadingSub = new BehaviorSubject(false); loadingMap = new Map(); isLoading$ = this.loadingSub.asObservable(); constructor() { } /** * Sets the loadingSub property value based on the following: * - If loading is true, add the provided url to the loadingMap with a true value, set loadingSub value to true * - If loading is false, remove the loadingMap entry and only when the map is empty will we set loadingSub to false * This pattern ensures if there are multiple requests awaiting completion, we don't set loading to false before * other requests have completed. At the moment, this function is only called from the @link{HttpRequestInterceptor} * @param loading {boolean} * @param url {string} */ setLoading(loading, url) { if (!url) { throw new Error('The request URL must be provided to the LoadingService.setLoading function'); } if (url.includes('.json')) return; setTimeout(() => { if (loading) { this.loadingMap.set(url, true); if (this.loadingSub.value === false) this.loadingSub.next(true); } else if (loading === false) { this.loadingMap.delete(url); if (this.loadingMap.size === 0) { this.loadingSub.next(false); } } }, 10); } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: LoadingService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: LoadingService }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: LoadingService, decorators: [{ type: Injectable }], ctorParameters: () => [] }); class DynamicFormPageService extends BaseService { constructor() { super(); } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: DynamicFormPageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: DynamicFormPageService }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: DynamicFormPageService, decorators: [{ type: Injectable }], ctorParameters: () => [] }); class BaseComponent { primaryKeyName = "id"; // bu alanı formlarda id dışında primary key kullanmak için override edebilirsiniz. id; page = 1; pageRowsCount = 50; totalRecords = 0; sortField = []; blocked = false; success; msgs = []; // translate service _translateService; globalService; datepipe; constructor() { this.globalService = inject(GlobalService); this._translateService = inject(TranslateService); this.datepipe = inject(DatePipe); } get inputTypeEnum() { return InputTypeEnum; } get fileShowTypeEnum() { return FileShowTypeEnum; } getRandomInt(max) { return Math.random() * max; } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: BaseComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.1.5", type: BaseComponent, isStandalone: true, selector: "ng-component", host: { attributes: { "Id": Math.random().toString() } }, ngImport: i0, template: ``, isInline: true }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: BaseComponent, decorators: [{ type: Component, args: [{ standalone: true, imports: [], template: ``, host: { 'Id': Math.random().toString() }, }] }], ctorParameters: () => [] }); class FilterPageSortComponent extends BaseComponent { rows = 15; filterDelay = 1000; rowsPerPageOptions = [25, 50, 100]; currentPageReportTemplate = "{first} - {last} / {totalRecords}"; static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: FilterPageSortComponent, deps: null, target: i0.ɵɵFactoryTarget.Component }); static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.1.5", type: FilterPageSortComponent, isStandalone: true, selector: "ng-component", host: { attributes: { "Id": Math.random().toString() } }, usesInheritance: true, ngImport: i0, template: ``, isInline: true }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: FilterPageSortComponent, decorators: [{ type: Component, args: [{ standalone: true, template: ``, host: { 'Id': Math.random().toString() }, }] }] }); class BaseListComponent extends FilterPageSortComponent { list = []; data; formVisible = false; rowMenuItemList = []; actionMenuItems = []; listOptions; resp = new EventEmitter(); /** * */ constructor() { super(); this.listOptions = {}; } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: BaseListComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.1.5", type: BaseListComponent, isStandalone: true, selector: "lib-base", outputs: { resp: "resp" }, host: { attributes: { "Id": Math.random().toString() } }, usesInheritance: true, ngImport: i0, template: ``, isInline: true }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.5", ngImport: i0, type: BaseListComponent, decorators: [{ type: Component, args: [{ standalone: true, selector: 'lib-base', template: ``, host: { 'Id': Math.random().toString() }, }] }], ctorParameters: () => [], propDecorators: { resp: [{ type: Output }] } }); class CatFileComponent extends BaseListComponent { fileOptions; uploadButtonText; uploadCompleted = new EventEmitter(); onCompleted = new EventEmitter(); canFileUpload; fileUploaded; readonly = false; get isFileUpload() { return this.canFileUpload ?? this.fileOptions?.canFileUpload ?? false; } token; baseurl; //fileUrl: string; date; showModal = false; preview = false; files = []; fileTur; fileTurList; isPDF; PDFdosyayolu; pdfHeight = "450px"; fileUrl = ''; columns; fileCss = {}; datePipe; fu; mimeClass = [ { mime: 'image', class: 'fas fa-file-image' }, { mime: 'audio', class: 'fas fa-file-audio' }, { mime: 'video', class: 'fas fa-file-video' }, { mime: 'application/pdf', class: 'fas fa-file-pdf' }, { mime: 'application/msword', class: 'fas fa-file-word' }, { mime: 'application/vnd.ms-word', class: 'fas fa-file-word' }, { mime: 'application/vnd.oasis.opendocument.text', class: 'fas fa-file-word' }, { mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml', class: 'fas fa-file-word' }, { mime: 'application/vnd.ms-excel', class: 'fas fa-file-excel' }, { mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml', class: 'fas fa-file-excel' }, { mime: 'application/vnd.oasis.opendocument.spreadsheet', class: 'fas fa-file-excel' }, { mime: 'application/vnd.ms-powerpoint', class: 'fas fa-file-powerpoint' }, { mime: 'application/vnd.openxmlformats-officedocument.presentationml', class: 'fas fa-file-powerpoint' }, { mime: 'application/vnd.oasis.opendocument.presentation', class: 'fas fa-file-powerpoint' }, { mime: 'text/plain', class: 'fas fa-file-text' }, { mime: 'text/html', class: 'fas fa-file-code' }, { mime: 'application/json', class: 'fas fa-file-code' }, { mime: 'application/gzip', class: 'fas fa-file-archive' }, { mime: 'application/zip', class: 'fas fa-file-archive' }, ]; appConfig; constructor() { super(); this.appConfig = inject(AppConfig); this.datePipe = inject(DatePipe); this.date = this.datePipe.transform(new Date(), 'dd.MM.yyyy h:mm:ss a'); } ngOnInit() { this.date = new Date(); this.token = this.globalService.getTokenLocal(); this.baseurl = this.appConfig.API_URL + '/api'; this.columns = [ { field: 'ad', header: 'label.ad' }, { field: 'zaman', header: 'label.zaman' }, { field: 'boyut', header: 'label.boyut' }, { field: 'tur', header: 'label.tur' } ]; //this.isFileYuklu = //(this.fileYukle?.GuidId && this.fileYukle?.GuidId != '00000000-0000-0000-0000-000000000000') ? true : false; if (this.fileOptions && !this.fileOptions.belge?.dosyaYol) this.fileOptions.url = "/belge/get"; if (this.fileOptions && !this.fileOptions.uploadUrl) this.fileOptions.uploadUrl = "/belge/upload"; if (this.fileOptions) this.setFileUrl(); // alttaki satır hata fırlatmasın diye kapatıldı. // Resim Gözükmüyor Diye Kapatıldı. // if (this.fileUrl == null || this.fileUrl == undefined || this.fileUrl == '') // this.fileUrl = this.appConfig.API_URL + '/' + (this.fileOptions?.url ?? "/file/get"); if (this.fileOptions?.showType == this.fileShowTypeEnum.show) { this.setPreview(); } this.setFileCss(); //this.load(); } setFileUrl() { this.date = this.datepipe.transform(this.date, 'dd.MM.yyyy HH:mm:ss'); } load() { if (this.fileOptions?.belge?.id) { } } onUpload(event) { this.date = this.datePipe.transform(new Date(), 'dd.MM.yyyy h:mm:ss a'); // this.blocked = false; // AppUtil.loading = false; // this.appService.showMessage(MessageStatusType.success, "File başarıyla yüklendi.", "File Yükleme"); // this.isFileYuklu = true; // this.fileYukle.Mime = event.originalEvent.body.Item?.Mime; // this.fileYukle.GuidId = event.originalEvent.body.Item?.GuidId; // this.yuklemeTamam.emit(event.originalEvent.body); // this.onComplated.emit(event.originalEvent.body) // this.date = new Date(); // this.showModal = false; // if (event.originalEvent.body.Item instanceof SoruDto) { // this.fileYukle.GuidId = event.originalEvent.body.Item?.BasvuruCevap[0]?.Cevap ?? this.appService.newGuid(); // } else { // this.fileYukle.GuidId = event.originalEvent.body.Item?.GuidId ?? event.originalEvent.body.Item?.Id ?? null; // } // AppUtil.fileDate = this.datepipe.transform(this.date, 'dd.MM.yyyy hh:mm:ss') as string; } onError(event) { // let hataMesaj = "File yüklenemedi!"; // this.appService.onErrorMessage(event.error, hataMesaj, "File Yükleme") this.load(); } indir(event) { // this.appService.post('file/indir', { id: event, kid: this.erisim.Id }).subscribe(); } sil(row) { // this.appService.confirm(row.ad + '(' + row.tur + ')', 'Silmek istediğinizden emin misiniz?', () => { // this.appService.post('file/sil', { id: row.id, kid: this.erisim.Id }).subscribe(() => { // this.load(); // }); // }); } onBeforeUpload(event) { if (this.fileOptions?.belge) { event.formData.append('id', this.fileOptions?.belge.id?.toString()); event.formData.append('belgeTurId', this.fileOptions?.belge.belgeTurId?.toString()); event.formData.append('refEntityId', this.fileOptions?.belge.refEntityId?.toString()); event.formData.append('entityId', this.fileOptions?.belge.entityId?.toString()); event.formData.append('ad', this.fileOptions?.belge.ad); event.formData.append('boyut', event.files[0].size.toString()); event.formData.append('mime', event.files[0].type); } // if (!this.fileYukle.BasvuruGuidId) { // event.formData.append('GuidId', this.fileYukle.GuidId ?? this.appService.newGuid()); // event.formData.append('EntityId', this.fileYukle.EntityId); // event.formData.append('FileTurId', this.fileYukle.FileTurId); // event.formData.append('RefEntityId', this.fileYukle.RefEntityId); // event.formData.append('Ad', this.fileYukle.FileAd); // } else { // event.formData.append('Id', !this.fileYukle.GuidId || this.fileYukle.GuidId == this.appService.guidEmpty() ? this.appService.newGuid() : this.fileYukle.GuidId); // event.formData.append('BasvuruGuidId', this.fileYukle.BasvuruGuidId); // event.formData.append('SoruId', this.fileYukle.SoruId); // event.formData.append('Ad', this.fileYukle.Soru?.FileAd ?? this.fileYukle.Soru?.Ad ?? 'Başvuru File'); // } } onSelect(event, fu) { this.files = fu.files; } onRemove(event, fu) { this.files = fu.files; } mimeTypeToClass(mimeType) { let clazz = this.mimeClass.find(f => mimeType.startsWith(f.mime)); if (clazz) { return clazz.class; } return 'fas fa-file'; } getFileDate() { return this.date; } setFileCss() { if (this.fileOptions?.border) { this.fileCss['border'] = this.fileOptions?.border; this.fileCss['padding'] = '3px'; } if (this.fileOptions?.radius) this.fileCss['border-radius'] = this.fileOptions?.radius; if (this.fileOptions?.width) this.fileCss['width'] = ((this.fileOptions?.width) instanceof Number ? this.fileOptions?.width + 'px' : this.fileOptions?.width); if (this.fileOptions?.height) this.fileCss['height'] = ((this.fileOptions?.height) instanceof Number ? this.fileOptions?.height + 'px' : this.fileOptions?.heig