diff --git a/src/applications/Mixcore/wwwroot/mix-app/js/app-portal.min.js b/src/applications/Mixcore/wwwroot/mix-app/js/app-portal.min.js index 63cd5cd99..9141250f1 100644 --- a/src/applications/Mixcore/wwwroot/mix-app/js/app-portal.min.js +++ b/src/applications/Mixcore/wwwroot/mix-app/js/app-portal.min.js @@ -1,4 +1,4 @@ -/* Thu Oct 12 2023 19:21:38 GMT+0700 (Indochina Time) */"use strict"; +/* Fri Oct 13 2023 14:38:30 GMT+0700 (Indochina Time) */"use strict"; var app = angular.module("MixPortal", [ "angularCroppie", "ui.bootstrap", @@ -415,8 +415,7 @@ app.controller("MixApplicationController", [ $scope.$apply(); } }; - $scope.receiveMessage = function (resp) { - let msg = JSON.parse(resp); + $scope.receiveMessage = function (msg) { switch (msg.action) { case "Downloading": var index = $scope.data.items.findIndex( @@ -424,11 +423,12 @@ app.controller("MixApplicationController", [ ); var progress = Math.round(msg.message); if (index >= 0) { - $scope.progress = progress; - if (progress == 100) { - $scope.installStatus = "Installing"; + if (progress < 100) { + $scope.progress = progress; + $scope.$apply(); + } else { + $location.url("/admin/mix-application/list"); } - $scope.$apply(); } break; @@ -464,7 +464,7 @@ app.controller("MixApplicationController", [ } }; $scope.select = function (theme) { - $scope.viewmodel.packateFilePath = theme.additionalData.source; + $scope.viewmodel.packateFilePath = theme.additionalData.builtSourceCode; $scope.current = theme; // TODO: verify user - theme to enable install $scope.current.canInstall = true; @@ -605,136 +605,6 @@ app.factory("ConfigurationService", [ }, ]); -"use strict"; -app.controller("CultureController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$routeParams", - "CultureService", - "CommonService", - "ApiService", - function ( - $scope, - $rootScope, - ngAppSettings, - $routeParams, - service, - commonService, - apiService - ) { - $scope.selected = null; - BaseCtrl.call( - this, - $scope, - $rootScope, - $routeParams, - ngAppSettings, - service - ); - $scope.loadCultures = async function () { - var getCultures = await commonService.loadJsonData("cultures"); - $scope.cultures = getCultures.data.items; - $scope.$apply(); - }; - $scope.saveSuccessCallback = function () { - apiService - .initAllSettings() - .then(() => (window.location.href = "/admin/language/list")); - }; - $scope.removeCallback = function () { - apiService - .initAllSettings() - .then(() => (window.location.href = "/admin/language/list")); - }; - $scope.changeData = function (selected) { - if (selected) { - $scope.viewmodel.specificulture = selected.specificulture; - $scope.viewmodel.displayName = selected.fullName; - $scope.viewmodel.icon = selected.icon; - } - }; - }, -]); - -"use strict"; -app.factory("CultureService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("culture"); - var _updateInfos = async function (pages) { - var req = { - method: "POST", - url: this.prefixUrl + "/update-infos", - data: JSON.stringify(pages), - }; - return await apiService.sendRequest(req); - }; - - var _syncTemplates = async function (id) { - var apiUrl = "/culture/"; - var url = apiUrl + "sync/" + id; - var req = { - method: "GET", - url: url, - }; - return await apiService.sendRequest(req); - }; - - serviceFactory.syncTemplates = _syncTemplates; - serviceFactory.updateInfos = _updateInfos; - return serviceFactory; - }, -]); - -"use strict"; -app.controller("DomainController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$location", - "$routeParams", - "DomainRestService", - function ( - $scope, - $rootScope, - ngAppSettings, - $location, - $routeParams, - service - ) { - BaseRestCtrl.call( - this, - $scope, - $rootScope, - $location, - $routeParams, - ngAppSettings, - service - ); - $scope.request.columns = [ - "id", - "displayName", - "host", - "createdDateTime", - "createdBy", - ]; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - }, -]); - -"use strict"; -app.factory("DomainRestService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-domain"); - return serviceFactory; - }, -]); - "use strict"; app.controller("AuditLogController", [ "$scope", @@ -871,6 +741,89 @@ app.factory("AuditLogRestService", [ }, ]); +"use strict"; +app.controller("CultureController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$routeParams", + "CultureService", + "CommonService", + "ApiService", + function ( + $scope, + $rootScope, + ngAppSettings, + $routeParams, + service, + commonService, + apiService + ) { + $scope.selected = null; + BaseCtrl.call( + this, + $scope, + $rootScope, + $routeParams, + ngAppSettings, + service + ); + $scope.loadCultures = async function () { + var getCultures = await commonService.loadJsonData("cultures"); + $scope.cultures = getCultures.data.items; + $scope.$apply(); + }; + $scope.saveSuccessCallback = function () { + apiService + .initAllSettings() + .then(() => (window.location.href = "/admin/language/list")); + }; + $scope.removeCallback = function () { + apiService + .initAllSettings() + .then(() => (window.location.href = "/admin/language/list")); + }; + $scope.changeData = function (selected) { + if (selected) { + $scope.viewmodel.specificulture = selected.specificulture; + $scope.viewmodel.displayName = selected.fullName; + $scope.viewmodel.icon = selected.icon; + } + }; + }, +]); + +"use strict"; +app.factory("CultureService", [ + "BaseRestService", + function (baseService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("culture"); + var _updateInfos = async function (pages) { + var req = { + method: "POST", + url: this.prefixUrl + "/update-infos", + data: JSON.stringify(pages), + }; + return await apiService.sendRequest(req); + }; + + var _syncTemplates = async function (id) { + var apiUrl = "/culture/"; + var url = apiUrl + "sync/" + id; + var req = { + method: "GET", + url: url, + }; + return await apiService.sendRequest(req); + }; + + serviceFactory.syncTemplates = _syncTemplates; + serviceFactory.updateInfos = _updateInfos; + return serviceFactory; + }, +]); + "use strict"; app.controller("CustomerController", [ "$scope", @@ -1164,47 +1117,94 @@ app.factory("DashboardServices", [ ]); "use strict"; -app.controller("FileController", [ +app.controller("DomainController", [ "$scope", "$rootScope", "ngAppSettings", - "$routeParams", - "$timeout", "$location", - "AuthService", - "FileServices", + "$routeParams", + "DomainRestService", function ( $scope, $rootScope, ngAppSettings, - $routeParams, - $timeout, $location, - authService, - fileServices + $routeParams, + service ) { - $scope.request = { - pageSize: "10", - pageIndex: 0, - status: "Published", - orderBy: "CreatedDateTime", - direction: "Desc", - fromDate: null, - toDate: null, - keyword: "", - key: "", - }; - - $scope.activedFile = null; - $scope.relatedFiles = []; - $rootScope.isBusy = false; - $scope.data = { - pageIndex: 0, - pageSize: 1, - totalItems: 0, - }; - $scope.errors = []; - + BaseRestCtrl.call( + this, + $scope, + $rootScope, + $location, + $routeParams, + ngAppSettings, + service + ); + $scope.request.columns = [ + "id", + "displayName", + "host", + "createdDateTime", + "createdBy", + ]; + $scope.canDrag = + $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; + }, +]); + +"use strict"; +app.factory("DomainRestService", [ + "BaseRestService", + function (baseService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("mix-domain"); + return serviceFactory; + }, +]); + +"use strict"; +app.controller("FileController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$routeParams", + "$timeout", + "$location", + "AuthService", + "FileServices", + function ( + $scope, + $rootScope, + ngAppSettings, + $routeParams, + $timeout, + $location, + authService, + fileServices + ) { + $scope.request = { + pageSize: "10", + pageIndex: 0, + status: "Published", + orderBy: "CreatedDateTime", + direction: "Desc", + fromDate: null, + toDate: null, + keyword: "", + key: "", + }; + + $scope.activedFile = null; + $scope.relatedFiles = []; + $rootScope.isBusy = false; + $scope.data = { + pageIndex: 0, + pageSize: 1, + totalItems: 0, + }; + $scope.errors = []; + $scope.range = function (max) { var input = []; for (var i = 1; i <= max; i += 1) input.push(i); @@ -1404,270 +1404,110 @@ app.factory("FileServices", [ ]); "use strict"; -app.controller("LocalizeController", [ +app.controller("ImportFileController", [ "$scope", "$rootScope", - "ngAppSettings", - "$routeParams", - "$location", - "LocalizeService", - "ApiService", - "CommonService", + "ImportFileServices", + "TranslatorService", + "AppSettingsService", function ( $scope, $rootScope, - ngAppSettings, - $routeParams, - $location, service, - commonService + translatorService, + AppSettingsService ) { - BaseRestCtrl.call( - this, - $scope, - $rootScope, - $location, - $routeParams, - ngAppSettings, - service - ); - - $scope.getSingleSuccessCallback = function () { - $scope.cates = ngAppSettings.enums.configuration_cates; - $scope.appSettings = $rootScope.globalSettings; - $scope.request.category = $routeParams.category || ""; - if (!$scope.viewmodel.id) { - $scope.viewmodel.dataType = "Text"; - } - if (!$scope.viewmodel.category) { - $scope.viewmodel.category = "Site"; - } - }; - $scope.saveSuccessCallback = function () { - apiService.getAllSettings().then(function () { - // $location.url($scope.referrerUrl); + $scope.saveImportFile = async function () { + $rootScope.isBusy = true; + var form = document.getElementById("frm-import"); + var frm = new FormData(); + frm.append("assets", form["assets"].files[0]); + var response = await service.saveImportFile(frm); + if (response.success) { + $scope.viewmodel = response.data; $rootScope.isBusy = false; $scope.$apply(); - }); - }; - $scope.removeCallback = function () { - apiService.getAllSettings().then(function () { - $location.url($scope.referrerUrl); - }); - }; - - $scope.generateName = function () { - $scope.viewmodel.keyword = $rootScope.generateKeyword( - $scope.viewmodel.keyword, - "_", - true - ); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } }; }, ]); "use strict"; -app.factory("LocalizeService", [ - "BaseRestService", - "ApiService", - "CommonService", - function (baseService, apiService, commonService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("language"); - - var _uploadLanguage = async function (languageFile) { - //var container = $(this).parents('.model-language').first().find('.custom-file').first(); - if (languageFile.file !== undefined && languageFile.file !== null) { - // Create FormData object - var files = new FormData(); - - // Looping over all files and add it to FormData object - files.append(languageFile.file.name, languageFile.file); - - // Adding one more key to FormData object - files.append("fileFolder", languageFile.folder); - files.append("title", languageFile.title); - files.append("description", languageFile.description); +app.factory("ImportFileServices", [ + "$rootScope", + "BaseService", + function ($rootScope, baseService) { + //var serviceBase = 'http://ngauthenticationapi.azurewebsites.net/'; - var req = { - url: this.prefixUrl + "/upload", - type: "POST", - headers: {}, - contentType: false, // Not to set any content header - processData: false, // Not to process data - data: files, - }; + var serviceFactory = {}; - return await apiService.sendRequest(req); - } + var settings = $rootScope.globalSettings; + var serviceFactory = Object.create(baseService); + serviceFactory.init("portal", true); + var _saveImportFile = async function (frm) { + var apiUrl = this.prefixUrl + "/" + settings.lang + "/import"; + return await this.ajaxSubmitForm(frm, apiUrl); }; - serviceFactory.uploadLanguage = _uploadLanguage; + + serviceFactory.saveImportFile = _saveImportFile; return serviceFactory; }, ]); "use strict"; -app.controller("loginController", [ - "$rootScope", +app.controller("JsonDataController", [ "$scope", + "$rootScope", "ngAppSettings", + "$routeParams", + "$timeout", "$location", "AuthService", - "ngAppSettings", + "JsonDataService", function ( - $rootScope, $scope, + $rootScope, ngAppSettings, + $routeParams, + $timeout, $location, authService, - ngAuthSettings + service ) { - if ( - authService.authentication && - authService.authentication.isAuth && - authService.authentication.isAdmin - ) { - authService.referredUrl = $location.path(); - $location.path("/admin"); - } + $scope.request = { + pageSize: "10", + pageIndex: 0, + status: "Published", + orderBy: "CreatedDateTime", + direction: "Desc", + fromDate: null, + toDate: null, + keyword: "", + key: "", + }; - $scope.pageClass = "page-login"; + $scope.activedFile = null; + $scope.editorVisible = false; + $scope.data = null; + $scope.relatedFiles = []; + $rootScope.isBusy = false; - $scope.loginData = { - username: "", - password: "", - rememberme: true, - }; + $scope.errors = []; - $scope.message = ""; - $scope.$on("$viewContentLoaded", function () { - $rootScope.isBusy = false; - }); - $scope.login = async function () { - if (authService.referredUrl === "/init/login") { - authService.referredUrl = "/admin"; + $scope.loadPage = async function (folder) { + if (folder) { + $scope.request.key += $scope.request.key !== "" ? "/" : ""; + $scope.request.key += folder; } - $rootScope.isBusy = true; - var result = await authService.login($scope.loginData); - if (result.success) { - if ($routeParams.ReturnUrl) { - window.top.location = $routeParams.ReturnUrl; - } else if ( - document.referrer && - document.referrer.indexOf("init") === -1 - ) { - window.top.location = document.referrer; - } else { - window.top.location = "/"; - } - } - $rootScope.isBusy = false; - $scope.$apply(); - }; - - $scope.authExternalProvider = function (provider) { - var redirectUri = - location.protocol + "//" + location.host + "/authcomplete.html"; - - var externalProviderUrl = - ngAuthSettings.apiServiceBaseUri + - "api/Account/ExternalLogin?provider=" + - provider + - "&response_type=token&client_id=" + - ngAuthSettings.clientId + - "&redirect_uri=" + - redirectUri; - window.$windowScope = $scope; - - var oauthWindow = window.open( - externalProviderUrl, - "Authenticate Account", - "location=0,status=0,width=600,height=750" - ); - }; - - $scope.authCompletedCB = function (fragment) { - $scope.$apply(function () { - if (fragment.haslocalaccount === "False") { - authService.logOut(); - - authService.externalAuthData = { - provider: fragment.provider, - username: fragment.external_user_name, - externalAccessToken: fragment.external_access_token, - }; - - $location.path("/associate"); - } else { - //Obtain access token and redirect to orders - var externalData = { - provider: fragment.provider, - externalAccessToken: fragment.external_access_token, - }; - authService.obtainAccessToken(externalData).then( - function (response) { - $location.path("/orders"); - }, - function (err) { - $scope.message = err.error_description; - } - ); - } - }); - }; - }, -]); - -"use strict"; -app.controller("JsonDataController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$routeParams", - "$timeout", - "$location", - "AuthService", - "JsonDataService", - function ( - $scope, - $rootScope, - ngAppSettings, - $routeParams, - $timeout, - $location, - authService, - service - ) { - $scope.request = { - pageSize: "10", - pageIndex: 0, - status: "Published", - orderBy: "CreatedDateTime", - direction: "Desc", - fromDate: null, - toDate: null, - keyword: "", - key: "", - }; - - $scope.activedFile = null; - $scope.editorVisible = false; - $scope.data = null; - $scope.relatedFiles = []; - $rootScope.isBusy = false; - - $scope.errors = []; - - $scope.loadPage = async function (folder) { - if (folder) { - $scope.request.key += $scope.request.key !== "" ? "/" : ""; - $scope.request.key += folder; - } - $location.url( - "/admin/json-data/list?folder=" + encodeURIComponent($scope.request.key) - ); - }; - $scope.init = async function () { + $location.url( + "/admin/json-data/list?folder=" + encodeURIComponent($scope.request.key) + ); + }; + $scope.init = async function () { $rootScope.isBusy = true; $scope.filename = $routeParams.filename; $scope.folder = $routeParams.folder; @@ -1833,26 +1673,23 @@ app.factory("JsonDataService", [ ]); "use strict"; -app.controller("MixDatabaseController", [ +app.controller("LocalizeController", [ "$scope", "$rootScope", - "$location", "ngAppSettings", "$routeParams", - "RestMixDatabaseDataPortalService", - "RestMixDatabaseColumnPortalService", - "RestMixDatabasePortalService", - "RestMixDatabaseContextService", + "$location", + "LocalizeService", + "ApiService", + "CommonService", function ( $scope, $rootScope, - $location, ngAppSettings, $routeParams, - databaseDataService, - databaseColumnService, - databaseService, - dbContextService + $location, + service, + commonService ) { BaseRestCtrl.call( this, @@ -1861,184 +1698,205 @@ app.controller("MixDatabaseController", [ $location, $routeParams, ngAppSettings, - databaseService + service ); - $scope.defaultAttr = null; - $scope.actions = ["Delete"]; - $scope.viewmodelType = "mix-database"; - // $scope.request.selects = 'id,title,name,createdDateTime'; - $scope.orders = [ - { title: "Id", value: "Id" }, - { title: "Name", value: "Name" }, - { title: "Created Date", value: "CreatedDateTime" }, - ]; - $scope.request.orderBy = "CreatedDateTime"; - $scope.request.columns = "id,displayName,systemName,type,createdDatetime"; - $scope.request.searchColumns = "displayName,systemName"; - $scope.saveDatabase = function () { - $scope.save($scope.viewmodel); - }; - $scope.getSingleSuccessCallback = async function () { - $scope.viewmodel.mixDatabaseContextId = $routeParams.mixDatabaseContextId; - if ($scope.viewmodel.mixDatabaseContextId) { - var resp = await dbContextService.getSingle([ - $scope.viewmodel.mixDatabaseContextId, - ]); - if (resp.success) { - $scope.dbContext = resp.data; - } - } - if (!$scope.defaultAttr) { - var getDefaultAttr = await databaseColumnService.getDefault(); - if (getDefaultAttr.success) { - $scope.defaultAttr = getDefaultAttr.data; - $scope.defaultAttr.options = []; - } - $scope.$apply(); - } - }; - $scope.migrate = async function () { - if ($scope.viewmodel.id) { - $rootScope.isBusy = true; - var result = await databaseService.migrate($scope.viewmodel); - if (result.success) { - $rootScope.showMessage( - "Please restart pool to apply new db schema", - "warning" - ); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(["Cannot migrate database"]); - $rootScope.isBusy = false; - $scope.$apply(); - } + $scope.getSingleSuccessCallback = function () { + $scope.cates = ngAppSettings.enums.configuration_cates; + $scope.appSettings = $rootScope.globalSettings; + $scope.request.category = $routeParams.category || ""; + if (!$scope.viewmodel.id) { + $scope.viewmodel.dataType = "Text"; } - }; - $scope.backup = async function () { - if ($scope.viewmodel.id) { - $rootScope.isBusy = true; - var result = await databaseService.backup($scope.viewmodel); - if (result.success) { - $rootScope.showMessage( - `Backup ${$scope.viewmodel.systemName} is queued`, - "success" - ); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(["Cannot backup database"]); - $rootScope.isBusy = false; - $scope.$apply(); - } + if (!$scope.viewmodel.category) { + $scope.viewmodel.category = "Site"; } }; - $scope.restore = async function () { - if ($scope.viewmodel.id) { - $rootScope.isBusy = true; - var result = await databaseService.restore($scope.viewmodel); - if (result.success) { - $rootScope.showMessage( - `Restore ${$scope.viewmodel.systemName} is queued`, - "success" - ); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(["Cannot restore database"]); - $rootScope.isBusy = false; - $scope.$apply(); - } - } + $scope.saveSuccessCallback = function () { + apiService.getAllSettings().then(function () { + // $location.url($scope.referrerUrl); + $rootScope.isBusy = false; + $scope.$apply(); + }); }; - $scope.updateSchema = async function () { - if ($scope.viewmodel.id) { - $rootScope.isBusy = true; - var result = await databaseService.updateSchema($scope.viewmodel); - if (result.success) { - $rootScope.showMessage( - "Please restart pool to apply new db schema", - "warning" - ); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(["Cannot update database"]); - $rootScope.isBusy = false; - $scope.$apply(); - } - } + $scope.removeCallback = function () { + apiService.getAllSettings().then(function () { + $location.url($scope.referrerUrl); + }); }; - $scope.back = function () { - window.history.back(); - }; + $scope.generateName = function () { + $scope.viewmodel.keyword = $rootScope.generateKeyword( + $scope.viewmodel.keyword, + "_", + true + ); + }; }, ]); "use strict"; -app.controller("ImportFileController", [ - "$scope", +app.factory("LocalizeService", [ + "BaseRestService", + "ApiService", + "CommonService", + function (baseService, apiService, commonService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("language"); + + var _uploadLanguage = async function (languageFile) { + //var container = $(this).parents('.model-language').first().find('.custom-file').first(); + if (languageFile.file !== undefined && languageFile.file !== null) { + // Create FormData object + var files = new FormData(); + + // Looping over all files and add it to FormData object + files.append(languageFile.file.name, languageFile.file); + + // Adding one more key to FormData object + files.append("fileFolder", languageFile.folder); + files.append("title", languageFile.title); + files.append("description", languageFile.description); + + var req = { + url: this.prefixUrl + "/upload", + type: "POST", + headers: {}, + contentType: false, // Not to set any content header + processData: false, // Not to process data + data: files, + }; + + return await apiService.sendRequest(req); + } + }; + serviceFactory.uploadLanguage = _uploadLanguage; + return serviceFactory; + }, +]); + +"use strict"; +app.controller("loginController", [ "$rootScope", - "ImportFileServices", - "TranslatorService", - "AppSettingsService", + "$scope", + "ngAppSettings", + "$location", + "AuthService", + "ngAppSettings", function ( - $scope, $rootScope, - service, - translatorService, - AppSettingsService + $scope, + ngAppSettings, + $location, + authService, + ngAuthSettings ) { - $scope.saveImportFile = async function () { + if ( + authService.authentication && + authService.authentication.isAuth && + authService.authentication.isAdmin + ) { + authService.referredUrl = $location.path(); + $location.path("/admin"); + } + + $scope.pageClass = "page-login"; + + $scope.loginData = { + username: "", + password: "", + rememberme: true, + }; + + $scope.message = ""; + $scope.$on("$viewContentLoaded", function () { + $rootScope.isBusy = false; + }); + $scope.login = async function () { + if (authService.referredUrl === "/init/login") { + authService.referredUrl = "/admin"; + } $rootScope.isBusy = true; - var form = document.getElementById("frm-import"); - var frm = new FormData(); - frm.append("assets", form["assets"].files[0]); - var response = await service.saveImportFile(frm); - if (response.success) { - $scope.viewmodel = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); + var result = await authService.login($scope.loginData); + if (result.success) { + if ($routeParams.ReturnUrl) { + window.top.location = $routeParams.ReturnUrl; + } else if ( + document.referrer && + document.referrer.indexOf("init") === -1 + ) { + window.top.location = document.referrer; + } else { + window.top.location = "/"; + } } + $rootScope.isBusy = false; + $scope.$apply(); }; - }, -]); -"use strict"; -app.factory("ImportFileServices", [ - "$rootScope", - "BaseService", - function ($rootScope, baseService) { - //var serviceBase = 'http://ngauthenticationapi.azurewebsites.net/'; + $scope.authExternalProvider = function (provider) { + var redirectUri = + location.protocol + "//" + location.host + "/authcomplete.html"; - var serviceFactory = {}; + var externalProviderUrl = + ngAuthSettings.apiServiceBaseUri + + "api/Account/ExternalLogin?provider=" + + provider + + "&response_type=token&client_id=" + + ngAuthSettings.clientId + + "&redirect_uri=" + + redirectUri; + window.$windowScope = $scope; - var settings = $rootScope.globalSettings; - var serviceFactory = Object.create(baseService); - serviceFactory.init("portal", true); - var _saveImportFile = async function (frm) { - var apiUrl = this.prefixUrl + "/" + settings.lang + "/import"; - return await this.ajaxSubmitForm(frm, apiUrl); + var oauthWindow = window.open( + externalProviderUrl, + "Authenticate Account", + "location=0,status=0,width=600,height=750" + ); }; - serviceFactory.saveImportFile = _saveImportFile; - return serviceFactory; + $scope.authCompletedCB = function (fragment) { + $scope.$apply(function () { + if (fragment.haslocalaccount === "False") { + authService.logOut(); + + authService.externalAuthData = { + provider: fragment.provider, + username: fragment.external_user_name, + externalAccessToken: fragment.external_access_token, + }; + + $location.path("/associate"); + } else { + //Obtain access token and redirect to orders + var externalData = { + provider: fragment.provider, + externalAccessToken: fragment.external_access_token, + }; + authService.obtainAccessToken(externalData).then( + function (response) { + $location.path("/orders"); + }, + function (err) { + $scope.message = err.error_description; + } + ); + } + }); + }; }, ]); "use strict"; -app.controller("MixDatabaseContextController", [ +app.controller("MixDatabaseController", [ "$scope", "$rootScope", "$location", "ngAppSettings", "$routeParams", + "RestMixDatabaseDataPortalService", + "RestMixDatabaseColumnPortalService", + "RestMixDatabasePortalService", "RestMixDatabaseContextService", function ( $scope, @@ -2046,7 +1904,10 @@ app.controller("MixDatabaseContextController", [ $location, ngAppSettings, $routeParams, - mixdbContextService + databaseDataService, + databaseColumnService, + databaseService, + dbContextService ) { BaseRestCtrl.call( this, @@ -2055,15 +1916,15 @@ app.controller("MixDatabaseContextController", [ $location, $routeParams, ngAppSettings, - mixdbContextService + databaseService ); $scope.defaultAttr = null; - $scope.databaseProvider = ["MySQL", "PostgreSQL", "SQLITE", "SQLSERVER"]; $scope.actions = ["Delete"]; + $scope.viewmodelType = "mix-database"; // $scope.request.selects = 'id,title,name,createdDateTime'; $scope.orders = [ { title: "Id", value: "Id" }, - { title: "Name", value: "DisplayName" }, + { title: "Name", value: "Name" }, { title: "Created Date", value: "CreatedDateTime" }, ]; $scope.request.orderBy = "CreatedDateTime"; @@ -2072,53 +1933,126 @@ app.controller("MixDatabaseContextController", [ $scope.saveDatabase = function () { $scope.save($scope.viewmodel); }; - $scope.generateName = function () { - $scope.viewmodel.systemName = $rootScope.generateKeyword( - $scope.viewmodel.displayName, - "_", - true, - true - ); - }; - $scope.getSingleSuccessCallback = async function () {}; - }, -]); - -"use strict"; -app.factory("RestMixDatabaseContextService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("mixdb-context"); - var _getByName = async function (name) { - var url = `${this.prefixUrl}/get-by-name/${name}`; - var req = { - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); + $scope.getSingleSuccessCallback = async function () { + $scope.viewmodel.mixDatabaseContextId = $routeParams.mixDatabaseContextId; + if ($scope.viewmodel.mixDatabaseContextId) { + var resp = await dbContextService.getSingle([ + $scope.viewmodel.mixDatabaseContextId, + ]); + if (resp.success) { + $scope.dbContext = resp.data; + } + } + if (!$scope.defaultAttr) { + var getDefaultAttr = await databaseColumnService.getDefault(); + if (getDefaultAttr.success) { + $scope.defaultAttr = getDefaultAttr.data; + $scope.defaultAttr.options = []; + } + $scope.$apply(); + } }; - serviceFactory.getByName = _getByName; - return serviceFactory; - }, -]); - -"use strict"; -app.controller("MixDatabaseDataController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$routeParams", - "$location", - "MixDbService", - function ( - $scope, + $scope.migrate = async function () { + if ($scope.viewmodel.id) { + $rootScope.isBusy = true; + var result = await databaseService.migrate($scope.viewmodel); + if (result.success) { + $rootScope.showMessage( + "Please restart pool to apply new db schema", + "warning" + ); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(["Cannot migrate database"]); + $rootScope.isBusy = false; + $scope.$apply(); + } + } + }; + $scope.backup = async function () { + if ($scope.viewmodel.id) { + $rootScope.isBusy = true; + var result = await databaseService.backup($scope.viewmodel); + if (result.success) { + $rootScope.showMessage( + `Backup ${$scope.viewmodel.systemName} is queued`, + "success" + ); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(["Cannot backup database"]); + $rootScope.isBusy = false; + $scope.$apply(); + } + } + }; + $scope.restore = async function () { + if ($scope.viewmodel.id) { + $rootScope.isBusy = true; + var result = await databaseService.restore($scope.viewmodel); + if (result.success) { + $rootScope.showMessage( + `Restore ${$scope.viewmodel.systemName} is queued`, + "success" + ); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(["Cannot restore database"]); + $rootScope.isBusy = false; + $scope.$apply(); + } + } + }; + $scope.updateSchema = async function () { + if ($scope.viewmodel.id) { + $rootScope.isBusy = true; + var result = await databaseService.updateSchema($scope.viewmodel); + if (result.success) { + $rootScope.showMessage( + "Please restart pool to apply new db schema", + "warning" + ); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(["Cannot update database"]); + $rootScope.isBusy = false; + $scope.$apply(); + } + } + }; + + $scope.back = function () { + window.history.back(); + }; + }, +]); + +"use strict"; +app.controller("ModuleController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$location", + "$routeParams", + "ModuleRestService", + "SharedModuleDataService", + "RestMixDatabaseDataPortalService", + "RestMixDatabaseColumnPortalService", + function ( + $scope, $rootScope, ngAppSettings, - $routeParams, $location, - mixDbService + $routeParams, + moduleServices, + moduleDataService, + dataService, + columnService ) { BaseRestCtrl.call( this, @@ -2127,187 +2061,84 @@ app.controller("MixDatabaseDataController", [ $location, $routeParams, ngAppSettings, - mixDbService + moduleServices, + "product" ); - $scope.queries = {}; - $scope.data = null; - $scope.exportAll = true; - $scope.mixConfigurations = $rootScope.globalSettings; - $scope.filterType = "contain"; - $scope.defaultId = "default"; - $scope.importFile = { - file: null, - fullPath: "", - folder: "import", - title: "", - description: "", - }; - $scope.initRouteParams = () => { - $scope.requestKey = `request${$rootScope.generateKeyword( - $location.$$path, - "_" - )}_${$routeParams.mixDatabaseId}`; - $scope.request = $rootScope.getRequest($scope.requestKey); - if ($routeParams.mixDatabaseId) { - $scope.request.mixDatabaseId = $routeParams.mixDatabaseId; - } - if ($routeParams.queryFields) { - if (Array.isArray($routeParams.queryFields)) { - angular.forEach($routeParams.queryFields, (e) => { - let val = e.split(":"); - $scope.queries[val[0]] = val[1]; - }); - } else { - let val = $routeParams.queryFields.split(":"); - $scope.queries[val[0]] = val[1]; - } - $scope.request.mixDatabaseId = $routeParams.mixDatabaseId; - } - $scope.request.mixDatabaseName = $routeParams.mixDatabaseName; - $scope.request.filterType = $routeParams.filterType || "contain"; - $scope.request.compareType = $routeParams.compareType || "or"; + $scope.request.culture = $rootScope.globalSettings.defaultCulture; + $scope.viewmodelType = "module"; + $scope.contentUrl = ""; + $scope.getSingleSuccessCallback = function () { + $scope.loadAdditionalData(); - $scope.mixDatabaseId = $routeParams.mixDatabaseId; - $scope.mixDatabaseName = $routeParams.mixDatabaseName; - $scope.mixDatabaseTitle = $routeParams.mixDatabaseTitle; - $scope.guidParentId = $routeParams.guidParentId; - $scope.parentType = $routeParams.parentType; - $scope.request.mixDatabaseName = $routeParams.mixDatabaseName; - $scope.request.isGroup = $routeParams.isGroup || false; - $scope.dataUrl = `/admin/mix-database-data/list?mixDatabaseId=${$scope.mixDatabaseId}&mixDatabaseName=${$scope.mixDatabaseName}&mixDatabaseTitle=${$scope.mixDatabaseTitle}`; - if ($routeParams.backUrl) { - $scope.backUrl = decodeURIComponent($routeParams.backUrl); + if ($scope.viewmodel.id > 0) { + // module => list post or list product + if ($scope.viewmodel.type.localeCompare("ListPost") == 0) { + $scope.contentUrl = "/admin/module-post/list/" + $scope.viewmodel.id; + } else if ($scope.viewmodel.type.localeCompare("Data") == 0) { + $scope.contentUrl = "/admin/module-data/list/" + $scope.viewmodel.id; + } } - if ($routeParams.dataContentId != $scope.defaultId) { - $scope.dataContentId = $routeParams.dataContentId; + if ($scope.viewmodel.sysCategories) { + angular.forEach($scope.viewmodel.sysCategories, function (e) { + e.attributeData.obj.isActived = true; + }); } - if ($scope.parentId && $scope.parentType) { - $scope.refDataModel = { - parentId: $scope.parentId, - parentType: $scope.parentType, - }; + if ($scope.viewmodel.sysTags) { + angular.forEach($scope.viewmodel.sysTags, function (e) { + e.attributeData.obj.isActived = true; + }); } - }; - $scope.init = async function () { - $scope.initRouteParams(); - mixDbService.initDbName($scope.request.mixDatabaseName); - }; - $scope.saveSuccess = function (data) { - if ($scope.backUrl) { - $location.url($scope.backUrl); - } else { - $location.url( - `/admin/mix-database-data/details?dataContentId=${data}&mixDatabaseTitle=${ - $scope.mixDatabaseTitle - }&backUrl=${encodeURIComponent($scope.dataUrl)}` + + if ($routeParams.template) { + $scope.viewmodel.view = $rootScope.findObjectByKey( + $scope.viewmodel.templates, + "fileName", + $routeParams.template ); } }; - $scope.selectData = function () { - if ($scope.selectedList.data.length) { - $scope.viewmodel = $scope.selectedList.data[0]; - } - }; - - $scope.preview = function (item) { - item.editUrl = "/admin/post/details/" + item.id; - $rootScope.preview("post", item, item.title, "modal-lg"); - }; - $scope.edit = function (data) { - $rootScope.goToPath( - `/admin/mix-database-data/details?dataContentId=${data.id}&mixDatabaseName=${$scope.mixDatabaseName}&mixDatabaseTitle=${$scope.mixDatabaseTitle}` - ); + $scope.getListByType = async function (pageIndex) { + $scope.request.query = "?type=" + $scope.type; + await $scope.getList(pageIndex); }; - $scope.remove = function (data) { - $rootScope.showConfirm( - $scope, - "removeConfirmed", - [data.id], - null, - "Remove", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); + $scope.defaultAttr = { + name: "", + options: [], + priority: 0, + dataType: 7, + isGroupBy: false, + isSelect: false, + isDisplay: true, + width: 3, }; + $scope.type = "-1"; - $scope.removeConfirmed = async function (dataContentId) { + $scope.localizeSettings = $rootScope.globalSettings; + $scope.viewmodel = null; + $scope.editDataUrl = ""; + + $scope.loadModuleDatas = async function () { $rootScope.isBusy = true; - var result = await mixDbService.delete([dataContentId]); - if (result.success) { - if ($scope.removeCallback) { - $rootScope.executeFunctionByName( - "removeCallback", - $scope.removeCallbackArgs, - $scope - ); - } - $scope.getList(); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.import = async function () { - if ($scope.validateDataFile()) { - $rootScope.isBusy = true; - var form = document.getElementById("form-portal"); - var result = await mixDbService.import( - form["import-data-inp"].files[0] - ); - if (result.success) { - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.getList(0); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - } - }; - $scope.validateDataFile = function () { - if (!$scope.importFile.file) { - $rootScope.showMessage("Please choose data file", "danger"); - return false; - } else { - return true; - } - }; - $scope.sendMail = function (data) { - var email = ""; - angular.forEach(data.values, function (e) { - if (e.mixDatabaseColumnName == "email") { - email = e.stringValue; - } - }); - $rootScope.showConfirm( - $scope, - "sendMailConfirmed", - [data], - null, - "Send mail", - "Are you sure to send mail to " + email - ); - }; - $scope.sendMailConfirmed = async function (data) { - $rootScope.isBusy = true; - $rootScope.isBusy = true; - var result = await service.sendMail([data.id]); - if (result.success) { - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.saveOthers = async function () { - var response = await service.saveList($scope.others); + var id = $routeParams.id; + $scope.dataColumns = []; + var response = await moduleServices.getSingle([id]); if (response.success) { - $scope.getList(); + $scope.viewmodel = response.data; + $scope.editDataUrl = + "/admin/module-data/details/" + $scope.viewmodel.id; + $scope.loadMoreModuleDatas(); + angular.forEach($scope.viewmodel.columns, function (e, i) { + if (e.isDisplay) { + $scope.dataColumns.push({ + title: e.title, + name: e.name, + filter: true, + type: 0, // string - ngAppSettings.dataTypes[0] + }); + } + }); + $rootScope.isBusy = false; $scope.$apply(); } else { $rootScope.showErrors(response.errors); @@ -2315,123 +2146,51 @@ app.controller("MixDatabaseDataController", [ $scope.$apply(); } }; - $scope.selectImportFile = function (files) { - if (files !== undefined && files !== null && files.length > 0) { - const file = files[0]; - $scope.importFile.folder = "imports"; - $scope.importFile.title = $scope.mixDatabaseName; - $scope.importFile.description = $scope.mixDatabaseName + "'s data"; - $scope.importFile.file = file; - // if (ctrl.auto=='true') { - // ctrl.uploadFile(file); - // } - // else { - // ctrl.getBase64(file); - // } - } - }; - $scope.getList = async function (pageIndex) { + $scope.loadMoreModuleDatas = async function (pageIndex) { + $scope.request.query = "&moduleContentId=" + $scope.viewmodel.id; if (pageIndex !== undefined) { $scope.request.pageIndex = pageIndex; } if ($scope.request.fromDate !== null) { - var df = new Date($scope.request.fromDate); - $scope.request.fromDate = df.toISOString(); + var d = new Date($scope.request.fromDate); + $scope.request.fromDate = d.toISOString(); } if ($scope.request.toDate !== null) { - var dt = new Date($scope.request.toDate); - $scope.request.toDate = dt.toISOString(); + var d = new Date($scope.request.toDate); + $scope.request.toDate = d.toISOString(); } - $scope.request.queries = []; - - Object.keys($scope.queries).forEach((e) => { - if ($scope.queries[e]) { - $scope.request.queries.push({ - fieldName: e, - value: $scope.queries[e], - }); - } - }); $rootScope.isBusy = true; - var resp = await mixDbService.filter($scope.request); + var resp = await moduleDataService.getModuleDatas($scope.request); if (resp && resp.success) { - $scope.data = resp.data; - $.each($scope.data.items, function (i, data) { - $.each($scope.activeddata, function (i, e) { - if (e.dataContentId === data.id) { - data.isHidden = true; - } - }); - }); - if ($scope.getListSuccessCallback) { - $scope.getListSuccessCallback(); - } - $("html, body").animate( - { - scrollTop: "0px", - }, - 500 - ); - if (!resp.data || !resp.data.items.length) { - $scope.queries = {}; - } + $scope.viewmodel.data = resp.data; $rootScope.isBusy = false; $scope.$apply(); } else { if (resp) { $rootScope.showErrors(resp.errors); } - if ($scope.getListFailCallback) { - $scope.getListFailCallback(); - } - $scope.queries = {}; $rootScope.isBusy = false; $scope.$apply(); } }; - $scope.export = async function (pageIndex, exportAll) { + $scope.exportModuleData = async function (pageIndex) { + $scope.request.query = "&moduleContentId=" + $scope.viewmodel.id; if (pageIndex !== undefined) { $scope.request.pageIndex = pageIndex; } if ($scope.request.fromDate !== null) { - var df = new Date($scope.request.fromDate); - $scope.request.fromDate = df.toISOString(); + var d = new Date($scope.request.fromDate); + $scope.request.fromDate = d.toISOString(); } if ($scope.request.toDate !== null) { - var dt = new Date($scope.request.toDate); - $scope.request.toDate = dt.toISOString(); - } - var query = {}; - if ($routeParams.mixDatabaseId) { - $scope.request.mixDatabaseId = $routeParams.mixDatabaseId; - } - $scope.request.mixDatabaseName = $routeParams.mixDatabaseName; - $scope.request.filterType = $routeParams.filterType || "contain"; - $scope.request.queries = []; - - Object.keys($scope.queries).forEach((e) => { - if ($scope.queries[e]) { - $scope.request.queries.push({ - fieldName: e, - value: $scope.queries[e], - }); - } - }); - var request = angular.copy($scope.request); - $scope.exportAll = $scope.exportAll; - if (exportAll) { - request.pageSize = 10000; - request.pageIndex = 0; + var d = new Date($scope.request.toDate); + $scope.request.toDate = d.toISOString(); } $rootScope.isBusy = true; - var resp = await mixDbService.export(request); + var resp = await moduleDataService.exportModuleData($scope.request); if (resp && resp.success) { - if (resp.data) { - window.top.location = resp.data.webPath; - } else { - $rootScope.showMessage("Nothing to export"); - } + window.top.location = resp.data; $rootScope.isBusy = false; $scope.$apply(); } else { @@ -2443,261 +2202,79 @@ app.controller("MixDatabaseDataController", [ } }; - $scope.migrate = async function () { - if ($routeParams.mixDatabaseId) { - $rootScope.isBusy = true; - var result = await service.migrate($routeParams.mixDatabaseId); - $scope.handleResult(result); + $scope.removeData = function (id) { + if ($scope.viewmodel) { + $rootScope.showConfirm( + $scope, + "removeDataConfirmed", + [id], + null, + "Remove Data", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + } + }; + + $scope.removeDataConfirmed = async function (id) { + $rootScope.isBusy = true; + var result = await moduleDataService.removeModuleData(id); + if (result.success) { + $scope.loadModuleDatas(); + } else { + $rootScope.showMessage("failed"); $rootScope.isBusy = false; $scope.$apply(); } }; - }, -]); - -"use strict"; -app.controller("ModuleController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$location", - "$routeParams", - "ModuleRestService", - "SharedModuleDataService", - "RestMixDatabaseDataPortalService", - "RestMixDatabaseColumnPortalService", - function ( - $scope, - $rootScope, - ngAppSettings, - $location, - $routeParams, - moduleServices, - moduleDataService, - dataService, - columnService - ) { - BaseRestCtrl.call( - this, - $scope, - $rootScope, - $location, - $routeParams, - ngAppSettings, - moduleServices, - "product" - ); - $scope.request.culture = $rootScope.globalSettings.defaultCulture; - $scope.viewmodelType = "module"; - $scope.contentUrl = ""; - $scope.getSingleSuccessCallback = function () { - $scope.loadAdditionalData(); - - if ($scope.viewmodel.id > 0) { - // module => list post or list product - if ($scope.viewmodel.type.localeCompare("ListPost") == 0) { - $scope.contentUrl = "/admin/module-post/list/" + $scope.viewmodel.id; - } else if ($scope.viewmodel.type.localeCompare("Data") == 0) { - $scope.contentUrl = "/admin/module-data/list/" + $scope.viewmodel.id; - } - } - if ($scope.viewmodel.sysCategories) { - angular.forEach($scope.viewmodel.sysCategories, function (e) { - e.attributeData.obj.isActived = true; - }); - } - - if ($scope.viewmodel.sysTags) { - angular.forEach($scope.viewmodel.sysTags, function (e) { - e.attributeData.obj.isActived = true; - }); - } - - if ($routeParams.template) { - $scope.viewmodel.view = $rootScope.findObjectByKey( - $scope.viewmodel.templates, - "fileName", - $routeParams.template - ); - } - }; - $scope.getListByType = async function (pageIndex) { - $scope.request.query = "?type=" + $scope.type; - await $scope.getList(pageIndex); - }; - $scope.defaultAttr = { - name: "", - options: [], - priority: 0, - dataType: 7, - isGroupBy: false, - isSelect: false, - isDisplay: true, - width: 3, - }; - $scope.type = "-1"; - - $scope.localizeSettings = $rootScope.globalSettings; - $scope.viewmodel = null; - $scope.editDataUrl = ""; - - $scope.loadModuleDatas = async function () { - $rootScope.isBusy = true; - var id = $routeParams.id; - $scope.dataColumns = []; - var response = await moduleServices.getSingle([id]); - if (response.success) { - $scope.viewmodel = response.data; - $scope.editDataUrl = - "/admin/module-data/details/" + $scope.viewmodel.id; - $scope.loadMoreModuleDatas(); - angular.forEach($scope.viewmodel.columns, function (e, i) { - if (e.isDisplay) { - $scope.dataColumns.push({ - title: e.title, - name: e.name, - filter: true, - type: 0, // string - ngAppSettings.dataTypes[0] - }); - } - }); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - - $scope.loadMoreModuleDatas = async function (pageIndex) { - $scope.request.query = "&moduleContentId=" + $scope.viewmodel.id; - if (pageIndex !== undefined) { - $scope.request.pageIndex = pageIndex; - } - if ($scope.request.fromDate !== null) { - var d = new Date($scope.request.fromDate); - $scope.request.fromDate = d.toISOString(); - } - if ($scope.request.toDate !== null) { - var d = new Date($scope.request.toDate); - $scope.request.toDate = d.toISOString(); - } - $rootScope.isBusy = true; - var resp = await moduleDataService.getModuleDatas($scope.request); - if (resp && resp.success) { - $scope.viewmodel.data = resp.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.exportModuleData = async function (pageIndex) { - $scope.request.query = "&moduleContentId=" + $scope.viewmodel.id; - if (pageIndex !== undefined) { - $scope.request.pageIndex = pageIndex; - } - if ($scope.request.fromDate !== null) { - var d = new Date($scope.request.fromDate); - $scope.request.fromDate = d.toISOString(); - } - if ($scope.request.toDate !== null) { - var d = new Date($scope.request.toDate); - $scope.request.toDate = d.toISOString(); - } - $rootScope.isBusy = true; - var resp = await moduleDataService.exportModuleData($scope.request); - if (resp && resp.success) { - window.top.location = resp.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - - $scope.removeData = function (id) { - if ($scope.viewmodel) { - $rootScope.showConfirm( - $scope, - "removeDataConfirmed", - [id], - null, - "Remove Data", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); - } - }; - - $scope.removeDataConfirmed = async function (id) { - $rootScope.isBusy = true; - var result = await moduleDataService.removeModuleData(id); - if (result.success) { - $scope.loadModuleDatas(); - } else { - $rootScope.showMessage("failed"); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.updateModuleDataField = async function (item, propertyName) { - var result = await moduleDataService.saveFields( - item.id, - propertyName, - item[propertyName] - ); - if (result.success) { - $scope.loadModuleDatas(); - } else { - $rootScope.showMessage("failed"); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.updateDataInfos = async function (items) { - $rootScope.isBusy = true; - var resp = await moduleDataService.updateInfos(items); - if (resp && resp.success) { - $scope.activedPage = resp.data; - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.saveSuccessCallback = async function () { - let result = await $scope.saveAdditionalData(); - if (result) { - $rootScope.showMessage("Saved", "success"); - } - }; - $scope.saveAdditionalData = async () => { - if ($scope.additionalData) { - $scope.additionalData.isClone = $scope.viewmodel.isClone; - $scope.additionalData.cultures = $scope.viewmodel.cultures; - $scope.additionalData.intParentId = $scope.viewmodel.id; - $scope.additionalData.parentType = "Module"; - let result = await dataService.save($scope.additionalData); - if (!result.success) { - $rootScope.showErrors(result.errors); - } - return result.success; - } - }; + $scope.updateModuleDataField = async function (item, propertyName) { + var result = await moduleDataService.saveFields( + item.id, + propertyName, + item[propertyName] + ); + if (result.success) { + $scope.loadModuleDatas(); + } else { + $rootScope.showMessage("failed"); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.updateDataInfos = async function (items) { + $rootScope.isBusy = true; + var resp = await moduleDataService.updateInfos(items); + if (resp && resp.success) { + $scope.activedPage = resp.data; + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.saveSuccessCallback = async function () { + let result = await $scope.saveAdditionalData(); + if (result) { + $rootScope.showMessage("Saved", "success"); + } + }; + $scope.saveAdditionalData = async () => { + if ($scope.additionalData) { + $scope.additionalData.isClone = $scope.viewmodel.isClone; + $scope.additionalData.cultures = $scope.viewmodel.cultures; + $scope.additionalData.intParentId = $scope.viewmodel.id; + $scope.additionalData.parentType = "Module"; + let result = await dataService.save($scope.additionalData); + if (!result.success) { + $rootScope.showErrors(result.errors); + } + return result.success; + } + }; $scope.saveColumns = async function () { let result = await columnService.saveMany($scope.additionalData.columns); @@ -2767,22 +2344,20 @@ app.factory("ModuleRestService", [ ]); "use strict"; -app.controller("ModuleDataController", [ +app.controller("MixDatabaseContextController", [ "$scope", "$rootScope", + "$location", "ngAppSettings", "$routeParams", - "$location", - "ModuleDataRestService", - "ModuleRestService", + "RestMixDatabaseContextService", function ( $scope, $rootScope, + $location, ngAppSettings, $routeParams, - $location, - service, - moduleService + mixdbContextService ) { BaseRestCtrl.call( this, @@ -2791,369 +2366,184 @@ app.controller("ModuleDataController", [ $location, $routeParams, ngAppSettings, - service + mixdbContextService ); - $scope.request.culture = $rootScope.globalSettings.defaultCulture; - // $scope.request.orderBy = "Priority"; - // $scope.request.direction = "Asc"; - $scope.cates = ["Site", "System"]; - $scope.others = []; - $scope.mixConfigurations = $rootScope.globalSettings; - $scope.moduleContentId = $routeParams.moduleContentId; - $scope.backUrl = `/admin/module-data/list/${$scope.moduleContentId}`; - $scope.module = null; - $scope.columns = []; - $scope.editDataUrl = "/admin/module-data/details/" + $scope.moduleContentId; - $scope.init = async function () { - $scope.id = $routeParams.id; - }; - $scope.initList = async function () { - $scope.id = $routeParams.id; - if (!$scope.module) { - var getModule = await moduleService.getSingle([$scope.moduleContentId]); - if (getModule.success) { - $scope.module = getModule.data; - $scope.columns = $scope.module.columns; - $scope.$apply(); - } - } - }; - $scope.getList = async function () { - $rootScope.isBusy = true; - $scope.request.moduleContentId = $scope.moduleContentId; - var response = await service.getList($scope.request); - if (response.success) { - $scope.data = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - - $scope.export = async function () { - $rootScope.isBusy = true; - $scope.request.moduleContentId = $scope.moduleContentId; - var response = await service.export($scope.request); - if (response.success) { - window.top.location = response.data.webPath; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - - $scope.getSingle = async function () { - $rootScope.isBusy = true; - var resp = await service.getSingle($routeParams.id, "portal"); - if (resp && resp.success) { - $scope.activedModuleData = resp.data; - $rootScope.initEditor(); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } + $scope.defaultAttr = null; + $scope.databaseProvider = ["MySQL", "PostgreSQL", "SQLITE", "SQLSERVER"]; + $scope.actions = ["Delete"]; + // $scope.request.selects = 'id,title,name,createdDateTime'; + $scope.orders = [ + { title: "Id", value: "Id" }, + { title: "Name", value: "DisplayName" }, + { title: "Created Date", value: "CreatedDateTime" }, + ]; + $scope.request.orderBy = "CreatedDateTime"; + $scope.request.columns = "id,displayName,systemName,type,createdDatetime"; + $scope.request.searchColumns = "displayName,systemName"; + $scope.saveDatabase = function () { + $scope.save($scope.viewmodel); }; - $scope.remove = function (dataContentId) { - $rootScope.showConfirm( - $scope, - "removeConfirmed", - [dataContentId], - null, - "Remove", - "Deleted data will not able to recover, are you sure you want to delete this item?" + $scope.generateName = function () { + $scope.viewmodel.systemName = $rootScope.generateKeyword( + $scope.viewmodel.displayName, + "_", + true, + true ); }; - - $scope.removeConfirmed = async function (dataContentId) { - $rootScope.isBusy = true; - var result = await service.delete([dataContentId]); - if (result.success) { - if ($scope.removeCallback) { - $rootScope.executeFunctionByName( - "removeCallback", - $scope.removeCallbackArgs, - $scope - ); - } - $scope.getList(); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - - $scope.removeCallback = function () {}; - - $scope.saveOthers = async function () { - var response = await service.saveList($scope.others); - if (response.success) { - $scope.getList(); - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; + $scope.getSingleSuccessCallback = async function () {}; }, ]); "use strict"; -app.factory("ModuleDataRestService", [ +app.factory("RestMixDatabaseContextService", [ "BaseRestService", - "ApiService", - "CommonService", - function (baseService, apiService, commonService) { + function (baseService) { var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-module-data"); - // Define more service methods here + serviceFactory.init("mixdb-context"); - var _initForm = async function (moduleContentId) { - var url = `${this.prefixUrl}/init-form/${moduleContentId}`; + var _getByName = async function (name) { + var url = `${this.prefixUrl}/get-by-name/${name}`; var req = { method: "GET", url: url, }; - return await apiService.sendRequest(req); + return await this.getRestApiResult(req); }; - serviceFactory.initForm = _initForm; + serviceFactory.getByName = _getByName; return serviceFactory; }, ]); "use strict"; -app.controller("ModuleGalleryController", [ +app.controller("MixDatabaseDataController", [ "$scope", "$rootScope", "ngAppSettings", "$routeParams", "$location", - "ModuleGalleryService", - "ApiService", - "CommonService", + "MixDbService", function ( $scope, $rootScope, ngAppSettings, $routeParams, $location, - service, - apiService, - commonService + mixDbService ) { - BaseCtrl.call( + BaseRestCtrl.call( this, $scope, $rootScope, + $location, $routeParams, ngAppSettings, - service + mixDbService ); - $scope.cates = ["Site", "System"]; - $scope.others = []; + $scope.queries = {}; + $scope.data = null; + $scope.exportAll = true; $scope.mixConfigurations = $rootScope.globalSettings; - $scope.moduleContentId = $routeParams.id; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - $scope.translate = $rootScope.translate; - $scope.moduleContentId = $routeParams.id; - $scope.getList = async function () { - $rootScope.isBusy = true; - var id = $routeParams.id; - $scope.moduleContentId = $routeParams.id; - $scope.request.query = "&moduleContentId=" + id; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || - $scope.request.direction !== "0"; - var response = await service.getList($scope.request); - if (response.success) { - $scope.data = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.remove = function (moduleContentId, postId) { - $rootScope.showConfirm( - $scope, - "removeConfirmed", - [moduleContentId, postId], - null, - "Remove", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); + $scope.filterType = "contain"; + $scope.defaultId = "default"; + $scope.importFile = { + file: null, + fullPath: "", + folder: "import", + title: "", + description: "", }; - - $scope.removeConfirmed = async function (moduleContentId, postId) { - $rootScope.isBusy = true; - var result = await service.delete(moduleContentId, postId); - if (result.success) { - if ($scope.removeCallback) { - $rootScope.executeFunctionByName( - "removeCallback", - $scope.removeCallbackArgs, - $scope - ); + $scope.initRouteParams = () => { + $scope.requestKey = `request${$rootScope.generateKeyword( + $location.$$path, + "_" + )}_${$routeParams.mixDatabaseId}`; + $scope.request = $rootScope.getRequest($scope.requestKey); + if ($routeParams.mixDatabaseId) { + $scope.request.mixDatabaseId = $routeParams.mixDatabaseId; + } + if ($routeParams.queryFields) { + if (Array.isArray($routeParams.queryFields)) { + angular.forEach($routeParams.queryFields, (e) => { + let val = e.split(":"); + $scope.queries[val[0]] = val[1]; + }); + } else { + let val = $routeParams.queryFields.split(":"); + $scope.queries[val[0]] = val[1]; } - $scope.getList(); - } else { - $rootScope.showMessage("failed"); - $rootScope.isBusy = false; - $scope.$apply(); + $scope.request.mixDatabaseId = $routeParams.mixDatabaseId; } - }; - - $scope.removeCallback = function () {}; + $scope.request.mixDatabaseName = $routeParams.mixDatabaseName; + $scope.request.filterType = $routeParams.filterType || "contain"; + $scope.request.compareType = $routeParams.compareType || "or"; - $scope.saveOthers = async function () { - var response = await service.saveList($scope.others); - if (response.success) { - $scope.getList(); - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.updateInfos = async function (index) { - $scope.data.items.splice(index, 1); - $rootScope.isBusy = true; - var startIndex = $scope.data.items[0].priority - 1; - for (var i = 0; i < $scope.data.items.length; i++) { - $scope.data.items[i].priority = startIndex + i + 1; + $scope.mixDatabaseId = $routeParams.mixDatabaseId; + $scope.mixDatabaseName = $routeParams.mixDatabaseName; + $scope.mixDatabaseTitle = $routeParams.mixDatabaseTitle; + $scope.guidParentId = $routeParams.guidParentId; + $scope.parentType = $routeParams.parentType; + $scope.request.mixDatabaseName = $routeParams.mixDatabaseName; + $scope.request.isGroup = $routeParams.isGroup || false; + $scope.dataUrl = `/admin/mix-database-data/list?mixDatabaseId=${$scope.mixDatabaseId}&mixDatabaseName=${$scope.mixDatabaseName}&mixDatabaseTitle=${$scope.mixDatabaseTitle}`; + if ($routeParams.backUrl) { + $scope.backUrl = decodeURIComponent($routeParams.backUrl); } - var resp = await service.updateInfos($scope.data.items); - if (resp && resp.success) { - $scope.activedPage = resp.data; - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); + if ($routeParams.dataContentId != $scope.defaultId) { + $scope.dataContentId = $routeParams.dataContentId; } - }; - }, -]); -"use strict"; -app.factory("ModuleGalleryService", [ - "$rootScope", - "ApiService", - "CommonService", - "BaseService", - function ($rootScope, apiService, commonService, baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("module-post"); - var _delete = async function (moduleContentId, postId) { - var url = this.prefixUrl + "/delete/" + moduleContentId + "/" + postId; - var req = { - method: "GET", - url: url, - }; - return await apiService.sendRequest(req); + if ($scope.parentId && $scope.parentType) { + $scope.refDataModel = { + parentId: $scope.parentId, + parentType: $scope.parentType, + }; + } }; - var _updateInfos = async function (modules) { - var req = { - method: "POST", - url: this.prefixUrl + "/update-infos", - data: JSON.stringify(modules), - }; - return await apiService.sendRequest(req); + $scope.init = async function () { + $scope.initRouteParams(); + mixDbService.initDbName($scope.request.mixDatabaseName); }; - serviceFactory.delete = _delete; - serviceFactory.updateInfos = _updateInfos; - return serviceFactory; - }, -]); - -"use strict"; -app.controller("PageGalleryController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$routeParams", - "$location", - "PageGalleryService", - "PostRestService", - "ApiService", - "CommonService", - function ( - $scope, - $rootScope, - ngAppSettings, - $routeParams, - $location, - service, - postService, - apiService, - commonService - ) { - BaseCtrl.call( - this, - $scope, - $rootScope, - $routeParams, - ngAppSettings, - service - ); - $scope.cates = ["Site", "System"]; - $scope.others = []; - $scope.mixConfigurations = $rootScope.globalSettings; - $scope.pageId = $routeParams.id; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - $scope.getList = async function () { - $rootScope.isBusy = true; - var id = $routeParams.id; - $scope.request.query = "&page_id=" + id; - var response = await service.getList($scope.request); - $scope.canDrag = - $scope.request.orderBy !== "Priority" || - $scope.request.direction !== "0"; - if (response.success) { - $scope.data = response.data; - $rootScope.isBusy = false; - $scope.$apply(); + $scope.saveSuccess = function (data) { + if ($scope.backUrl) { + $location.url($scope.backUrl); } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); + $location.url( + `/admin/mix-database-data/details?dataContentId=${data}&mixDatabaseTitle=${ + $scope.mixDatabaseTitle + }&backUrl=${encodeURIComponent($scope.dataUrl)}` + ); } }; - $scope.remove = function (pageId, postId) { + $scope.selectData = function () { + if ($scope.selectedList.data.length) { + $scope.viewmodel = $scope.selectedList.data[0]; + } + }; + + $scope.preview = function (item) { + item.editUrl = "/admin/post/details/" + item.id; + $rootScope.preview("post", item, item.title, "modal-lg"); + }; + $scope.edit = function (data) { + $rootScope.goToPath( + `/admin/mix-database-data/details?dataContentId=${data.id}&mixDatabaseName=${$scope.mixDatabaseName}&mixDatabaseTitle=${$scope.mixDatabaseTitle}` + ); + }; + $scope.remove = function (data) { $rootScope.showConfirm( $scope, "removeConfirmed", - [pageId, postId], + [data.id], null, "Remove", "Deleted data will not able to recover, are you sure you want to delete this item?" ); }; - $scope.removeConfirmed = async function (pageId, postId) { + $scope.removeConfirmed = async function (dataContentId) { $rootScope.isBusy = true; - var result = await service.delete(pageId, postId); + var result = await mixDbService.delete([dataContentId]); if (result.success) { if ($scope.removeCallback) { $rootScope.executeFunctionByName( @@ -3164,153 +2554,265 @@ app.controller("PageGalleryController", [ } $scope.getList(); } else { - $rootScope.showMessage("failed"); + $rootScope.showErrors(result.errors); $rootScope.isBusy = false; $scope.$apply(); } }; - - $scope.saveOthers = async function () { - var response = await service.saveList($scope.others); - if (response.success) { - $scope.getList(); - $scope.$apply(); + $scope.import = async function () { + if ($scope.validateDataFile()) { + $rootScope.isBusy = true; + var form = document.getElementById("form-portal"); + var result = await mixDbService.import( + form["import-data-inp"].files[0] + ); + if (result.success) { + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.getList(0); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + } + }; + $scope.validateDataFile = function () { + if (!$scope.importFile.file) { + $rootScope.showMessage("Please choose data file", "danger"); + return false; } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); + return true; } }; - $scope.updateInfos = async function (index) { - $scope.data.items.splice(index, 1); + $scope.sendMail = function (data) { + var email = ""; + angular.forEach(data.values, function (e) { + if (e.mixDatabaseColumnName == "email") { + email = e.stringValue; + } + }); + $rootScope.showConfirm( + $scope, + "sendMailConfirmed", + [data], + null, + "Send mail", + "Are you sure to send mail to " + email + ); + }; + $scope.sendMailConfirmed = async function (data) { $rootScope.isBusy = true; - var startIndex = $scope.data.items[0].priority - 1; - for (var i = 0; i < $scope.data.items.length; i++) { - $scope.data.items[i].priority = startIndex + i + 1; - } - var resp = await service.updateInfos($scope.data.items); - if (resp && resp.success) { - $scope.activedPage = resp.data; + $rootScope.isBusy = true; + var result = await service.sendMail([data.id]); + if (result.success) { $rootScope.showMessage("success", "success"); $rootScope.isBusy = false; $scope.$apply(); } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } + $rootScope.showErrors(result.errors); $rootScope.isBusy = false; $scope.$apply(); } }; - }, -]); - -"use strict"; -app.factory("PageGalleryService", [ - "$rootScope", - "ApiService", - "CommonService", - "BaseService", - function ($rootScope, apiService, commonService, baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("page-post"); - var _delete = async function (pageId, postId) { - var url = this.prefixUrl + "/delete/" + pageId + "/" + postId; - var req = { - method: "GET", - url: url, - }; - return await apiService.sendRequest(req); + $scope.saveOthers = async function () { + var response = await service.saveList($scope.others); + if (response.success) { + $scope.getList(); + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } }; - var _updateInfos = async function (pages) { - var req = { - method: "POST", - url: this.prefixUrl + "/update-infos", - data: JSON.stringify(pages), - }; - return await apiService.sendRequest(req); + $scope.selectImportFile = function (files) { + if (files !== undefined && files !== null && files.length > 0) { + const file = files[0]; + $scope.importFile.folder = "imports"; + $scope.importFile.title = $scope.mixDatabaseName; + $scope.importFile.description = $scope.mixDatabaseName + "'s data"; + $scope.importFile.file = file; + + // if (ctrl.auto=='true') { + // ctrl.uploadFile(file); + // } + // else { + // ctrl.getBase64(file); + // } + } + }; + $scope.getList = async function (pageIndex) { + if (pageIndex !== undefined) { + $scope.request.pageIndex = pageIndex; + } + if ($scope.request.fromDate !== null) { + var df = new Date($scope.request.fromDate); + $scope.request.fromDate = df.toISOString(); + } + if ($scope.request.toDate !== null) { + var dt = new Date($scope.request.toDate); + $scope.request.toDate = dt.toISOString(); + } + $scope.request.queries = []; + + Object.keys($scope.queries).forEach((e) => { + if ($scope.queries[e]) { + $scope.request.queries.push({ + fieldName: e, + value: $scope.queries[e], + }); + } + }); + $rootScope.isBusy = true; + var resp = await mixDbService.filter($scope.request); + if (resp && resp.success) { + $scope.data = resp.data; + $.each($scope.data.items, function (i, data) { + $.each($scope.activeddata, function (i, e) { + if (e.dataContentId === data.id) { + data.isHidden = true; + } + }); + }); + if ($scope.getListSuccessCallback) { + $scope.getListSuccessCallback(); + } + $("html, body").animate( + { + scrollTop: "0px", + }, + 500 + ); + if (!resp.data || !resp.data.items.length) { + $scope.queries = {}; + } + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + if ($scope.getListFailCallback) { + $scope.getListFailCallback(); + } + $scope.queries = {}; + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.export = async function (pageIndex, exportAll) { + if (pageIndex !== undefined) { + $scope.request.pageIndex = pageIndex; + } + if ($scope.request.fromDate !== null) { + var df = new Date($scope.request.fromDate); + $scope.request.fromDate = df.toISOString(); + } + if ($scope.request.toDate !== null) { + var dt = new Date($scope.request.toDate); + $scope.request.toDate = dt.toISOString(); + } + var query = {}; + if ($routeParams.mixDatabaseId) { + $scope.request.mixDatabaseId = $routeParams.mixDatabaseId; + } + $scope.request.mixDatabaseName = $routeParams.mixDatabaseName; + $scope.request.filterType = $routeParams.filterType || "contain"; + $scope.request.queries = []; + + Object.keys($scope.queries).forEach((e) => { + if ($scope.queries[e]) { + $scope.request.queries.push({ + fieldName: e, + value: $scope.queries[e], + }); + } + }); + var request = angular.copy($scope.request); + $scope.exportAll = $scope.exportAll; + if (exportAll) { + request.pageSize = 10000; + request.pageIndex = 0; + } + $rootScope.isBusy = true; + var resp = await mixDbService.export(request); + if (resp && resp.success) { + if (resp.data) { + window.top.location = resp.data.webPath; + } else { + $rootScope.showMessage("Nothing to export"); + } + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + + $scope.migrate = async function () { + if ($routeParams.mixDatabaseId) { + $rootScope.isBusy = true; + var result = await service.migrate($routeParams.mixDatabaseId); + $scope.handleResult(result); + $rootScope.isBusy = false; + $scope.$apply(); + } }; - serviceFactory.delete = _delete; - serviceFactory.updateInfos = _updateInfos; - return serviceFactory; }, ]); "use strict"; -app.controller("PageController", [ +app.controller("ModuleGalleryController", [ "$scope", "$rootScope", "ngAppSettings", - "$location", "$routeParams", - "PageRestService", - "PagePostRestService", - "UrlAliasService", - "RestMixDatabasePortalService", - "RestMixDatabaseDataPortalService", - "RestMixDatabaseColumnPortalService", - "MixDbService", + "$location", + "ModuleGalleryService", + "ApiService", + "CommonService", function ( $scope, $rootScope, ngAppSettings, - $location, $routeParams, + $location, service, - pagePostRestService, - urlAliasService, - databaseService, - dataService, - columnService, - mixDbService + apiService, + commonService ) { - BaseRestCtrl.call( + BaseCtrl.call( this, $scope, $rootScope, - $location, $routeParams, ngAppSettings, service ); - $scope.request.culture = $rootScope.globalSettings.defaultCulture; - var pageModuleService = $rootScope.getRestService("mix-page-module"); - $scope.viewmodelType = "page"; - $scope.request.query = "level=0"; - $scope.pageType = {}; - $scope.pageTypes = $rootScope.globalSettings.pageTypes; - $scope.selectedCategories = []; - $scope.selectedTags = []; - $scope.selectedModules = []; - $scope.pageData = { - posts: [], - products: [], - data: [], - }; - $scope.request.columns = [ - "id", - "title", - "createdDateTime", - "type", - "image", - ]; - $scope.additionalData = null; - $scope.temp = null; - $scope.postRequest = angular.copy(ngAppSettings.request); - $scope.additionalDatabaseRequest = angular.copy(ngAppSettings.request); - ($scope.additionalDatabaseRequest.searchColumns = "Type"), - ($scope.additionalDatabaseRequest.searchMethod = "Equal"), - ($scope.additionalDatabaseRequest.keyword = "AdditionalData"); + $scope.cates = ["Site", "System"]; + $scope.others = []; + $scope.mixConfigurations = $rootScope.globalSettings; + $scope.moduleContentId = $routeParams.id; $scope.canDrag = $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - $scope.loadPosts = async function () { + $scope.translate = $rootScope.translate; + $scope.moduleContentId = $routeParams.id; + $scope.getList = async function () { $rootScope.isBusy = true; var id = $routeParams.id; - $scope.postRequest.query += "&page_id=" + id; - var response = await pagePostRestService.getList($scope.postRequest); - + $scope.moduleContentId = $routeParams.id; + $scope.request.query = "&moduleContentId=" + id; + $scope.canDrag = + $scope.request.orderBy !== "Priority" || + $scope.request.direction !== "0"; + var response = await service.getList($scope.request); if (response.success) { - $scope.pageData.posts = response.data; + $scope.data = response.data; $rootScope.isBusy = false; $scope.$apply(); } else { @@ -3319,64 +2821,48 @@ app.controller("PageController", [ $scope.$apply(); } }; - $scope.$watch("additionalDatabase", function (newValue, oldValue) { - console.log(newValue, oldValue); - }); - $scope.init = async function () { - await $scope.loadAdditionalDatabases(); - await $scope.getSingle(); - }; - $scope.initList = function () { - $scope.additionalDatabases.splice(0, 0, { - systemName: "", - displayName: "All", - id: 0, - }); - $scope.getList(); - }; - $scope.getSingleSuccessCallback = function () { - mixDbService.initDbName($scope.viewmodel.mixDatabaseName); - $scope.additionalDatabase = $rootScope.findObjectByKey( - $scope.additionalDatabases, - "systemName", - $scope.viewmodel.mixDatabaseName + $scope.remove = function (moduleContentId, postId) { + $rootScope.showConfirm( + $scope, + "removeConfirmed", + [moduleContentId, postId], + null, + "Remove", + "Deleted data will not able to recover, are you sure you want to delete this item?" ); - if ($scope.additionalDatabase) { - $scope.loadAdditionalData(); - } - if ($routeParams.template) { - $scope.viewmodel.view = $rootScope.findObjectByKey( - $scope.viewmodel.templates, - "fileName", - $routeParams.template - ); - } - $scope.$apply(); - }; - $scope.getListSuccessCallback = function () { - $scope.canDrag = - $scope.request.orderBy !== "Priority" || - $scope.request.direction !== "0"; }; - $scope.loadAdditionalData = async function () { - $scope.loadingData = true; - const getData = await mixDbService.getSingleByParent( - "Page", - $scope.viewmodel.id - ); - if (getData.success) { - $scope.additionalData = getData.data; - $scope.loadingData = false; + + $scope.removeConfirmed = async function (moduleContentId, postId) { + $rootScope.isBusy = true; + var result = await service.delete(moduleContentId, postId); + if (result.success) { + if ($scope.removeCallback) { + $rootScope.executeFunctionByName( + "removeCallback", + $scope.removeCallbackArgs, + $scope + ); + } + $scope.getList(); } else { - $scope.additionalData = { - parentType: "Page", - }; - $scope.loadingData = false; + $rootScope.showMessage("failed"); + $rootScope.isBusy = false; + $scope.$apply(); } - $scope.$apply(); }; - $scope.showChilds = function (id) { - $("#childs-" + id).toggleClass("collapse"); + + $scope.removeCallback = function () {}; + + $scope.saveOthers = async function () { + var response = await service.saveList($scope.others); + if (response.success) { + $scope.getList(); + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } }; $scope.updateInfos = async function (index) { $scope.data.items.splice(index, 1); @@ -3399,208 +2885,48 @@ app.controller("PageController", [ $scope.$apply(); } }; - $scope.selPageType = function () { - $scope.request.query = "level=0&pageType=" + $scope.pageType; - $scope.getList(); - }; - $scope.selectModule = (associations) => { - if (associations) { - $scope.selectedModules = associations; - } - }; - $scope.goUp = async function (items, index) { - items[index].priority -= 1; - items[index - 1].priority += 1; - }; - - $scope.goDown = async function (items, index) { - items[index].priority += 1; - items[index - 1].priority -= 1; - }; - - $scope.saveSuccessCallback = async function () { - var result = await $scope.savePageModules(); - result = result && (await $scope.saveAdditionalData()); - if (result) { - $rootScope.showMessage("Saved", "success"); - } - $rootScope.isBusy = false; - $scope.$apply(); - }; - $scope.loadAdditionalDatabases = async function () { - let getTypes = await databaseService.getList( - $scope.additionalDatabaseRequest - ); - if (getTypes.success) { - $scope.additionalDatabases = getTypes.data.items; - $scope.additionalDatabases.splice(0, 0, { - systemName: null, - displayName: "All", - id: 0, - }); - if ($scope.request.mixDatabaseName) { - $scope.additionalDatabase = $rootScope.findObjectByKey( - $scope.additionalDatabases, - "mixDatabaseName", - $scope.request.mixDatabaseName - ); - } - $scope.request.mixDatabaseName = $routeParams.type || ""; - $scope.$apply(); - } - }; - $scope.onSelectType = async function () { - if ( - $scope.viewmodel && - $scope.additionalDatabase && - $scope.additionalDatabase.systemName - ) { - $scope.viewmodel.mixDatabaseName = $scope.additionalDatabase.systemName; - mixDbService.initDbName($scope.viewmodel.mixDatabaseName); - await $scope.loadAdditionalData(); - } else { - $scope.viewmodel.mixDatabaseName = null; - $scope.additionalData = null; - } - $scope.request.mixDatabaseName = $scope.additionalDatabase.systemName; - $scope.createUrl = `/admin/page/create?type=${$scope.request.mixDatabaseName}`; - if ($routeParams.template) { - $scope.createUrl += `&template=${$routeParams.template}`; - } - if ( - $scope.additionalDatabase && - (!$scope.viewmodel || !$scope.viewmodel.id) - ) { - await $scope.getDefault($scope.request.mixDatabaseName); - } - if ($scope.pageName == "pageList") { - await $scope.filter(); - } - }; - $scope.getDefault = async function (type = null) { - $rootScope.isBusy = true; - type = type || $routeParams.type; - var resp = await service.getDefault({ - type: type || "", - template: $routeParams.template || "", - }); - if (resp.success) { - $scope.viewmodel = resp.data; - mixDbService.initDbName($scope.viewmodel.mixDatabaseName); - if ($scope.getSingleSuccessCallback) { - $scope.getSingleSuccessCallback(); - } - - // $scope.viewmodel.createdDateTime = Date.now(); - $scope.viewmodel.createdBy = $rootScope.authentication.username; - - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - if ($scope.getSingleFailCallback) { - $scope.getSingleFailCallback(); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.saveAdditionalData = async () => { - if ($scope.additionalDatabase.systemName && $scope.additionalData) { - $scope.additionalData.isClone = $scope.viewmodel.isClone; - $scope.additionalData.cultures = $scope.viewmodel.cultures; - $scope.additionalData.intParentId = $scope.viewmodel.id; - $scope.additionalData.parentType = "Page"; - let result = await dataService.save($scope.additionalData); - if (!result.success) { - $rootScope.showErrors(result.errors); - } - return result.success; - } - }; - $scope.savePageModules = async () => { - angular.forEach($scope.selectedModules, (e) => { - e.parentId = $scope.viewmodel.id; - }); - var result = await pageModuleService.saveMany($scope.selectedModules); - if (!result.success) { - $rootScope.showErrors(result.errors); - } - return result.success; - }; - $scope.saveColumns = async function () { - let result = await columnService.saveMany($scope.additionalData.columns); - if (result.success) { - $rootScope.showMessage("success", "success"); - } - }; - - $scope.validate = async function () { - return true; - // Add default alias if create new page - // if (!$scope.viewmodel.id && !$scope.viewmodel.urlAliases.length) { - // // Ex: en-us/page-seo-name - // // await $scope.addAlias($scope.viewmodel.specificulture + '/' + $scope.viewmodel.seoName); - // return true; - // } else { - // return true; - // } - }; - $scope.addAlias = async function (alias) { - var getAlias = await urlAliasService.getDefault(); - if (getAlias.success) { - if (alias) { - getAlias.data.alias = alias; - } - $scope.viewmodel.urlAliases.push(getAlias.data); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(getAlias.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.removeAliasCallback = async function (index) { - $scope.viewmodel.urlAliases.splice(index, 1); - $scope.$apply(); - }; }, ]); "use strict"; -app.factory("PageRestService", [ +app.factory("ModuleGalleryService", [ "$rootScope", "ApiService", "CommonService", - "BaseRestService", + "BaseService", function ($rootScope, apiService, commonService, baseService) { var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-page-content"); - var _updateInfos = async function (pages) { + serviceFactory.init("module-post"); + var _delete = async function (moduleContentId, postId) { + var url = this.prefixUrl + "/delete/" + moduleContentId + "/" + postId; + var req = { + method: "GET", + url: url, + }; + return await apiService.sendRequest(req); + }; + var _updateInfos = async function (modules) { var req = { method: "POST", url: this.prefixUrl + "/update-infos", - data: JSON.stringify(pages), + data: JSON.stringify(modules), }; return await apiService.sendRequest(req); }; + serviceFactory.delete = _delete; serviceFactory.updateInfos = _updateInfos; return serviceFactory; }, ]); "use strict"; -app.controller("PagePostController", [ +app.controller("ModulePostController", [ "$scope", "$rootScope", "ngAppSettings", "$routeParams", "$location", - "PagePostRestService", - "PostRestService", + "ModulePostRestService", "ApiService", "CommonService", function ( @@ -3610,7 +2936,6 @@ app.controller("PagePostController", [ $routeParams, $location, service, - postService, commonService ) { BaseCtrl.call( @@ -3625,35 +2950,30 @@ app.controller("PagePostController", [ $scope.cates = ["Site", "System"]; $scope.others = []; $scope.mixConfigurations = $rootScope.globalSettings; + $scope.canDrag = + $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; + $scope.translate = $rootScope.translate; + $scope.moduleIds = $routeParams.moduleIds || $routeParams.id; + $scope.pageIds = $routeParams.page_ids; + $scope.type = $routeParams.type; + $scope.template = $routeParams.template || ""; + $scope.init = function () { - $scope.pageId = $routeParams.id; - $scope.type = $routeParams.type || ""; - $scope.template = $routeParams.template || ""; - $scope.pageIds = $routeParams.page_ids || $routeParams.id || ""; - $scope.moduleIds = $routeParams.module_ids || ""; - $scope.canDrag = - $scope.request.orderBy === "Priority" && - $scope.request.direction === "Asc"; - $scope.createUrl = - $routeParams.post_type === "gallery" - ? "/admin/post/create-gallery" - : `/admin/post/create?page_ids=${$scope.pageIds}&moduleIds=${$scope.moduleIds}&type=${$scope.type}&template=${$scope.template}`; - $scope.updateUrl = - $routeParams.post_type === "gallery" - ? "/admin/post/gallery-details" - : "/admin/post/details"; + $scope.createUrl = `/admin/post/create?page_ids=${$scope.pageIds}&moduleIds=${$scope.moduleIds}&type=${$scope.type}&template=${$scope.template}`; + $scope.getList(); }; $scope.getList = async function (pageIndex) { + $rootScope.isBusy = true; if (pageIndex !== undefined) { $scope.request.pageIndex = pageIndex; } - $rootScope.isBusy = true; var id = $routeParams.id; - $scope.request.query = "&page_id=" + id; - var response = await service.getList($scope.request); + $scope.moduleContentId = $routeParams.id; + $scope.request.parentId = id; $scope.canDrag = - $scope.request.orderBy === "Priority" && - $scope.request.direction === "Asc"; + $scope.request.orderBy !== "Priority" || + $scope.request.direction !== "0"; + var response = await service.search($scope.request); if (response.success) { $scope.data = response.data; $rootScope.isBusy = false; @@ -3668,19 +2988,16 @@ app.controller("PagePostController", [ item.editUrl = "/admin/post/details/" + item.id; $rootScope.preview("post", item, item.title, "modal-lg"); }; - $scope.remove = function (pageId, postId) { + $scope.remove = function (id) { $rootScope.showConfirm( $scope, "removeConfirmed", - [pageId, postId], + [id], null, "Remove", "Deleted data will not able to recover, are you sure you want to delete this item?" ); }; - $scope.back = function () { - window.history.back(); - }; $scope.removeConfirmed = async function (id) { $rootScope.isBusy = true; @@ -3695,12 +3012,14 @@ app.controller("PagePostController", [ } $scope.getList(); } else { - $rootScope.showErrors(result.errors); + $rootScope.showMessage("failed"); $rootScope.isBusy = false; $scope.$apply(); } }; + $scope.removeCallback = function () {}; + $scope.saveOthers = async function () { var response = await service.saveList($scope.others); if (response.success) { @@ -3737,30 +3056,48 @@ app.controller("PagePostController", [ ]); "use strict"; -app.factory("PagePostRestService", [ +app.factory("ModulePostRestService", [ "$rootScope", "ApiService", "CommonService", "BaseRestService", function ($rootScope, apiService, commonService, baseService) { var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-page-post"); - var _delete = async function (id) { - var url = this.prefixUrl + "/delete/" + id; + serviceFactory.init("module-post"); + + var _search = async function (objData) { + var data = serviceFactory.parseQuery(objData); + var url = this.prefixUrl; + + if (data) { + url += "/search?"; + url = url.concat(data); + } var req = { + serviceBase: this.serviceBase, method: "GET", url: url, }; - return await apiService.getApiResult(req); + return await this.getRestApiResult(req); }; - var _updateInfos = async function (pages) { + + var _delete = async function (id) { + var url = this.prefixUrl + "/" + id; + var req = { + method: "DELETE", + url: url, + }; + return await apiService.sendRequest(req); + }; + var _updateInfos = async function (modules) { var req = { method: "POST", url: this.prefixUrl + "/update-infos", - data: JSON.stringify(pages), + data: JSON.stringify(modules), }; - return await apiService.getApiResult(req); + return await apiService.sendRequest(req); }; + serviceFactory.search = _search; serviceFactory.delete = _delete; serviceFactory.updateInfos = _updateInfos; return serviceFactory; @@ -3768,15 +3105,14 @@ app.factory("PagePostRestService", [ ]); "use strict"; -app.controller("ModulePostController", [ +app.controller("ModuleDataController", [ "$scope", "$rootScope", "ngAppSettings", "$routeParams", "$location", - "ModulePostRestService", - "ApiService", - "CommonService", + "ModuleDataRestService", + "ModuleRestService", function ( $scope, $rootScope, @@ -3784,44 +3120,46 @@ app.controller("ModulePostController", [ $routeParams, $location, service, - commonService + moduleService ) { - BaseCtrl.call( + BaseRestCtrl.call( this, $scope, $rootScope, + $location, $routeParams, ngAppSettings, service ); $scope.request.culture = $rootScope.globalSettings.defaultCulture; + // $scope.request.orderBy = "Priority"; + // $scope.request.direction = "Asc"; $scope.cates = ["Site", "System"]; $scope.others = []; $scope.mixConfigurations = $rootScope.globalSettings; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - $scope.translate = $rootScope.translate; - $scope.moduleIds = $routeParams.moduleIds || $routeParams.id; - $scope.pageIds = $routeParams.page_ids; - $scope.type = $routeParams.type; - $scope.template = $routeParams.template || ""; - - $scope.init = function () { - $scope.createUrl = `/admin/post/create?page_ids=${$scope.pageIds}&moduleIds=${$scope.moduleIds}&type=${$scope.type}&template=${$scope.template}`; - $scope.getList(); + $scope.moduleContentId = $routeParams.moduleContentId; + $scope.backUrl = `/admin/module-data/list/${$scope.moduleContentId}`; + $scope.module = null; + $scope.columns = []; + $scope.editDataUrl = "/admin/module-data/details/" + $scope.moduleContentId; + $scope.init = async function () { + $scope.id = $routeParams.id; }; - $scope.getList = async function (pageIndex) { - $rootScope.isBusy = true; - if (pageIndex !== undefined) { - $scope.request.pageIndex = pageIndex; + $scope.initList = async function () { + $scope.id = $routeParams.id; + if (!$scope.module) { + var getModule = await moduleService.getSingle([$scope.moduleContentId]); + if (getModule.success) { + $scope.module = getModule.data; + $scope.columns = $scope.module.columns; + $scope.$apply(); + } } - var id = $routeParams.id; - $scope.moduleContentId = $routeParams.id; - $scope.request.parentId = id; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || - $scope.request.direction !== "0"; - var response = await service.search($scope.request); + }; + $scope.getList = async function () { + $rootScope.isBusy = true; + $scope.request.moduleContentId = $scope.moduleContentId; + var response = await service.getList($scope.request); if (response.success) { $scope.data = response.data; $rootScope.isBusy = false; @@ -3832,24 +3170,52 @@ app.controller("ModulePostController", [ $scope.$apply(); } }; - $scope.preview = function (item) { - item.editUrl = "/admin/post/details/" + item.id; - $rootScope.preview("post", item, item.title, "modal-lg"); + + $scope.export = async function () { + $rootScope.isBusy = true; + $scope.request.moduleContentId = $scope.moduleContentId; + var response = await service.export($scope.request); + if (response.success) { + window.top.location = response.data.webPath; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } }; - $scope.remove = function (id) { + + $scope.getSingle = async function () { + $rootScope.isBusy = true; + var resp = await service.getSingle($routeParams.id, "portal"); + if (resp && resp.success) { + $scope.activedModuleData = resp.data; + $rootScope.initEditor(); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.remove = function (dataContentId) { $rootScope.showConfirm( $scope, "removeConfirmed", - [id], + [dataContentId], null, "Remove", "Deleted data will not able to recover, are you sure you want to delete this item?" ); }; - $scope.removeConfirmed = async function (id) { + $scope.removeConfirmed = async function (dataContentId) { $rootScope.isBusy = true; - var result = await service.delete(id); + var result = await service.delete([dataContentId]); if (result.success) { if ($scope.removeCallback) { $rootScope.executeFunctionByName( @@ -3860,7 +3226,7 @@ app.controller("ModulePostController", [ } $scope.getList(); } else { - $rootScope.showMessage("failed"); + $rootScope.showErrors(result.errors); $rootScope.isBusy = false; $scope.$apply(); } @@ -3879,100 +3245,47 @@ app.controller("ModulePostController", [ $scope.$apply(); } }; - $scope.updateInfos = async function (index) { - $scope.data.items.splice(index, 1); - $rootScope.isBusy = true; - var startIndex = $scope.data.items[0].priority - 1; - for (var i = 0; i < $scope.data.items.length; i++) { - $scope.data.items[i].priority = startIndex + i + 1; - } - var resp = await service.updateInfos($scope.data.items); - if (resp && resp.success) { - $scope.activedPage = resp.data; - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; }, ]); "use strict"; -app.factory("ModulePostRestService", [ - "$rootScope", +app.factory("ModuleDataRestService", [ + "BaseRestService", "ApiService", "CommonService", - "BaseRestService", - function ($rootScope, apiService, commonService, baseService) { + function (baseService, apiService, commonService) { var serviceFactory = Object.create(baseService); - serviceFactory.init("module-post"); - - var _search = async function (objData) { - var data = serviceFactory.parseQuery(objData); - var url = this.prefixUrl; + serviceFactory.init("mix-module-data"); + // Define more service methods here - if (data) { - url += "/search?"; - url = url.concat(data); - } + var _initForm = async function (moduleContentId) { + var url = `${this.prefixUrl}/init-form/${moduleContentId}`; var req = { - serviceBase: this.serviceBase, method: "GET", url: url, }; - return await this.getRestApiResult(req); - }; - - var _delete = async function (id) { - var url = this.prefixUrl + "/" + id; - var req = { - method: "DELETE", - url: url, - }; return await apiService.sendRequest(req); }; - var _updateInfos = async function (modules) { - var req = { - method: "POST", - url: this.prefixUrl + "/update-infos", - data: JSON.stringify(modules), - }; - return await apiService.sendRequest(req); - }; - serviceFactory.search = _search; - serviceFactory.delete = _delete; - serviceFactory.updateInfos = _updateInfos; + serviceFactory.initForm = _initForm; return serviceFactory; }, ]); "use strict"; -app.controller("PermissionController", [ +app.controller("OrderDetailController", [ "$scope", "$rootScope", "ngAppSettings", - "$routeParams", "$location", - "ApiService", - "CommonService", - "PermissionService", - "RestPortalPageNavigationService", + "$routeParams", + "RestOrderDetailService", function ( $scope, $rootScope, ngAppSettings, - $routeParams, $location, - apiService, - commonService, - service, - navService + $routeParams, + service ) { BaseRestCtrl.call( this, @@ -3983,150 +3296,94 @@ app.controller("PermissionController", [ ngAppSettings, service ); - $scope.request.level = 0; - $scope.miOptions = ngAppSettings.miIcons; - $scope.initDialog = function () { - $("#dlg-permission").on("shown.bs.modal", function () { - $scope.initCurrentPath(); - }); - }; + BaseHub.call(this, $scope); + $scope.progress = 0; + $scope.viewMode = "list"; + $scope.current = null; - $scope.initCurrentPath = async function () { - var resp = await service.getDefault(); - if (resp && resp.success) { - $scope.viewmodel = resp.data; - $scope.viewmodel.url = $location.url(); - $rootScope.isBusy = false; - $scope.$applyAsync(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - if ($scope.getSingleFailCallback) { - $scope.getSingleFailCallback(); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.saveSuccessCallback = function () { - $scope.getSingle(); - }; + $scope.canDrag = + $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - $scope.dragStart = function (index) { - $scope.minPriority = $scope.data.items[0].priority; - $scope.dragStartIndex = index; - }; - $scope.updateOrders = function (index) { - if (index > $scope.dragStartIndex) { - $scope.data.items.splice($scope.dragStartIndex, 1); - } else { - $scope.data.items.splice($scope.dragStartIndex + 1, 1); - } - angular.forEach($scope.data.items, function (e, i) { - e.priority = $scope.minPriority + i; - service.saveFields(e.id, { priority: e.priority }).then((resp) => { - $rootScope.isBusy = false; - $scope.$apply(); - }); + $scope.init = async function () { + $scope.startConnection("mixEcommerceHub", null, (err) => { + console.log(err); }); + $scope.onConnected = () => { + $scope.joinRoom("Admin"); + }; + await $scope.getThemes(); }; + $scope.receiveMessage = function (msg) { + switch (msg.action) { + case "Downloading": + var index = $scope.data.items.findIndex( + (m) => m.id == $scope.current.id + ); + var progress = Math.round(msg.message); + if (index >= 0) { + $scope.progress = progress; + if (progress == 100) { + $scope.installStatus = "Installing"; + } + $scope.$apply(); + } + break; - $scope.updateChildInfos = async function (items) { - $rootScope.isBusy = true; - var resp = await service.updateChildInfos(items); - if (resp && resp.success) { - $scope.activedPage = resp.data; - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); + default: + console.log(msg); + break; } }; - $("#dlg-favorite").on("show.bs.modal", function (event) { - $scope.initCurrentPath(); - }); }, ]); "use strict"; -app.factory("PermissionService", [ +app.factory("RestOrderDetailService", [ "BaseRestService", - "ApiService", - "CommonService", - function (baseService, apiService, commonService) { + function (baseService) { var serviceFactory = Object.create(baseService); - serviceFactory.initService("/rest/mix-services", "permission", true); - var _updateInfos = async function (pages) { - var req = { - method: "POST", - url: this.prefixUrl + "/update-infos", - data: JSON.stringify(pages), - }; - return await apiService.sendRequest(req); - }; - - var _updateChildInfos = async function (pages) { + serviceFactory.initService("/rest/ecommerce", "order-detail"); + var _updateOrderStatus = async function (id, objData) { + var url = `${this.prefixUrl}/update-order-status/${id}`; var req = { + serviceBase: this.serviceBase, method: "POST", - url: this.prefixUrl + "/update-child-infos", - data: JSON.stringify(pages), + url: url, + data: JSON.stringify(objData), }; - return await apiService.sendRequest(req); + return await this.getRestApiResult(req); }; - - serviceFactory.updateInfos = _updateInfos; - serviceFactory.updateChildInfos = _updateChildInfos; - return serviceFactory; - }, -]); - -"use strict"; -app.factory("RestPortalPageNavigationService", [ - "BaseRestService", - "ApiService", - "CommonService", - function (baseService, apiService, commonService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("portal-page-navigation", true); - + serviceFactory.updateOrderStatus = _updateOrderStatus; return serviceFactory; }, ]); "use strict"; -app.controller("PostController", [ +app.controller("PageController", [ "$scope", "$rootScope", - "$location", - "$filter", "ngAppSettings", + "$location", "$routeParams", - "PostRestService", + "PageRestService", + "PagePostRestService", "UrlAliasService", + "RestMixDatabasePortalService", "RestMixDatabaseDataPortalService", "RestMixDatabaseColumnPortalService", - "RestRelatedAttributeDataPortalService", - "RestMixDatabasePortalService", "MixDbService", function ( $scope, $rootScope, - $location, - $filter, ngAppSettings, + $location, $routeParams, service, + pagePostRestService, urlAliasService, + databaseService, dataService, columnService, - navService, - databaseService, mixDbService ) { BaseRestCtrl.call( @@ -4138,116 +3395,164 @@ app.controller("PostController", [ ngAppSettings, service ); - if (!$scope.referrerUrl) { - $scope.referrerUrl = "/admin/post/list"; - } - $scope.request.searchColumns = "title"; $scope.request.culture = $rootScope.globalSettings.defaultCulture; - $scope.request.queries = []; - $scope.request.metadataQueries = []; - $scope.defaultQuery = { - fieldName: "", - compareOperator: "Equal", - value: "", + var pageModuleService = $rootScope.getRestService("mix-page-module"); + $scope.viewmodelType = "page"; + $scope.request.query = "level=0"; + $scope.pageType = {}; + $scope.pageTypes = $rootScope.globalSettings.pageTypes; + $scope.selectedCategories = []; + $scope.selectedTags = []; + $scope.selectedModules = []; + $scope.pageData = { + posts: [], + products: [], + data: [], }; - $scope.viewmodelType = "post"; - $scope.additionalData = {}; - $scope.createUrl = "/admin/post/create?"; - $scope.postTypeRequest = angular.copy(ngAppSettings.request); - ($scope.postTypeRequest.searchColumns = "Type"), - ($scope.postTypeRequest.searchMethod = "Equal"), - ($scope.postTypeRequest.keyword = "AdditionalData"); + $scope.request.columns = [ + "id", + "title", + "createdDateTime", + "type", + "image", + ]; + $scope.additionalData = null; + $scope.temp = null; + $scope.postRequest = angular.copy(ngAppSettings.request); + $scope.additionalDatabaseRequest = angular.copy(ngAppSettings.request); + ($scope.additionalDatabaseRequest.searchColumns = "Type"), + ($scope.additionalDatabaseRequest.searchMethod = "Equal"), + ($scope.additionalDatabaseRequest.keyword = "AdditionalData"); + $scope.canDrag = + $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; + $scope.loadPosts = async function () { + $rootScope.isBusy = true; + var id = $routeParams.id; + $scope.postRequest.query += "&page_id=" + id; + var response = await pagePostRestService.getList($scope.postRequest); - $scope.initList = async function () { - if ($routeParams.template) { - $scope.createUrl = `${$scope.createUrl}&template=${$routeParams.template}`; - } - if ($routeParams.category) { - $scope.request.category = $routeParams.category; - } - if ($routeParams.type) { - $scope.createUrl = `${$scope.createUrl}&type=${$routeParams.type}`; - $scope.request.additionalDatabase = $routeParams.type; - $scope.request.mixDatabaseName = $routeParams.type; - } - if ($routeParams.layout) { - $scope.createUrl = `${$scope.createUrl}&layout=${$routeParams.layout}`; - } - if ($routeParams.page_ids) { - $scope.createUrl = `${$scope.createUrl}&page_ids=${$routeParams.page_ids}`; + if (response.success) { + $scope.pageData.posts = response.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); } - $scope.pageName = "postList"; - await $scope.loadAdditionalDatabases(); - $scope.filter(); }; - - $scope.parseQueryField = function (fieldName, value, operator = "Equal") { - return { - fieldName: fieldName, - value: value, - compareOperator: operator, - }; + $scope.$watch("additionalDatabase", function (newValue, oldValue) { + console.log(newValue, oldValue); + }); + $scope.init = async function () { + await $scope.loadAdditionalDatabases(); + await $scope.getSingle(); }; - $scope.syncProducts = async function () { - $rootScope.isBusy = true; - let names = $scope.data.items.map((m) => { - return m.title; + $scope.initList = function () { + $scope.additionalDatabases.splice(0, 0, { + systemName: "", + displayName: "All", + id: 0, }); - await service.syncProducts(names); - $rootScope.isBusy = false; + $scope.getList(); }; - $scope.filter = async function (pageIndex) { - $rootScope.isBusy = true; - if (pageIndex !== undefined) { - $scope.request.pageIndex = pageIndex; + $scope.getSingleSuccessCallback = function () { + mixDbService.initDbName($scope.viewmodel.mixDatabaseName); + $scope.additionalDatabase = $rootScope.findObjectByKey( + $scope.additionalDatabases, + "systemName", + $scope.viewmodel.mixDatabaseName + ); + if ($scope.additionalDatabase) { + $scope.loadAdditionalData(); } - if ($scope.request.fromDate !== null) { - var d = new Date($scope.request.fromDate); - $scope.request.fromDate = d.toISOString(); + if ($routeParams.template) { + $scope.viewmodel.view = $rootScope.findObjectByKey( + $scope.viewmodel.templates, + "fileName", + $routeParams.template + ); } - if ($scope.request.toDate !== null) { - var dt = new Date($scope.request.toDate); - $scope.request.toDate = dt.toISOString(); + $scope.$apply(); + }; + $scope.getListSuccessCallback = function () { + $scope.canDrag = + $scope.request.orderBy !== "Priority" || + $scope.request.direction !== "0"; + }; + $scope.loadAdditionalData = async function () { + $scope.loadingData = true; + const getData = await mixDbService.getSingleByParent( + "Page", + $scope.viewmodel.id + ); + if (getData.success) { + $scope.additionalData = getData.data; + $scope.loadingData = false; + } else { + $scope.additionalData = { + parentType: "Page", + }; + $scope.loadingData = false; } - var resp = await service.filter($scope.request); + $scope.$apply(); + }; + $scope.showChilds = function (id) { + $("#childs-" + id).toggleClass("collapse"); + }; + $scope.updateInfos = async function (index) { + $scope.data.items.splice(index, 1); + $rootScope.isBusy = true; + var startIndex = $scope.data.items[0].priority - 1; + for (var i = 0; i < $scope.data.items.length; i++) { + $scope.data.items[i].priority = startIndex + i + 1; + } + var resp = await service.updateInfos($scope.data.items); if (resp && resp.success) { - $scope.data = resp.data; - $.each($scope.data.items, function (i, data) { - $.each($scope.viewmodels, function (i, e) { - if (e.dataContentId === data.id) { - data.isHidden = true; - } - }); - }); - if ($scope.getListSuccessCallback) { - $scope.getListSuccessCallback(); - } - if ($scope.isScrollTop) { - $("html, body").animate({ scrollTop: "0px" }, 500); - } + $scope.activedPage = resp.data; + $rootScope.showMessage("success", "success"); $rootScope.isBusy = false; $scope.$apply(); } else { if (resp) { - $rootScope.showErrors(resp.errors || ["Failed"]); - } - if ($scope.getListFailCallback) { - $scope.getListFailCallback(); + $rootScope.showErrors(resp.errors); } $rootScope.isBusy = false; $scope.$apply(); } }; - $scope.loadMetadataDatabase = async function () { - var getMixDatabase = await databaseService.getByName(["Metadata"]); - let typeCol = getMixDatabase.data.columns.find( - (c) => c.systemName == "type" - ); - $scope.lstMetadata = typeCol.columnConfigurations.allowedValues; + $scope.selPageType = function () { + $scope.request.query = "level=0&pageType=" + $scope.pageType; + $scope.getList(); + }; + $scope.selectModule = (associations) => { + if (associations) { + $scope.selectedModules = associations; + } + }; + $scope.goUp = async function (items, index) { + items[index].priority -= 1; + items[index - 1].priority += 1; + }; + + $scope.goDown = async function (items, index) { + items[index].priority += 1; + items[index - 1].priority -= 1; + }; + + $scope.saveSuccessCallback = async function () { + var result = await $scope.savePageModules(); + result = result && (await $scope.saveAdditionalData()); + if (result) { + $rootScope.showMessage("Saved", "success"); + } + $rootScope.isBusy = false; $scope.$apply(); }; $scope.loadAdditionalDatabases = async function () { - let getTypes = await databaseService.getList($scope.postTypeRequest); + let getTypes = await databaseService.getList( + $scope.additionalDatabaseRequest + ); if (getTypes.success) { $scope.additionalDatabases = getTypes.data.items; $scope.additionalDatabases.splice(0, 0, { @@ -4266,6 +3571,34 @@ app.controller("PostController", [ $scope.$apply(); } }; + $scope.onSelectType = async function () { + if ( + $scope.viewmodel && + $scope.additionalDatabase && + $scope.additionalDatabase.systemName + ) { + $scope.viewmodel.mixDatabaseName = $scope.additionalDatabase.systemName; + mixDbService.initDbName($scope.viewmodel.mixDatabaseName); + await $scope.loadAdditionalData(); + } else { + $scope.viewmodel.mixDatabaseName = null; + $scope.additionalData = null; + } + $scope.request.mixDatabaseName = $scope.additionalDatabase.systemName; + $scope.createUrl = `/admin/page/create?type=${$scope.request.mixDatabaseName}`; + if ($routeParams.template) { + $scope.createUrl += `&template=${$routeParams.template}`; + } + if ( + $scope.additionalDatabase && + (!$scope.viewmodel || !$scope.viewmodel.id) + ) { + await $scope.getDefault($scope.request.mixDatabaseName); + } + if ($scope.pageName == "pageList") { + await $scope.filter(); + } + }; $scope.getDefault = async function (type = null) { $rootScope.isBusy = true; type = type || $routeParams.type; @@ -4296,240 +3629,58 @@ app.controller("PostController", [ $scope.$apply(); } }; - $scope.preview = function (item) { - item.editUrl = "/admin/post/details/" + item.id; - $rootScope.preview("post", item, item.title, "modal-lg"); - }; - $scope.onSelectType = function () { - if ($scope.viewmodel) { - $scope.viewmodel.mixDatabaseName = $scope.additionalDatabase.systemName; - mixDbService.initDbName($scope.viewmodel.mixDatabaseName); - $scope.loadAdditionalData(); - } - $scope.request.additionalDatabase = - $scope.additionalDatabase.mixDatabaseName; - $scope.createUrl = `/admin/post/create?type=${$scope.request.additionalDatabase}`; - if ($routeParams.template) { - $scope.createUrl += `&template=${$routeParams.template}`; - } - if ( - $scope.additionalDatabase.mixDatabaseName && - (!$scope.viewmodel || !$scope.viewmodel.id) - ) { - $scope.getDefault($scope.request.additionalDatabase); - } - if ($scope.pageName == "postList") { - $scope.filter(); + $scope.saveAdditionalData = async () => { + if ($scope.additionalDatabase.systemName && $scope.additionalData) { + $scope.additionalData.isClone = $scope.viewmodel.isClone; + $scope.additionalData.cultures = $scope.viewmodel.cultures; + $scope.additionalData.intParentId = $scope.viewmodel.id; + $scope.additionalData.parentType = "Page"; + let result = await dataService.save($scope.additionalData); + if (!result.success) { + $rootScope.showErrors(result.errors); + } + return result.success; } }; - $scope.getListRelated = async function (pageIndex) { - if (pageIndex !== undefined) { - $scope.request.pageIndex = pageIndex; - } - if ($scope.request.fromDate !== null) { - var d = new Date($scope.request.fromDate); - $scope.request.fromDate = d.toISOString(); + $scope.savePageModules = async () => { + angular.forEach($scope.selectedModules, (e) => { + e.parentId = $scope.viewmodel.id; + }); + var result = await pageModuleService.saveMany($scope.selectedModules); + if (!result.success) { + $rootScope.showErrors(result.errors); } - if ($scope.request.toDate !== null) { - var d = new Date($scope.request.toDate); - $scope.request.toDate = d.toISOString(); + return result.success; + }; + $scope.saveColumns = async function () { + let result = await columnService.saveMany($scope.additionalData.columns); + if (result.success) { + $rootScope.showMessage("success", "success"); } - var resp = await service.filter($scope.request); - if (resp && resp.success) { - $scope.relatedData = angular.copy(resp.data); - $scope.relatedData.items = []; - angular.forEach(resp.data.items, (element) => { - let isActive = - null != - $scope.viewmodel.postNavs.find( - (p) => p.destinationId == element.id - ); - if (!isActive) { - var obj = { - description: element.title, - destinationId: element.id, - image: element.image, - isActived: isActive, - sourceId: $scope.viewmodel.id, - specificulture: $scope.viewmodel.specificulture, - status: "Published", - }; - result.push(obj); - } - }); - resp.data.items = result; + }; + + $scope.validate = async function () { + return true; + // Add default alias if create new page + // if (!$scope.viewmodel.id && !$scope.viewmodel.urlAliases.length) { + // // Ex: en-us/page-seo-name + // // await $scope.addAlias($scope.viewmodel.specificulture + '/' + $scope.viewmodel.seoName); + // return true; + // } else { + // return true; + // } + }; + $scope.addAlias = async function (alias) { + var getAlias = await urlAliasService.getDefault(); + if (getAlias.success) { + if (alias) { + getAlias.data.alias = alias; + } + $scope.viewmodel.urlAliases.push(getAlias.data); $rootScope.isBusy = false; $scope.$apply(); - return resp.data; } else { - $rootScope.showErrors(getData.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.saveFailCallback = function () { - angular.forEach($scope.viewmodel.mixDatabaseNavs, function (nav) { - if (nav.isActived) { - $rootScope.decryptMixDatabase( - nav.mixDatabase.attributes, - nav.mixDatabase.postData.items - ); - } - }); - }; - $scope.saveSuccessCallback = async function () { - if ($scope.additionalData && $scope.viewmodel.mixDatabaseName) { - var creating = !$scope.additionalData.parentId; - $scope.additionalData.parentType = "Post"; - $scope.additionalData.parentId = $scope.viewmodel.id; - mixDbService.initDbName($scope.viewmodel.mixDatabaseName); - var saveResult = await mixDbService.save($scope.additionalData); - if (saveResult.success) { - $rootScope.showMessage("Additional Data Saved", "success"); - $scope.additionalData = saveResult.data; - if (creating) { - $location.url(`/admin/post/details/${$scope.viewmodel.id}`); - } - } else { - $rootScope.showErrors(result.errors); - } - // $scope.additionalData.isClone = $scope.viewmodel.isClone; - // $scope.additionalData.cultures = $scope.viewmodel.cultures; - // $scope.additionalData.intParentId = $scope.viewmodel.id; - // $scope.additionalData.parentType = "Post"; - // let result = await dataService.save($scope.additionalData); - // if (!result.success) { - // $rootScope.showErrors(result.errors); - // } else { - // $scope.additionalData = result.data; - // // $scope.saveColumns(); - // } - } - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - }; - - $scope.saveColumns = async function () { - let result = await columnService.saveMany($scope.additionalData.columns); - if (result.success) { - $rootScope.showMessage("success", "success"); - } - }; - $scope.getSingleSuccessCallback = async function () { - if (!$scope.viewmodel.id) { - $scope.viewmodel.mixDatabaseName = $routeParams.type; - } - mixDbService.initDbName($scope.viewmodel.mixDatabaseName); - await $scope.loadMetadataDatabase(); - // $scope.defaultThumbnailImgWidth = - // ngAppSettings.mixConfigurations.DefaultThumbnailImgWidth; - // $scope.defaultThumbnailImgHeight = - // ngAppSettings.mixConfigurations.DefaultThumbnailImgHeight; - - // $scope.defaultFeatureImgWidth = - // ngAppSettings.mixConfigurations.DefaultFeatureImgWidth; - // $scope.defaultFeatureImgHeight = - // ngAppSettings.mixConfigurations.DefaultFeatureImgHeight; - $scope.request.additionalDatabase = $scope.viewmodel.mixDatabaseName; - var moduleIds = $routeParams.moduleIds; - var pageIds = $routeParams.page_ids; - $scope.additionalDatabase = $rootScope.findObjectByKey( - $scope.additionalDatabases, - "systemName", - $scope.request.additionalDatabase - ); - $scope.loadAdditionalData(); - if (moduleIds) { - for (var moduleContentId of moduleIds.split(",")) { - var moduleNav = $rootScope.findObjectByKey( - $scope.viewmodel.modules, - "moduleContentId", - moduleContentId - ); - if (moduleNav) { - moduleNav.isActived = true; - } - } - } - if (pageIds) { - for (var pageId of pageIds.split(",")) { - var pageNav = $rootScope.findObjectByKey( - $scope.viewmodel.pages, - "pageId", - pageId - ); - if (pageNav) { - pageNav.isActived = true; - } - } - } - }; - $scope.loadAdditionalData = async function () { - if ($scope.viewmodel.mixDatabaseName) { - $scope.loadingData = true; - mixDbService.initDbName($scope.viewmodel.mixDatabaseName); - if ($scope.viewmodel.id) { - const getData = await mixDbService.getSingleByParent( - "Post", - $scope.viewmodel.id - ); - if (getData.success) { - $scope.additionalData = getData.data; - $scope.loadingData = false; - } - $scope.$apply(); - } else { - $scope.additionalData = { - parentType: "Post", - }; - $scope.loadingData = false; - } - } - }; - $scope.generateSeo = function () { - if ($scope.viewmodel) { - if ( - $scope.viewmodel.seoName === null || - $scope.viewmodel.seoName === "" - ) { - $scope.viewmodel.seoName = $rootScope.generateKeyword( - $scope.viewmodel.title, - "-" - ); - if ($scope.viewmodel.seoName.length > 50) { - $scope.viewmodel.seoName = - $scope.viewmodel.seoName.substring(0, 80) + "..."; - } - } - if ( - $scope.viewmodel.seoTitle === null || - $scope.viewmodel.seoTitle === "" - ) { - $scope.viewmodel.seoTitle = $scope.viewmodel.title; - } - if ( - $scope.viewmodel.seoDescription === null || - $scope.viewmodel.seoDescription === "" - ) { - $scope.viewmodel.seoDescription = $scope.viewmodel.excerpt; - } - if ( - $scope.viewmodel.seoKeywords === null || - $scope.viewmodel.seoKeywords === "" - ) { - $scope.viewmodel.seoKeywords = $scope.viewmodel.title; - } - } - }; - $scope.addAlias = async function () { - var getAlias = await urlAliasService.getDefault(); - if (getAlias.success) { - $scope.viewmodel.urlAliases.push(getAlias.data); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(getAlias.errors); + $rootScope.showErrors(getAlias.errors); $rootScope.isBusy = false; $scope.$apply(); } @@ -4538,105 +3689,143 @@ app.controller("PostController", [ $scope.viewmodel.urlAliases.splice(index, 1); $scope.$apply(); }; - - $scope.validate = function () { - angular.forEach($scope.viewmodel.mixDatabaseNavs, function (nav) { - if (nav.isActived) { - $rootScope.encryptMixDatabase( - nav.mixDatabase.attributes, - nav.mixDatabase.postData.items - ); - } - }); - return true; - }; }, ]); "use strict"; -app.factory("PostRestService", [ - "BaseRestService", +app.factory("PageRestService", [ + "$rootScope", "ApiService", - function (baseService, apiService) { + "CommonService", + "BaseRestService", + function ($rootScope, apiService, commonService, baseService) { var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-post-content"); - var _syncProducts = async function (names) { - var url = `/api/daphale/sync/products`; - var req = { - serviceBase: "", - method: "POST", - url: url, - data: { - batch: 50, - isScaleImage: true, - isSyncPrice: true, - isSyncAll: false, - productNames: names, - }, - }; - return await apiService.sendPureRequest(req); - }; - var _filter = async function (request) { - var url = `${this.prefixUrl}/filter`; + serviceFactory.init("mix-page-content"); + var _updateInfos = async function (pages) { var req = { - serviceBase: this.serviceBase, method: "POST", - url: url, - data: request, + url: this.prefixUrl + "/update-infos", + data: JSON.stringify(pages), }; - return await this.getRestApiResult(req); + return await apiService.sendRequest(req); }; - // Define more service methods here - serviceFactory.filter = _filter; - serviceFactory.syncProducts = _syncProducts; + serviceFactory.updateInfos = _updateInfos; return serviceFactory; }, ]); "use strict"; -app.controller("RoleController", [ +app.controller("PageGalleryController", [ "$scope", "$rootScope", - "$location", - "$routeParams", "ngAppSettings", - "RestMixDatabaseDataPortalService", - "RestMixDatabaseColumnPortalService", - "RoleService", + "$routeParams", + "$location", + "PageGalleryService", + "PostRestService", + "ApiService", + "CommonService", function ( $scope, $rootScope, - $location, - $routeParams, ngAppSettings, - dataService, - columnService, - service + $routeParams, + $location, + service, + postService, + apiService, + commonService ) { - BaseRestCtrl.call( + BaseCtrl.call( this, $scope, $rootScope, - $location, $routeParams, ngAppSettings, service ); - $scope.role = { name: "" }; - $scope.initPermissions = async function () { - let backUrl = "/admin/role/list"; - $scope.createUrl = `/admin/mix-database-data/create?mixDatabaseName=sysPermission&dataContentId=default&guidParentId=${$scope.viewmodel.id}&parentType=Role&backUrl=${backUrl}`; - $scope.updateUrl = "/admin/mix-database-data/details"; - }; - - $scope.createRole = async function () { + $scope.cates = ["Site", "System"]; + $scope.others = []; + $scope.mixConfigurations = $rootScope.globalSettings; + $scope.pageId = $routeParams.id; + $scope.canDrag = + $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; + $scope.getList = async function () { $rootScope.isBusy = true; - var result = await service.createRole($scope.role.name); - if (result.success) { - $scope.role.name = ""; - $scope.getList(); + var id = $routeParams.id; + $scope.request.query = "&page_id=" + id; + var response = await service.getList($scope.request); + $scope.canDrag = + $scope.request.orderBy !== "Priority" || + $scope.request.direction !== "0"; + if (response.success) { + $scope.data = response.data; + $rootScope.isBusy = false; + $scope.$apply(); } else { - $rootScope.showErrors(result.errors); + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.remove = function (pageId, postId) { + $rootScope.showConfirm( + $scope, + "removeConfirmed", + [pageId, postId], + null, + "Remove", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + }; + + $scope.removeConfirmed = async function (pageId, postId) { + $rootScope.isBusy = true; + var result = await service.delete(pageId, postId); + if (result.success) { + if ($scope.removeCallback) { + $rootScope.executeFunctionByName( + "removeCallback", + $scope.removeCallbackArgs, + $scope + ); + } + $scope.getList(); + } else { + $rootScope.showMessage("failed"); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + + $scope.saveOthers = async function () { + var response = await service.saveList($scope.others); + if (response.success) { + $scope.getList(); + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.updateInfos = async function (index) { + $scope.data.items.splice(index, 1); + $rootScope.isBusy = true; + var startIndex = $scope.data.items[0].priority - 1; + for (var i = 0; i < $scope.data.items.length; i++) { + $scope.data.items[i].priority = startIndex + i + 1; + } + var resp = await service.updateInfos($scope.data.items); + if (resp && resp.success) { + $scope.activedPage = resp.data; + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } $rootScope.isBusy = false; $scope.$apply(); } @@ -4645,151 +3834,232 @@ app.controller("RoleController", [ ]); "use strict"; -app.factory("RoleService", [ - "BaseRestService", +app.factory("PageGalleryService", [ + "$rootScope", "ApiService", "CommonService", - function (baseService, apiService, commonService) { + "BaseService", + function ($rootScope, apiService, commonService, baseService) { var serviceFactory = Object.create(baseService); - serviceFactory.initService("/rest/mix-account", "role", true); - - var _getPermissions = async function () { + serviceFactory.init("page-post"); + var _delete = async function (pageId, postId) { + var url = this.prefixUrl + "/delete/" + pageId + "/" + postId; var req = { method: "GET", - url: this.prefixUrl + "/permissions", + url: url, }; return await apiService.sendRequest(req); }; - - var _updatePermission = async function (permission) { + var _updateInfos = async function (pages) { var req = { method: "POST", - url: this.prefixUrl + "/update-permission", - data: JSON.stringify(permission), + url: this.prefixUrl + "/update-infos", + data: JSON.stringify(pages), }; return await apiService.sendRequest(req); }; - var _createRole = function (name) { - var req = { - method: "POST", - url: this.prefixUrl + "/create", - data: JSON.stringify(name), - }; - - return apiService.sendRequest(req); - }; - serviceFactory.createRole = _createRole; - serviceFactory.getPermissions = _getPermissions; - serviceFactory.updatePermission = _updatePermission; + serviceFactory.delete = _delete; + serviceFactory.updateInfos = _updateInfos; return serviceFactory; }, ]); "use strict"; -app.controller("OrderDetailController", [ +app.controller("PagePostController", [ "$scope", "$rootScope", "ngAppSettings", - "$location", "$routeParams", - "RestOrderDetailService", + "$location", + "PagePostRestService", + "PostRestService", + "ApiService", + "CommonService", function ( $scope, $rootScope, ngAppSettings, - $location, $routeParams, - service + $location, + service, + postService, + commonService ) { - BaseRestCtrl.call( + BaseCtrl.call( this, $scope, $rootScope, - $location, $routeParams, ngAppSettings, service ); - BaseHub.call(this, $scope); - $scope.progress = 0; - $scope.viewMode = "list"; - $scope.current = null; - - $scope.canDrag = - $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - - $scope.init = async function () { - $scope.startConnection("mixEcommerceHub", null, (err) => { - console.log(err); - }); - $scope.onConnected = () => { - $scope.joinRoom("Admin"); - }; - await $scope.getThemes(); + $scope.request.culture = $rootScope.globalSettings.defaultCulture; + $scope.cates = ["Site", "System"]; + $scope.others = []; + $scope.mixConfigurations = $rootScope.globalSettings; + $scope.init = function () { + $scope.pageId = $routeParams.id; + $scope.type = $routeParams.type || ""; + $scope.template = $routeParams.template || ""; + $scope.pageIds = $routeParams.page_ids || $routeParams.id || ""; + $scope.moduleIds = $routeParams.module_ids || ""; + $scope.canDrag = + $scope.request.orderBy === "Priority" && + $scope.request.direction === "Asc"; + $scope.createUrl = + $routeParams.post_type === "gallery" + ? "/admin/post/create-gallery" + : `/admin/post/create?page_ids=${$scope.pageIds}&moduleIds=${$scope.moduleIds}&type=${$scope.type}&template=${$scope.template}`; + $scope.updateUrl = + $routeParams.post_type === "gallery" + ? "/admin/post/gallery-details" + : "/admin/post/details"; }; - $scope.receiveMessage = function (resp) { - let msg = JSON.parse(resp); - switch (msg.action) { - case "Downloading": - var index = $scope.data.items.findIndex( - (m) => m.id == $scope.current.id - ); - var progress = Math.round(msg.message); - if (index >= 0) { - $scope.progress = progress; - if (progress == 100) { - $scope.installStatus = "Installing"; - } - $scope.$apply(); - } - break; - - default: - console.log(msg); - break; + $scope.getList = async function (pageIndex) { + if (pageIndex !== undefined) { + $scope.request.pageIndex = pageIndex; + } + $rootScope.isBusy = true; + var id = $routeParams.id; + $scope.request.query = "&page_id=" + id; + var response = await service.getList($scope.request); + $scope.canDrag = + $scope.request.orderBy === "Priority" && + $scope.request.direction === "Asc"; + if (response.success) { + $scope.data = response.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); } }; - }, -]); - -"use strict"; -app.factory("RestOrderDetailService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.initService("/rest/ecommerce", "order-detail"); - var _updateOrderStatus = async function (id, objData) { - var url = `${this.prefixUrl}/update-order-status/${id}`; - var req = { - serviceBase: this.serviceBase, - method: "POST", - url: url, - data: JSON.stringify(objData), - }; - return await this.getRestApiResult(req); + $scope.preview = function (item) { + item.editUrl = "/admin/post/details/" + item.id; + $rootScope.preview("post", item, item.title, "modal-lg"); + }; + $scope.remove = function (pageId, postId) { + $rootScope.showConfirm( + $scope, + "removeConfirmed", + [pageId, postId], + null, + "Remove", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + }; + $scope.back = function () { + window.history.back(); }; - serviceFactory.updateOrderStatus = _updateOrderStatus; - return serviceFactory; - }, -]); -"use strict"; -app.controller("QueueLogController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$location", - "$routeParams", - "AuthService", - "QueueLogRestService", - function ( - $scope, - $rootScope, - ngAppSettings, - $location, - $routeParams, - authService, - service + $scope.removeConfirmed = async function (id) { + $rootScope.isBusy = true; + var result = await service.delete(id); + if (result.success) { + if ($scope.removeCallback) { + $rootScope.executeFunctionByName( + "removeCallback", + $scope.removeCallbackArgs, + $scope + ); + } + $scope.getList(); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + + $scope.saveOthers = async function () { + var response = await service.saveList($scope.others); + if (response.success) { + $scope.getList(); + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.updateInfos = async function (index) { + $scope.data.items.splice(index, 1); + $rootScope.isBusy = true; + var startIndex = $scope.data.items[0].priority - 1; + for (var i = 0; i < $scope.data.items.length; i++) { + $scope.data.items[i].priority = startIndex + i + 1; + } + var resp = await service.updateInfos($scope.data.items); + if (resp && resp.success) { + $scope.activedPage = resp.data; + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + }, +]); + +"use strict"; +app.factory("PagePostRestService", [ + "$rootScope", + "ApiService", + "CommonService", + "BaseRestService", + function ($rootScope, apiService, commonService, baseService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("mix-page-post"); + var _delete = async function (id) { + var url = this.prefixUrl + "/delete/" + id; + var req = { + method: "GET", + url: url, + }; + return await apiService.getApiResult(req); + }; + var _updateInfos = async function (pages) { + var req = { + method: "POST", + url: this.prefixUrl + "/update-infos", + data: JSON.stringify(pages), + }; + return await apiService.getApiResult(req); + }; + serviceFactory.delete = _delete; + serviceFactory.updateInfos = _updateInfos; + return serviceFactory; + }, +]); + +"use strict"; +app.controller("PermissionController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$routeParams", + "$location", + "ApiService", + "CommonService", + "PermissionService", + "RestPortalPageNavigationService", + function ( + $scope, + $rootScope, + ngAppSettings, + $routeParams, + $location, + apiService, + commonService, + service, + navService ) { BaseRestCtrl.call( this, @@ -4800,748 +4070,840 @@ app.controller("QueueLogController", [ ngAppSettings, service ); - authService.fillAuthData(); - $scope.request.status = null; - $scope.messages = []; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - $scope.getListSuccessCallback = function () { - angular.forEach($scope.data.items, function (e) { - switch (e.state) { - case "ACK": - e.objClass = "text-success"; - break; - case "NACK": - e.objClass = "text-warning"; - break; - case "FAILED": - e.objClass = "text-danger"; - break; - default: - e.objClass = "text-info"; - break; + $scope.request.level = 0; + $scope.miOptions = ngAppSettings.miIcons; + $scope.initDialog = function () { + $("#dlg-permission").on("shown.bs.modal", function () { + $scope.initCurrentPath(); + }); + }; + + $scope.initCurrentPath = async function () { + var resp = await service.getDefault(); + if (resp && resp.success) { + $scope.viewmodel = resp.data; + $scope.viewmodel.url = $location.url(); + $rootScope.isBusy = false; + $scope.$applyAsync(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + if ($scope.getSingleFailCallback) { + $scope.getSingleFailCallback(); } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.saveSuccessCallback = function () { + $scope.getSingle(); + }; + + $scope.dragStart = function (index) { + $scope.minPriority = $scope.data.items[0].priority; + $scope.dragStartIndex = index; + }; + $scope.updateOrders = function (index) { + if (index > $scope.dragStartIndex) { + $scope.data.items.splice($scope.dragStartIndex, 1); + } else { + $scope.data.items.splice($scope.dragStartIndex + 1, 1); + } + angular.forEach($scope.data.items, function (e, i) { + e.priority = $scope.minPriority + i; + service.saveFields(e.id, { priority: e.priority }).then((resp) => { + $rootScope.isBusy = false; + $scope.$apply(); + }); }); }; - $scope.view = function (item) { - switch (item.state) { - case "ACK": - item.objClass = "text-success"; - break; - case "NACK": - item.objClass = "text-warning"; - break; - case "FAILED": - item.objClass = "text-danger"; - break; - default: - item.objClass = "text-info"; - break; + + $scope.updateChildInfos = async function (items) { + $rootScope.isBusy = true; + var resp = await service.updateChildInfos(items); + if (resp && resp.success) { + $scope.activedPage = resp.data; + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); } - $rootScope.preview("object", item, null, "modal-lg"); }; + $("#dlg-favorite").on("show.bs.modal", function (event) { + $scope.initCurrentPath(); + }); }, ]); "use strict"; -app.factory("QueueLogRestService", [ +app.factory("PermissionService", [ "BaseRestService", - function (baseService) { - var serviceFactory = angular.copy(baseService); - serviceFactory.initService("/rest", "mix-log/queue-log", true); - var _search = async function (objData, queries = null) { - var data = serviceFactory.parseQuery(objData); - - var url = `${this.prefixUrl}/search`; + "ApiService", + "CommonService", + function (baseService, apiService, commonService) { + var serviceFactory = Object.create(baseService); + serviceFactory.initService("/rest/mix-services", "permission", true); + var _updateInfos = async function (pages) { + var req = { + method: "POST", + url: this.prefixUrl + "/update-infos", + data: JSON.stringify(pages), + }; + return await apiService.sendRequest(req); + }; - if (data) { - url += "?"; - url = url.concat(data); - if (queries) { - url += "&"; - var extraQueries = serviceFactory.parseQuery(queries); - url = url.concat(extraQueries); - } - } + var _updateChildInfos = async function (pages) { var req = { - serviceBase: this.serviceBase, - apiVersion: this.apiVersion, - method: "GET", - url: url, + method: "POST", + url: this.prefixUrl + "/update-child-infos", + data: JSON.stringify(pages), }; - return await this.getRestApiResult(req); + return await apiService.sendRequest(req); }; - serviceFactory.getList = _search; + + serviceFactory.updateInfos = _updateInfos; + serviceFactory.updateChildInfos = _updateChildInfos; return serviceFactory; }, ]); "use strict"; -app.controller("SchedulerController", [ - "$scope", - "$rootScope", - "$routeParams", - "$location", - "SchedulerService", - function ($scope, $rootScope, $routeParams, $location, service) { - $scope.jobs = []; - $scope.intervalTypes = [ - "Second", - "Minute", - "Hour", - "Day", - "Week", - "Month", - "Year", - ]; - $scope.templates = { - "Mix.Scheduler.Jobs.KeepPoolAliveJob": { - domain: "https://example.com", - }, - "Mix.Scheduler.Jobs.PublishScheduledPostsJob": {}, - "Mix.Scheduler.Jobs.SendMessageQueueJob": { - data: { - topic: "", - action: "", - data: {}, - }, - }, - "Mix.Scheduler.Jobs.SendPortalMessageJob": { - data: { - topic: "", - action: "", - data: "", - }, - }, - }; - $scope.schedule = { - jobData: { - data: { - type: "Info", - from: { - connectionId: "", - userName: "", - avatar: "", - }, - title: "value", - message: "content", - data: {}, - }, - }, - cronExpression: null, - name: null, - groupName: null, - jobName: null, - description: null, - startAt: null, - isStartNow: true, - interval: null, - intervalType: "Second", - repeatCount: null, - }; - $scope.updateMessageTemplate = () => { - $scope.schedule.jobData = null; - setTimeout(() => { - $scope.schedule.jobData = $scope.templates[$scope.schedule.jobName]; - $scope.$apply(); - }, 200); - }; - $scope.init = function () { - $scope.getTriggers(); - $scope.getJobs(); - }; +app.factory("RestPortalPageNavigationService", [ + "BaseRestService", + "ApiService", + "CommonService", + function (baseService, apiService, commonService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("portal-page-navigation", true); - $scope.getSingle = async function () { - $scope.getJobs(); - $scope.getTrigger(); + return serviceFactory; + }, +]); + +"use strict"; +app.controller("PostController", [ + "$scope", + "$rootScope", + "$location", + "$filter", + "ngAppSettings", + "$routeParams", + "PostRestService", + "UrlAliasService", + "RestMixDatabaseDataPortalService", + "RestMixDatabaseColumnPortalService", + "RestRelatedAttributeDataPortalService", + "RestMixDatabasePortalService", + "MixDbService", + function ( + $scope, + $rootScope, + $location, + $filter, + ngAppSettings, + $routeParams, + service, + urlAliasService, + dataService, + columnService, + navService, + databaseService, + mixDbService + ) { + BaseRestCtrl.call( + this, + $scope, + $rootScope, + $location, + $routeParams, + ngAppSettings, + service + ); + if (!$scope.referrerUrl) { + $scope.referrerUrl = "/admin/post/list"; + } + $scope.request.searchColumns = "title"; + $scope.request.culture = $rootScope.globalSettings.defaultCulture; + $scope.request.queries = []; + $scope.request.metadataQueries = []; + $scope.defaultQuery = { + fieldName: "", + compareOperator: "Equal", + value: "", }; + $scope.viewmodelType = "post"; + $scope.additionalData = {}; + $scope.createUrl = "/admin/post/create?"; + $scope.postTypeRequest = angular.copy(ngAppSettings.request); + ($scope.postTypeRequest.searchColumns = "Type"), + ($scope.postTypeRequest.searchMethod = "Equal"), + ($scope.postTypeRequest.keyword = "AdditionalData"); - $scope.getTrigger = async function () { - if ($routeParams.name) { - $rootScope.isBusy = true; - $scope.isReschedule = true; - var resp = await service.getTrigger($routeParams.name); - if (resp && resp.success) { - $scope.trigger = resp.data.trigger; - // $scope.schedule.trigger = $scope.trigger; - $scope.schedule.name = $scope.trigger.name; - $scope.schedule.jobName = $scope.trigger.jobName; - $scope.schedule.groupName = $scope.trigger.group; - // $scope.schedule.interval = $scope.trigger.repeatInterval; - $scope.schedule.repeatCount = $scope.trigger.repeatCount; - if ($scope.trigger.jobDataMap) { - if ($scope.trigger.jobDataMap.data) { - $scope.schedule.jobData = { - data: JSON.parse($scope.trigger.jobDataMap.data), - }; - } else { - $scope.schedule.jobData = $scope.trigger.jobDataMap; - } - } - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors || ["Failed"]); - } - $rootScope.isBusy = false; - $scope.$apply(); - } + $scope.initList = async function () { + if ($routeParams.template) { + $scope.createUrl = `${$scope.createUrl}&template=${$routeParams.template}`; + } + if ($routeParams.category) { + $scope.request.category = $routeParams.category; + } + if ($routeParams.type) { + $scope.createUrl = `${$scope.createUrl}&type=${$routeParams.type}`; + $scope.request.additionalDatabase = $routeParams.type; + $scope.request.mixDatabaseName = $routeParams.type; + } + if ($routeParams.layout) { + $scope.createUrl = `${$scope.createUrl}&layout=${$routeParams.layout}`; + } + if ($routeParams.page_ids) { + $scope.createUrl = `${$scope.createUrl}&page_ids=${$routeParams.page_ids}`; } + $scope.pageName = "postList"; + await $scope.loadAdditionalDatabases(); + $scope.filter(); }; - $scope.createSchedule = async function () { + $scope.parseQueryField = function (fieldName, value, operator = "Equal") { + return { + fieldName: fieldName, + value: value, + compareOperator: operator, + }; + }; + $scope.syncProducts = async function () { $rootScope.isBusy = true; - var resp = $scope.isReschedule - ? await service.reschedule($scope.schedule) - : await service.createSchedule($scope.schedule); + let names = $scope.data.items.map((m) => { + return m.title; + }); + await service.syncProducts(names); + $rootScope.isBusy = false; + }; + $scope.filter = async function (pageIndex) { + $rootScope.isBusy = true; + if (pageIndex !== undefined) { + $scope.request.pageIndex = pageIndex; + } + if ($scope.request.fromDate !== null) { + var d = new Date($scope.request.fromDate); + $scope.request.fromDate = d.toISOString(); + } + if ($scope.request.toDate !== null) { + var dt = new Date($scope.request.toDate); + $scope.request.toDate = dt.toISOString(); + } + var resp = await service.filter($scope.request); if (resp && resp.success) { - $rootScope.isBusy = true; - $location.url("/admin/scheduler"); + $scope.data = resp.data; + $.each($scope.data.items, function (i, data) { + $.each($scope.viewmodels, function (i, e) { + if (e.dataContentId === data.id) { + data.isHidden = true; + } + }); + }); + if ($scope.getListSuccessCallback) { + $scope.getListSuccessCallback(); + } + if ($scope.isScrollTop) { + $("html, body").animate({ scrollTop: "0px" }, 500); + } + $rootScope.isBusy = false; $scope.$apply(); } else { if (resp) { $rootScope.showErrors(resp.errors || ["Failed"]); } + if ($scope.getListFailCallback) { + $scope.getListFailCallback(); + } $rootScope.isBusy = false; $scope.$apply(); } }; - $scope.execute = async function (name) { - try { - $rootScope.isBusy = true; - await service.execute(name); - $rootScope.isBusy = false; - $scope.$apply(); - } catch {} + $scope.loadMetadataDatabase = async function () { + var getMixDatabase = await databaseService.getByName(["Metadata"]); + let typeCol = getMixDatabase.data.columns.find( + (c) => c.systemName == "type" + ); + $scope.lstMetadata = typeCol.columnConfigurations.allowedValues; + $scope.$apply(); }; - $scope.updateJobData = function (content) { - try { - $scope.schedule.jobData = JSON.parse(content); - $scope.$apply(); - } catch {} - }; - $scope.pauseTrigger = async function (name) { - $rootScope.isBusy = true; - var resp = await service.pauseTrigger(name); - if (resp && resp.success) { - $scope.schedule = resp.data; - await $scope.getTriggers(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors || ["Failed"]); + $scope.loadAdditionalDatabases = async function () { + let getTypes = await databaseService.getList($scope.postTypeRequest); + if (getTypes.success) { + $scope.additionalDatabases = getTypes.data.items; + $scope.additionalDatabases.splice(0, 0, { + systemName: null, + displayName: "All", + id: 0, + }); + if ($scope.request.mixDatabaseName) { + $scope.additionalDatabase = $rootScope.findObjectByKey( + $scope.additionalDatabases, + "mixDatabaseName", + $scope.request.mixDatabaseName + ); } - $rootScope.isBusy = false; + $scope.request.mixDatabaseName = $routeParams.type || ""; $scope.$apply(); } }; - - $scope.resumeTrigger = async function (name) { + $scope.getDefault = async function (type = null) { $rootScope.isBusy = true; - var resp = await service.resumeTrigger(name); - if (resp && resp.success) { - $scope.schedule = resp.data; - await $scope.getTriggers(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors || ["Failed"]); + type = type || $routeParams.type; + var resp = await service.getDefault({ + type: type || "", + template: $routeParams.template || "", + }); + if (resp.success) { + $scope.viewmodel = resp.data; + mixDbService.initDbName($scope.viewmodel.mixDatabaseName); + if ($scope.getSingleSuccessCallback) { + $scope.getSingleSuccessCallback(); } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.getTriggers = async function () { - $rootScope.isBusy = true; - var resp = await service.getTriggers(); - if (resp && resp.success) { - $scope.data = resp.data; + // $scope.viewmodel.createdDateTime = Date.now(); + $scope.viewmodel.createdBy = $rootScope.authentication.username; + $rootScope.isBusy = false; $scope.$apply(); } else { if (resp) { - $rootScope.showErrors(resp.errors || ["Failed"]); + $rootScope.showErrors(resp.errors); + } + if ($scope.getSingleFailCallback) { + $scope.getSingleFailCallback(); } $rootScope.isBusy = false; $scope.$apply(); } }; - $scope.getJobs = async function () { - $rootScope.isBusy = true; - var resp = await service.getJobs(); + $scope.preview = function (item) { + item.editUrl = "/admin/post/details/" + item.id; + $rootScope.preview("post", item, item.title, "modal-lg"); + }; + $scope.onSelectType = function () { + if ($scope.viewmodel) { + $scope.viewmodel.mixDatabaseName = $scope.additionalDatabase.systemName; + mixDbService.initDbName($scope.viewmodel.mixDatabaseName); + $scope.loadAdditionalData(); + } + $scope.request.additionalDatabase = + $scope.additionalDatabase.mixDatabaseName; + $scope.createUrl = `/admin/post/create?type=${$scope.request.additionalDatabase}`; + if ($routeParams.template) { + $scope.createUrl += `&template=${$routeParams.template}`; + } + if ( + $scope.additionalDatabase.mixDatabaseName && + (!$scope.viewmodel || !$scope.viewmodel.id) + ) { + $scope.getDefault($scope.request.additionalDatabase); + } + if ($scope.pageName == "postList") { + $scope.filter(); + } + }; + $scope.getListRelated = async function (pageIndex) { + if (pageIndex !== undefined) { + $scope.request.pageIndex = pageIndex; + } + if ($scope.request.fromDate !== null) { + var d = new Date($scope.request.fromDate); + $scope.request.fromDate = d.toISOString(); + } + if ($scope.request.toDate !== null) { + var d = new Date($scope.request.toDate); + $scope.request.toDate = d.toISOString(); + } + var resp = await service.filter($scope.request); if (resp && resp.success) { - $scope.jobs = resp.data; + $scope.relatedData = angular.copy(resp.data); + $scope.relatedData.items = []; + angular.forEach(resp.data.items, (element) => { + let isActive = + null != + $scope.viewmodel.postNavs.find( + (p) => p.destinationId == element.id + ); + if (!isActive) { + var obj = { + description: element.title, + destinationId: element.id, + image: element.image, + isActived: isActive, + sourceId: $scope.viewmodel.id, + specificulture: $scope.viewmodel.specificulture, + status: "Published", + }; + result.push(obj); + } + }); + resp.data.items = result; $rootScope.isBusy = false; $scope.$apply(); + return resp.data; } else { - if (resp) { - $rootScope.showErrors(resp.errors || ["Failed"]); - } + $rootScope.showErrors(getData.errors); $rootScope.isBusy = false; $scope.$apply(); } }; - $scope.deleteJob = async function (name) { - $rootScope.isBusy = true; - var resp = await service.deleteJob(name); - if (resp && resp.success) { - $scope.getJobs(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors || ["Failed"]); + $scope.saveFailCallback = function () { + angular.forEach($scope.viewmodel.mixDatabaseNavs, function (nav) { + if (nav.isActived) { + $rootScope.decryptMixDatabase( + nav.mixDatabase.attributes, + nav.mixDatabase.postData.items + ); } - $rootScope.isBusy = false; - $scope.$apply(); + }); + }; + $scope.saveSuccessCallback = async function () { + if ($scope.additionalData && $scope.viewmodel.mixDatabaseName) { + var creating = !$scope.additionalData.parentId; + $scope.additionalData.parentType = "Post"; + $scope.additionalData.parentId = $scope.viewmodel.id; + mixDbService.initDbName($scope.viewmodel.mixDatabaseName); + var saveResult = await mixDbService.save($scope.additionalData); + if (saveResult.success) { + $rootScope.showMessage("Additional Data Saved", "success"); + $scope.additionalData = saveResult.data; + if (creating) { + $location.url(`/admin/post/details/${$scope.viewmodel.id}`); + } + } else { + $rootScope.showErrors(result.errors); + } + // $scope.additionalData.isClone = $scope.viewmodel.isClone; + // $scope.additionalData.cultures = $scope.viewmodel.cultures; + // $scope.additionalData.intParentId = $scope.viewmodel.id; + // $scope.additionalData.parentType = "Post"; + // let result = await dataService.save($scope.additionalData); + // if (!result.success) { + // $rootScope.showErrors(result.errors); + // } else { + // $scope.additionalData = result.data; + // // $scope.saveColumns(); + // } } + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); }; - }, -]); -"use strict"; -app.factory("SchedulerService", [ - "AuthService", - "ApiService", - function (authService, apiService) { - var serviceFactory = {}; - serviceFactory.prefixUrl = "/scheduler"; - var _createSchedule = async function (schedule) { - var url = `${this.prefixUrl}/trigger/create`; - var req = { - serviceBase: this.serviceBase, - method: "POST", - url: url, - data: JSON.stringify(schedule), - }; - return await this.getRestApiResult(req); - }; - var _reschedule = async function (schedule) { - var url = `${this.prefixUrl}/reschedule`; - var req = { - serviceBase: this.serviceBase, - method: "POST", - url: url, - data: JSON.stringify(schedule), - }; - return await this.getRestApiResult(req); - }; - var _execute = async function (name) { - var url = `${this.prefixUrl}/execute/${name}`; - var req = { - serviceBase: this.serviceBase, - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); - }; - var _pauseTrigger = async function (name) { - var url = `${this.prefixUrl}/trigger/pause/${name}`; - var req = { - serviceBase: this.serviceBase, - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); + $scope.saveColumns = async function () { + let result = await columnService.saveMany($scope.additionalData.columns); + if (result.success) { + $rootScope.showMessage("success", "success"); + } }; + $scope.getSingleSuccessCallback = async function () { + if (!$scope.viewmodel.id) { + $scope.viewmodel.mixDatabaseName = $routeParams.type; + } + mixDbService.initDbName($scope.viewmodel.mixDatabaseName); + await $scope.loadMetadataDatabase(); + // $scope.defaultThumbnailImgWidth = + // ngAppSettings.mixConfigurations.DefaultThumbnailImgWidth; + // $scope.defaultThumbnailImgHeight = + // ngAppSettings.mixConfigurations.DefaultThumbnailImgHeight; - var _resumeTrigger = async function (name) { - var url = `${this.prefixUrl}/trigger/resume/${name}`; - var req = { - serviceBase: this.serviceBase, - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); + // $scope.defaultFeatureImgWidth = + // ngAppSettings.mixConfigurations.DefaultFeatureImgWidth; + // $scope.defaultFeatureImgHeight = + // ngAppSettings.mixConfigurations.DefaultFeatureImgHeight; + $scope.request.additionalDatabase = $scope.viewmodel.mixDatabaseName; + var moduleIds = $routeParams.moduleIds; + var pageIds = $routeParams.page_ids; + $scope.additionalDatabase = $rootScope.findObjectByKey( + $scope.additionalDatabases, + "systemName", + $scope.request.additionalDatabase + ); + $scope.loadAdditionalData(); + if (moduleIds) { + for (var moduleContentId of moduleIds.split(",")) { + var moduleNav = $rootScope.findObjectByKey( + $scope.viewmodel.modules, + "moduleContentId", + moduleContentId + ); + if (moduleNav) { + moduleNav.isActived = true; + } + } + } + if (pageIds) { + for (var pageId of pageIds.split(",")) { + var pageNav = $rootScope.findObjectByKey( + $scope.viewmodel.pages, + "pageId", + pageId + ); + if (pageNav) { + pageNav.isActived = true; + } + } + } }; - - var _getTrigger = async function (name) { - var url = `${this.prefixUrl}/trigger/${name}`; - var req = { - serviceBase: this.serviceBase, - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); + $scope.loadAdditionalData = async function () { + if ($scope.viewmodel.mixDatabaseName) { + $scope.loadingData = true; + mixDbService.initDbName($scope.viewmodel.mixDatabaseName); + if ($scope.viewmodel.id) { + const getData = await mixDbService.getSingleByParent( + "Post", + $scope.viewmodel.id + ); + if (getData.success) { + $scope.additionalData = getData.data; + $scope.loadingData = false; + } + $scope.$apply(); + } else { + $scope.additionalData = { + parentType: "Post", + }; + $scope.loadingData = false; + } + } + }; + $scope.generateSeo = function () { + if ($scope.viewmodel) { + if ( + $scope.viewmodel.seoName === null || + $scope.viewmodel.seoName === "" + ) { + $scope.viewmodel.seoName = $rootScope.generateKeyword( + $scope.viewmodel.title, + "-" + ); + if ($scope.viewmodel.seoName.length > 50) { + $scope.viewmodel.seoName = + $scope.viewmodel.seoName.substring(0, 80) + "..."; + } + } + if ( + $scope.viewmodel.seoTitle === null || + $scope.viewmodel.seoTitle === "" + ) { + $scope.viewmodel.seoTitle = $scope.viewmodel.title; + } + if ( + $scope.viewmodel.seoDescription === null || + $scope.viewmodel.seoDescription === "" + ) { + $scope.viewmodel.seoDescription = $scope.viewmodel.excerpt; + } + if ( + $scope.viewmodel.seoKeywords === null || + $scope.viewmodel.seoKeywords === "" + ) { + $scope.viewmodel.seoKeywords = $scope.viewmodel.title; + } + } + }; + $scope.addAlias = async function () { + var getAlias = await urlAliasService.getDefault(); + if (getAlias.success) { + $scope.viewmodel.urlAliases.push(getAlias.data); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(getAlias.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.removeAliasCallback = async function (index) { + $scope.viewmodel.urlAliases.splice(index, 1); + $scope.$apply(); }; - var _getTriggers = async function () { - var url = `${this.prefixUrl}/trigger`; - var req = { - serviceBase: this.serviceBase, - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); + $scope.validate = function () { + angular.forEach($scope.viewmodel.mixDatabaseNavs, function (nav) { + if (nav.isActived) { + $rootScope.encryptMixDatabase( + nav.mixDatabase.attributes, + nav.mixDatabase.postData.items + ); + } + }); + return true; }; - var _getJobs = async function () { - var url = `${this.prefixUrl}/job`; + }, +]); + +"use strict"; +app.factory("PostRestService", [ + "BaseRestService", + "ApiService", + function (baseService, apiService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("mix-post-content"); + var _syncProducts = async function (names) { + var url = `/api/daphale/sync/products`; var req = { - serviceBase: this.serviceBase, - method: "GET", + serviceBase: "", + method: "POST", url: url, + data: { + batch: 50, + isScaleImage: true, + isSyncPrice: true, + isSyncAll: false, + productNames: names, + }, }; - return await this.getRestApiResult(req); + return await apiService.sendPureRequest(req); }; - - var _deleteJob = async function (name) { - var url = `${this.prefixUrl}/job/${name}`; + var _filter = async function (request) { + var url = `${this.prefixUrl}/filter`; var req = { serviceBase: this.serviceBase, - method: "DELETE", + method: "POST", url: url, + data: request, }; return await this.getRestApiResult(req); }; - - var _getRestApiResult = async function (req) { - if (!authService.authentication) { - await authService.fillAuthData(); - } - if (authService.authentication) { - req.Authorization = authService.authentication.accessToken; - } - if (!req.headers) { - req.headers = { - "Content-Type": "application/json", - }; - } - req.headers.Authorization = "Bearer " + req.Authorization || ""; - - return apiService.sendRequest(req).then(function (resp) { - return resp; - }); - }; - var _parseQuery = function (req) { - var result = ""; - if (req) { - for (var key in req) { - if (angular.isObject(req.query)) { - req.query = JSON.stringify(req.query); - } - if (req.hasOwnProperty(key) && req[key]) { - if (result != "") { - result += "&"; - } - result += `${key}=${req[key]}`; - } - } - return result; - } else { - return result; - } - }; - serviceFactory.execute = _execute; - serviceFactory.parseQuery = _parseQuery; - serviceFactory.getRestApiResult = _getRestApiResult; - serviceFactory.createSchedule = _createSchedule; - serviceFactory.reschedule = _reschedule; - serviceFactory.getJobs = _getJobs; - serviceFactory.deleteJob = _deleteJob; - serviceFactory.getTrigger = _getTrigger; - serviceFactory.getTriggers = _getTriggers; - serviceFactory.pauseTrigger = _pauseTrigger; - serviceFactory.resumeTrigger = _resumeTrigger; + // Define more service methods here + serviceFactory.filter = _filter; + serviceFactory.syncProducts = _syncProducts; return serviceFactory; }, ]); "use strict"; -app.controller("SocialFeedController", [ - "$rootScope", - "$scope", - "$http", - "PostRestService", - function ($rootScope, $scope, $http, postService) { - $scope.types = ["Facebook", "Instagram"]; - $scope.isInit = false; - $scope.defaultPost = null; - $scope.defaultProperty = { - name: null, - dataType: 7, - value: "", - }; - $scope.data = []; - $scope.errors = []; - $scope.socialSettings = { - app_id: null, - page_id: null, - app_secret: null, - access_token: "", - page: [], - data: [], - posts: [], - show_login: true, - errors: [], - }; - $scope.init = async function () { - window.fbAsyncInit = function () { - FB.init({ - appId: $rootScope.getConfiguration("FacebookAppId"), - autoLogAppEvents: true, - xfbml: true, - version: "v3.2", - }); - }; - $scope.socialSettings = { - app_id: $rootScope.mixConfigurations.data.FacebookAppId, - page_id: $rootScope.mixConfigurations.data.Facebook_Page_Id, - app_secret: $rootScope.mixConfigurations.data.FacebookAppSecret, - access_token: $rootScope.mixConfigurations.data.FacebookAccessToken, - show_login: true, - errors: [], - }; - if ($scope.socialSettings.access_token) { - $scope.socialSettings.show_login = false; - $scope.loadPages(); - } - postService.getSingle(["portal"]).then((resp) => { - $scope.defaultPost = resp.data; - }); - }; - - // This function is called when someone finishes with the Login - // Button. See the onlogin handler attached to it in the sample - // code below. - $scope.login = function () { - FB.login( - function (response) { - // handle the response - $scope.statusChangeCallback(response); - }, - { - scope: "email, manage_pages", - return_scopes: true, - } - ); - }; - - $scope.statusChangeCallback = function (response) { - // The response object is returned with a status column that lets the - // app know the current login status of the person. - // Full docs on the response object can be found in the documentation - // for FB.getLoginStatus(). - if (response.status === "connected") { - // Logged into your app and Facebook. - $scope.exchangeToken(response); - $scope.loadPages(); - //window.location = '/bo/feed?code=' + response.authResponse.accessToken; - } else { - $scope.socialSettings.show_login = true; - $scope.$apply(); - // The person is not logged into your app or we are unable to tell. - } - }; - - $scope.exchangeToken = function (response) { - var url = - "/oauth/access_token?grant_type=fb_exchange_token&client_id=" + - $scope.socialSettings.app_id + - "&client_secret=" + - $scope.socialSettings.app_secret + - "&fb_exchange_token=" + - response.authResponse.accessToken; - FB.api(url, function (response) { - if (response.access_token) { - $scope.socialSettings.access_token = response.access_token; - } else { - $scope.show_login = true; - $scope.socialSettings.errors = response; - $scope.$apply(); - } - }); - }; - $scope.loadFeeds = function (url) { - $scope.socialSettings.errors = ""; - $scope.socialSettings.posts = []; - url = - url || - "/" + - $scope.socialSettings.page_id + - "/posts?access_token=" + - $scope.socialSettings.access_token + - "&columns=type,name,story,full_picture,created_time,permalink_url,message,description,caption,attachments{media,type,target,subattachments},shares.summary(true).limit(0),likes.summary(true).limit(0),comments.summary(true).limit(0)&limit=10"; - $rootScope.isBusy = true; - FB.api(url, function (response) { - if (response.data) { - $scope.socialSettings.data = response.data; - angular.forEach(response.data, function (e, i) { - var post = $scope.parsePost(e); - $scope.socialSettings.posts.push(post); - }); - if (response.paging) { - $scope.socialSettings.nextUrl = response.paging.next; - $scope.socialSettings.prevUrl = response.paging.previous; - } - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $scope.socialSettings.show_login = true; - $rootScope.isBusy = false; - $scope.socialSettings.errors = response; - $scope.$apply(); - } - }); - }; - $scope.loadPages = function () { - $scope.socialSettings.errors = ""; - var url = - "/me/accounts?access_token=" + - $scope.socialSettings.access_token + - "&columns=id,name"; - FB.api(url, function (response) { - if (response.data) { - $scope.socialSettings.pages = response.data; - $scope.$apply(); - } else { - $scope.socialSettings.show_login = true; - $scope.socialSettings.errors = response; - } - }); - }; - $scope.setAttr = function (e, attrName, attVal) { - $(e).attr(attrName, attVal); - }; - $scope.parsePost = function (post) { - var post = angular.copy($scope.defaultPost); - var prop = angular.copy($scope.defaultProperty); - post.title = "Facebook Id"; - post.name = "facebook_id"; - post.value = post.id; - post.properties.push(prop); - - post.title = post.name || post.id; - post.excerpt = post.message; - post.content = post.description; - post.source = "Facebook"; - post.image = post.full_picture; - post.detailUrl = post.permalink_url; - var attachments = post.attachments.data[0]; - - if (attachments.media) { - var media = $scope.parseMedia(attachments.media, attachments.type); - if (media) { - post.mediaNavs.push({ - media: media, - specificulture: $rootScope.mixConfigurations.lang, - image: media.fullPath, - }); - } - } - - if (attachments.subattachments) { - var medias = $scope.parseMedias(attachments.subattachments.data); - angular.forEach(medias, function (e, i) { - post.mediaNavs.push({ - media: e, - specificulture: $rootScope.mixConfigurations.lang, - image: e.fullPath, - }); - }); - } - return post; - }; - $scope.parseMedias = function (data) { - var result = []; - if (data) { - angular.forEach(data, function (e, i) { - var media = $scope.parseMedia(e.media, e.type); - if (media) { - result.push(media); - } - }); - } - return result; - }; - $scope.parseMedia = function (media, type) { - if (media) { - var src = ""; - switch (type) { - case "video_autoplay": - src = media.source; - break; - case "profile_media": - case "photo": - default: - src = media.image.src; - break; - } - try { - if (src) { - var index = src.lastIndexOf("/"); - var ext = src.match(/.(?:jpg|gif|png|gif|jpeg|mp4)/)[0]; - // if valid file - if (ext) { - var eIndex = src.indexOf(ext); - var filename = src.substring(index + 1, eIndex); - var media = { - fileName: filename, - fileFolder: "Facebook", - extension: ext, - targetUrl: src, - fullPath: src, - fileType: type, - source: "Facebook", - }; - - return media; - } else { - return null; - } - } else { - return null; - } - } catch (err) { - console.log("Cannot parse media", media); - return null; - } - } - }; - $scope.syncPosts = async function () { - $rootScope.isBusy = true; - var resp = await postService.saveList($scope.socialSettings.posts); - if (resp && resp.success) { - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - }, -]); - -"use strict"; -app.controller("ServiceController", [ +app.controller("QueueLogController", [ "$scope", "$rootScope", "ngAppSettings", - "$routeParams", "$location", - "RestMixDatabasePortalService", - "ApiService", - "CommonService", + "$routeParams", + "AuthService", + "QueueLogRestService", function ( $scope, $rootScope, ngAppSettings, - $routeParams, $location, - service, - commonService + $routeParams, + authService, + service ) { - BaseODataCtrl.call( + BaseRestCtrl.call( this, $scope, $rootScope, + $location, $routeParams, ngAppSettings, service ); - $scope.defaultId = "default"; - $scope.parentId = null; + authService.fillAuthData(); + $scope.request.status = null; + $scope.messages = []; + $scope.canDrag = + $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; + $scope.getListSuccessCallback = function () { + angular.forEach($scope.data.items, function (e) { + switch (e.state) { + case "ACK": + e.objClass = "text-success"; + break; + case "NACK": + e.objClass = "text-warning"; + break; + case "FAILED": + e.objClass = "text-danger"; + break; + default: + e.objClass = "text-info"; + break; + } + }); + }; + $scope.view = function (item) { + switch (item.state) { + case "ACK": + item.objClass = "text-success"; + break; + case "NACK": + item.objClass = "text-warning"; + break; + case "FAILED": + item.objClass = "text-danger"; + break; + default: + item.objClass = "text-info"; + break; + } + $rootScope.preview("object", item, null, "modal-lg"); + }; + }, +]); + +"use strict"; +app.factory("QueueLogRestService", [ + "BaseRestService", + function (baseService) { + var serviceFactory = angular.copy(baseService); + serviceFactory.initService("/rest", "mix-log/queue-log", true); + var _search = async function (objData, queries = null) { + var data = serviceFactory.parseQuery(objData); + + var url = `${this.prefixUrl}/search`; + + if (data) { + url += "?"; + url = url.concat(data); + if (queries) { + url += "&"; + var extraQueries = serviceFactory.parseQuery(queries); + url = url.concat(extraQueries); + } + } + var req = { + serviceBase: this.serviceBase, + apiVersion: this.apiVersion, + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); + }; + serviceFactory.getList = _search; + return serviceFactory; + }, +]); + +"use strict"; +app.controller("RoleController", [ + "$scope", + "$rootScope", + "$location", + "$routeParams", + "ngAppSettings", + "RestMixDatabaseDataPortalService", + "RestMixDatabaseColumnPortalService", + "RoleService", + function ( + $scope, + $rootScope, + $location, + $routeParams, + ngAppSettings, + dataService, + columnService, + service + ) { + BaseRestCtrl.call( + this, + $scope, + $rootScope, + $location, + $routeParams, + ngAppSettings, + service + ); + $scope.role = { name: "" }; + $scope.initPermissions = async function () { + let backUrl = "/admin/role/list"; + $scope.createUrl = `/admin/mix-database-data/create?mixDatabaseName=sysPermission&dataContentId=default&guidParentId=${$scope.viewmodel.id}&parentType=Role&backUrl=${backUrl}`; + $scope.updateUrl = "/admin/mix-database-data/details"; + }; + + $scope.createRole = async function () { + $rootScope.isBusy = true; + var result = await service.createRole($scope.role.name); + if (result.success) { + $scope.role.name = ""; + $scope.getList(); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + }, +]); + +"use strict"; +app.factory("RoleService", [ + "BaseRestService", + "ApiService", + "CommonService", + function (baseService, apiService, commonService) { + var serviceFactory = Object.create(baseService); + serviceFactory.initService("/rest/mix-account", "role", true); + + var _getPermissions = async function () { + var req = { + method: "GET", + url: this.prefixUrl + "/permissions", + }; + return await apiService.sendRequest(req); + }; + + var _updatePermission = async function (permission) { + var req = { + method: "POST", + url: this.prefixUrl + "/update-permission", + data: JSON.stringify(permission), + }; + return await apiService.sendRequest(req); + }; + var _createRole = function (name) { + var req = { + method: "POST", + url: this.prefixUrl + "/create", + data: JSON.stringify(name), + }; + + return apiService.sendRequest(req); + }; + serviceFactory.createRole = _createRole; + serviceFactory.getPermissions = _getPermissions; + serviceFactory.updatePermission = _updatePermission; + return serviceFactory; + }, +]); + +"use strict"; +app.controller("ServiceController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$routeParams", + "$location", + "RestMixDatabasePortalService", + "ApiService", + "CommonService", + function ( + $scope, + $rootScope, + ngAppSettings, + $routeParams, + $location, + service, + commonService + ) { + BaseODataCtrl.call( + this, + $scope, + $rootScope, + $routeParams, + ngAppSettings, + service + ); + $scope.defaultId = "default"; + $scope.parentId = null; $scope.parentType = null; $scope.cates = ["Site", "System"]; $scope.others = []; @@ -5671,790 +5033,630 @@ app.controller("ServiceController", [ ]); "use strict"; -app.controller("TemplateController", [ +app.controller("SchedulerController", [ "$scope", "$rootScope", "$routeParams", "$location", - "ngAppSettings", - "AuthService", - "TemplateService", - function ( - $scope, - $rootScope, - $routeParams, - $location, - ngAppSettings, - authService, - service - ) { - BaseRestCtrl.call( - this, - $scope, - $rootScope, - $location, - $routeParams, - ngAppSettings, - service - ); - BaseHub.call(this, $scope); - $scope.folderTypes = [ - "Masters", - "Layouts", - "Pages", - "Modules", - "Forms", - "Edms", - "Products", - "Posts", - "Widgets", + "SchedulerService", + function ($scope, $rootScope, $routeParams, $location, service) { + $scope.jobs = []; + $scope.intervalTypes = [ + "Second", + "Minute", + "Hour", + "Day", + "Week", + "Month", + "Year", ]; - $scope.isInitHub = false; - $scope.room = null; - $scope.members = []; - $scope.activedPane = null; - $scope.canRename = true; - $scope.user = null; - $scope.selectPane = function (pane) { - $scope.activedPane = pane; - }; - $scope.init = async function () { - authService.fillAuthData().then(function () { - $scope.user = { - username: authService.authentication.info.username, - avatar: authService.authentication.info.avatar, - }; - $scope.canEdit = true; - // $scope.startConnection("editFileHub", () => { - // let id = $routeParams.id || $rootScope.generateUUID(); - // $scope.room = `Template-${id}`; - // $scope.joinRoom(); - // }); - }); + $scope.templates = { + "Mix.Scheduler.Jobs.KeepPoolAliveJob": { + domain: "https://example.com", + }, + "Mix.Scheduler.Jobs.PublishScheduledPostsJob": {}, + "Mix.Scheduler.Jobs.SendMessageQueueJob": { + data: { + topic: "", + action: "", + data: {}, + }, + }, + "Mix.Scheduler.Jobs.SendPortalMessageJob": { + data: { + topic: "", + action: "", + data: "", + }, + }, }; - $scope.validate = function () { - $scope.viewmodel.displayName = $scope.viewmodel.fileName; - $scope.viewmodel.extension = ".cshtml"; - return true; + $scope.schedule = { + jobData: { + data: { + type: "Info", + from: { + connectionId: "", + userName: "", + avatar: "", + }, + title: "value", + message: "content", + data: {}, + }, + }, + cronExpression: null, + name: null, + groupName: null, + jobName: null, + description: null, + startAt: null, + isStartNow: true, + interval: null, + intervalType: "Second", + repeatCount: null, }; - $scope.loadFolder = function (d) { - $location.url( - "/admin/template/list/" + - $routeParams.themeId + - "?folderType=" + - encodeURIComponent(d) - ); + $scope.updateMessageTemplate = () => { + $scope.schedule.jobData = null; + setTimeout(() => { + $scope.schedule.jobData = $scope.templates[$scope.schedule.jobName]; + $scope.$apply(); + }, 200); }; - $scope.loadParams = async function () { - $rootScope.isBusy = true; - $scope.themeId = $routeParams.themeId; - $scope.folderType = $routeParams.folderType; + $scope.init = function () { + $scope.getTriggers(); + $scope.getJobs(); }; + $scope.getSingle = async function () { - $rootScope.isBusy = true; - var id = $routeParams.id; - $scope.folderType = $routeParams.folderType; + $scope.getJobs(); + $scope.getTrigger(); + }; - if (id) { - var resp = await service.getSingle([id], { - folderType: $scope.folderType, - }); - if (resp && resp.success) { - $scope.viewmodel = resp.data; - if (!$scope.viewmodel.content) { - $scope.viewmodel.content = "
"; - } - $scope.listUrl = - "/admin/template/list/" + - $scope.viewmodel.themeId + - "?folderType=" + - encodeURIComponent($scope.viewmodel.folderType); - $scope.canRename = - $scope.viewmodel.id === 0 || - $scope.viewmodel.fileName.indexOf("Copy") === 0; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - } else { - var themeId = $routeParams.themeId; - var resp = await service.getDefault(); + $scope.getTrigger = async function () { + if ($routeParams.name) { + $rootScope.isBusy = true; + $scope.isReschedule = true; + var resp = await service.getTrigger($routeParams.name); if (resp && resp.success) { - resp.data.mixThemeId = themeId; - resp.data.folderType = $scope.folderType; - $scope.viewmodel = resp.data; - if (!$scope.viewmodel.content) { - $scope.viewmodel.content = "
"; + $scope.trigger = resp.data.trigger; + // $scope.schedule.trigger = $scope.trigger; + $scope.schedule.name = $scope.trigger.name; + $scope.schedule.jobName = $scope.trigger.jobName; + $scope.schedule.groupName = $scope.trigger.group; + // $scope.schedule.interval = $scope.trigger.repeatInterval; + $scope.schedule.repeatCount = $scope.trigger.repeatCount; + if ($scope.trigger.jobDataMap) { + if ($scope.trigger.jobDataMap.data) { + $scope.schedule.jobData = { + data: JSON.parse($scope.trigger.jobDataMap.data), + }; + } else { + $scope.schedule.jobData = $scope.trigger.jobDataMap; + } } $rootScope.isBusy = false; $scope.$apply(); } else { if (resp) { - $rootScope.showErrors(resp.errors); + $rootScope.showErrors(resp.errors || ["Failed"]); } $rootScope.isBusy = false; $scope.$apply(); } } }; - $scope.copy = async function (id) { + + $scope.createSchedule = async function () { $rootScope.isBusy = true; - $scope.folderType = $routeParams.folderType; // ? $routeParams.folderType : 'Masters'; - var themeId = $routeParams.themeId; - $scope.listUrl = - "/admin/template/list/" + - themeId + - "?folderType=" + - encodeURIComponent($scope.folderType); - var resp = await service.copy(id); + var resp = $scope.isReschedule + ? await service.reschedule($scope.schedule) + : await service.createSchedule($scope.schedule); if (resp && resp.success) { - $location.url( - `/admin/template/details/${$scope.folderType}/${resp.data.id}` - ); + $rootScope.isBusy = true; + $location.url("/admin/scheduler"); $scope.$apply(); } else { if (resp) { - $rootScope.showErrors(resp.errors); + $rootScope.showErrors(resp.errors || ["Failed"]); } $rootScope.isBusy = false; $scope.$apply(); } }; - $scope.getList = async function (pageIndex, themeId) { - $scope.request.themeId = themeId || $routeParams.themeId; - $scope.request.folderType = $routeParams.folderType; - $scope.request.status = null; - $scope.folderType = $routeParams.folderType; - if ($scope.folderType) { - if (pageIndex !== undefined) { - $scope.request.pageIndex = pageIndex; - } - if ($scope.request.fromDate !== null) { - var df = new Date($scope.request.fromDate); - $scope.request.fromDate = df.toISOString(); - } - if ($scope.request.toDate !== null) { - var dt = new Date($scope.request.toDate); - $scope.request.toDate = dt.toISOString(); - } - var resp = await service.getList($scope.request, [$scope.themeId]); - if (resp && resp.success) { - $scope.data = resp.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - } else { + $scope.execute = async function (name) { + try { + $rootScope.isBusy = true; + await service.execute(name); $rootScope.isBusy = false; - } - }; - $scope.updateTemplateContent = function (content) { - $scope.viewmodel.content = content; - }; - $scope.updateStyleContent = function (content) { - $scope.viewmodel.scripts = content; + $scope.$apply(); + } catch {} }; - $scope.updateScriptContent = function (content) { - $scope.viewmodel.styles = content; + $scope.updateJobData = function (content) { + try { + $scope.schedule.jobData = JSON.parse(content); + $scope.$apply(); + } catch {} }; - $scope.joinRoom = function () { - $scope.connection.invoke("JoinRoom", $scope.room, $scope.user); + $scope.pauseTrigger = async function (name) { + $rootScope.isBusy = true; + var resp = await service.pauseTrigger(name); + if (resp && resp.success) { + $scope.schedule = resp.data; + await $scope.getTriggers(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors || ["Failed"]); + } + $rootScope.isBusy = false; + $scope.$apply(); + } }; - $scope.receiveMessage = function (msg) { - switch (msg.type) { - case "MemberList": - $scope.members = msg.data; - $scope.initMembersData(); - $scope.canEdit = $scope.members.length == 1; - if (!$scope.canEdit) { - $scope.errors = [ - "Cannot modify if there is another user opening this template", - ]; - } else { - $scope.errors = []; - } - $scope.$apply(); - break; - default: - break; + $scope.resumeTrigger = async function (name) { + $rootScope.isBusy = true; + var resp = await service.resumeTrigger(name); + if (resp && resp.success) { + $scope.schedule = resp.data; + await $scope.getTriggers(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors || ["Failed"]); + } + $rootScope.isBusy = false; + $scope.$apply(); } - console.log(msg); - }; - $scope.initMembersData = function () { - angular.forEach($scope.members, function (e) { - if (!e.Avatar) { - e.Avatar = "/mix-app/assets/img/user.png"; - } - }); - }; - }, -]); - -"use strict"; -app.controller("StoreController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "CryptoService", - "ThemeService", - "StoreService", - function ( - $scope, - $rootScope, - ngAppSettings, - cryptoService, - themeService, - service - ) { - }, -]); - -"use strict"; -app.controller("TenantController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$location", - "$routeParams", - "TenantRestService", - function ( - $scope, - $rootScope, - ngAppSettings, - $location, - $routeParams, - service - ) { - BaseRestCtrl.call( - this, - $scope, - $rootScope, - $location, - $routeParams, - ngAppSettings, - service - ); - $scope.request.columns = [ - "id", - "displayName", - "systemName", - "primaryDomain", - "createdDateTime", - "createdBy", - ]; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - }, -]); - -"use strict"; -app.factory("TenantRestService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-tenant"); - return serviceFactory; - }, -]); - -"use strict"; -app.controller("ThemeController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$routeParams", - "$location", - "ThemeService", - "ApiService", - "CommonService", - function ( - $scope, - $rootScope, - ngAppSettings, - $routeParams, - $location, - service, - commonService - ) { - BaseRestCtrl.call( - this, - $scope, - $rootScope, - $location, - $routeParams, - ngAppSettings, - service - ); - $scope.exportData = null; - $scope.exportThemeDto = { - isIncludeAssets: true, - isIncludeTemplates: true, - isIncludeConfigurations: true, - isIncludePermissions: true, - cultureIds: [], - content: { - pageIds: [], - pageContentIds: [], - postIds: [], - postContentIds: [], - moduleIds: [], - moduleContentIds: [], - mixDatabaseIds: [], - }, - associations: { - pageIds: [], - pageContentIds: [], - postIds: [], - postContentIds: [], - moduleIds: [], - moduleContentIds: [], - mixDatabaseIds: [], - }, - }; - - $scope.getSingleSuccessCallback = function () { - $scope.assets = null; - $scope.theme = null; }; - $scope.syncTemplates = async function (id) { + $scope.getTriggers = async function () { $rootScope.isBusy = true; - var response = await service.syncTemplates(id); - if (response.success) { - $scope.viewmodel = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); + var resp = await service.getTriggers(); + if (resp && resp.success) { + $scope.data = resp.data; $rootScope.isBusy = false; $scope.$apply(); - } - }; - $scope.extract = async function () { - $rootScope.isBusy = true; - var frm = new FormData(); - var url = "/rest/mix-tenancy/setup/extract-theme"; - $scope.data.isCreateDefault = $scope.themeType === "materialkit"; - $rootScope.isBusy = true; - // Looping over all files and add it to FormData object - frm.append("theme", theme); - // Adding one more key to FormData object - frm.append("model", angular.toJson($scope.data)); - var response = await service.ajaxSubmitForm(frm, url); - $rootScope.isBusy = false; - if (response.success) { - $rootScope.goToPath("/init/step4"); - $scope.$apply(); } else { - $rootScope.showErrors(response.errors); + if (resp) { + $rootScope.showErrors(resp.errors || ["Failed"]); + } $rootScope.isBusy = false; $scope.$apply(); } }; - $scope.export = async function () { - $scope.exportThemeDto.themeId = $routeParams.id; + $scope.getJobs = async function () { $rootScope.isBusy = true; - var response = await service.export($scope.exportThemeDto); - - if (response.success) { + var resp = await service.getJobs(); + if (resp && resp.success) { + $scope.jobs = resp.data; $rootScope.isBusy = false; - window.open(response.data, "_blank"); $scope.$apply(); } else { - $rootScope.showErrors(response.errors); + if (resp) { + $rootScope.showErrors(resp.errors || ["Failed"]); + } $rootScope.isBusy = false; $scope.$apply(); } }; - $scope.saveSuccessCallback = function () { - apiService.getAllSettings().then(function () { - // $location.path("/admin/theme/list"); - $rootScope.isBusy = false; - $scope.$apply(); - }); - }; - $scope.removeCallback = function () { - apiService.getAllSettings().then(function () { - $location.path("/admin/theme/list"); - }); - }; - - $scope.getExportData = async function () { - var id = $routeParams.id; - var resp = await service.getExportData(id); + $scope.deleteJob = async function (name) { + $rootScope.isBusy = true; + var resp = await service.deleteJob(name); if (resp && resp.success) { - $scope.exportData = resp.data; - $rootScope.isBusy = false; - $scope.$apply(); + $scope.getJobs(); } else { if (resp) { - $rootScope.showErrors(resp.errors); + $rootScope.showErrors(resp.errors || ["Failed"]); } $rootScope.isBusy = false; $scope.$apply(); } }; - - $scope.generateSEO = function () { - $scope.viewmodel.name = $rootScope.generateKeyword( - $scope.viewmodel.title, - "-" - ); - }; }, ]); "use strict"; -app.controller("ThemeImportController", [ - "$scope", - "$rootScope", - "ngAppSettings", - "$routeParams", - "$location", +app.factory("SchedulerService", [ + "AuthService", "ApiService", - "TenancyService", - function ( - $scope, - $rootScope, - ngAppSettings, - $routeParams, - $location, - apiService, - tenancyService - ) { - $scope.importData = null; - $scope.init = function () {}; - $scope.getSingleSuccessCallback = function () { - $scope.assets = null; - $scope.theme = null; + function (authService, apiService) { + var serviceFactory = {}; + serviceFactory.prefixUrl = "/scheduler"; + var _createSchedule = async function (schedule) { + var url = `${this.prefixUrl}/trigger/create`; + var req = { + serviceBase: this.serviceBase, + method: "POST", + url: url, + data: JSON.stringify(schedule), + }; + return await this.getRestApiResult(req); }; - $scope.submit = async function () { - $scope.form = document.getElementById("form-portal"); - let theme = $scope.form["theme"].files[0]; - if (theme) { - await $scope.extract(theme); - document.getElementById("form-portal")["theme"].value = ""; - } else { - $scope.import(); - } + var _reschedule = async function (schedule) { + var url = `${this.prefixUrl}/reschedule`; + var req = { + serviceBase: this.serviceBase, + method: "POST", + url: url, + data: JSON.stringify(schedule), + }; + return await this.getRestApiResult(req); }; - $scope.extract = async function (theme) { - $rootScope.isBusy = true; - var frm = new FormData(); - var url = "/rest/mix-tenancy/setup/extract-theme"; - $rootScope.isBusy = true; - // Looping over all files and add it to FormData object - frm.append("theme", theme); - // Adding one more key to FormData object - frm.append("model", angular.toJson($scope.data)); - var response = await apiService.ajaxSubmitForm(frm, url); - $rootScope.isBusy = false; - if (response.success) { - var getData = await $scope.loadTheme(); - if (getData.success) { - $scope.importThemeDto = getData.data; - $rootScope.isBusy = false; - $scope.$apply(); - } - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } + var _execute = async function (name) { + var url = `${this.prefixUrl}/execute/${name}`; + var req = { + serviceBase: this.serviceBase, + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); }; - - $scope.loadTheme = async function () { + var _pauseTrigger = async function (name) { + var url = `${this.prefixUrl}/trigger/pause/${name}`; var req = { + serviceBase: this.serviceBase, method: "GET", - url: "/rest/mix-tenancy/setup/load-theme", + url: url, }; - return await apiService.sendRequest(req); + return await this.getRestApiResult(req); }; - $scope.import = async function () { - $scope.importThemeDto.themeId = $routeParams.id; - $rootScope.isBusy = true; - var response = await tenancyService.import($scope.importThemeDto); - - if (response.success) { - $rootScope.isBusy = false; - window.open("/", "_blank"); - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } + var _resumeTrigger = async function (name) { + var url = `${this.prefixUrl}/trigger/resume/${name}`; + var req = { + serviceBase: this.serviceBase, + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); }; - }, -]); -"use strict"; -app.controller("UserController", [ - "$scope", - "$rootScope", - "$location", - "ngAppSettings", - "$routeParams", - "AuthService", - "UserServices", - "RestMixDatabaseDataPortalService", - "MixDbService", - function ( - $scope, - $rootScope, - $location, - ngAppSettings, - $routeParams, - authService, - userServices, - dataService, - mixDbService - ) { - $scope.request = { - pageSize: "10", - pageIndex: 0, - status: "Published", - orderBy: "CreatedDateTime", - direction: "Desc", - fromDate: null, - toDate: null, - keyword: "", + var _getTrigger = async function (name) { + var url = `${this.prefixUrl}/trigger/${name}`; + var req = { + serviceBase: this.serviceBase, + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); }; - $scope.mediaFile = { - file: null, - fullPath: "", - folder: "User", - title: "", - description: "", + var _getTriggers = async function () { + var url = `${this.prefixUrl}/trigger`; + var req = { + serviceBase: this.serviceBase, + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); }; - $scope.activedUser = null; - $scope.relatedUsers = []; - $rootScope.isBusy = false; - $scope.data = { - pageIndex: 0, - pageSize: 1, - totalItems: 0, + var _getJobs = async function () { + var url = `${this.prefixUrl}/job`; + var req = { + serviceBase: this.serviceBase, + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); }; - $scope.errors = []; - $scope.range = function (max) { - var input = []; - for (var i = 1; i <= max; i += 1) input.push(i); - return input; + var _deleteJob = async function (name) { + var url = `${this.prefixUrl}/job/${name}`; + var req = { + serviceBase: this.serviceBase, + method: "DELETE", + url: url, + }; + return await this.getRestApiResult(req); }; - $scope.loadUser = async function () { - var id = $routeParams.id; - if (id) { - $rootScope.isBusy = true; - var response = await userServices.getUser(id, "portal"); - if (response.success) { - $scope.activedUser = response.data; - $scope.loadAdditionalData(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } + var _getRestApiResult = async function (req) { + if (!authService.authentication) { + await authService.fillAuthData(); } - }; - $scope.loadAdditionalData = async function () { - mixDbService.initDbName("sysUserData"); - const getData = await mixDbService.getSingleByParent( - "User", - $scope.activedUser.id - ); - if (getData.success) { - $scope.additionalData = getData.data; - if (!$rootScope.isInRole("Owner")) { - $scope.activedUser.roles = $scope.activedUser.roles.filter( - (role) => role.description != "Owner" - ); - } - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $scope.additionalData = {}; - $rootScope.isBusy = false; - $scope.$apply(); + if (authService.authentication) { + req.Authorization = authService.authentication.accessToken; } - }; - $scope.loadMyProfile = async function () { - $rootScope.isBusy = true; - var response = await userServices.getMyProfile(); - if (response.success) { - $scope.activedUser = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); + if (!req.headers) { + req.headers = { + "Content-Type": "application/json", + }; } - }; + req.headers.Authorization = "Bearer " + req.Authorization || ""; - $scope.loadUsers = async function (pageIndex) { - authService.fillAuthData().then(() => { - if ($rootScope.isInRoles(["Owner", "Admin"])) { - $scope.createUrl = "/admin/user/create"; - } + return apiService.sendRequest(req).then(function (resp) { + return resp; }); - - if (pageIndex !== undefined) { - $scope.request.pageIndex = pageIndex; - } - $rootScope.isBusy = true; - var resp = await userServices.getUsers($scope.request); - if (resp && resp.success) { - $scope.data = resp.data; - if (!$rootScope.isInRole("Owner")) { - $scope.data.items = $scope.data.items.filter( - (user) => - user.roles.length == 0 || user.roles[0].role.name != "Owner" - ); - } - $.each($scope.data.items, function (i, user) { - $.each($scope.data, function (i, e) { - if (e.userId === user.id) { - user.isHidden = true; + }; + var _parseQuery = function (req) { + var result = ""; + if (req) { + for (var key in req) { + if (angular.isObject(req.query)) { + req.query = JSON.stringify(req.query); + } + if (req.hasOwnProperty(key) && req[key]) { + if (result != "") { + result += "&"; } - }); - }); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); + result += `${key}=${req[key]}`; + } } - $rootScope.isBusy = false; - $scope.$apply(); + return result; + } else { + return result; } }; + serviceFactory.execute = _execute; + serviceFactory.parseQuery = _parseQuery; + serviceFactory.getRestApiResult = _getRestApiResult; + serviceFactory.createSchedule = _createSchedule; + serviceFactory.reschedule = _reschedule; + serviceFactory.getJobs = _getJobs; + serviceFactory.deleteJob = _deleteJob; + serviceFactory.getTrigger = _getTrigger; + serviceFactory.getTriggers = _getTriggers; + serviceFactory.pauseTrigger = _pauseTrigger; + serviceFactory.resumeTrigger = _resumeTrigger; + return serviceFactory; + }, +]); - $scope.removeUser = function (id) { - $rootScope.showConfirm( - $scope, - "removeUserConfirmed", - [id], - null, - "Remove User", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); +"use strict"; +app.controller("SocialFeedController", [ + "$rootScope", + "$scope", + "$http", + "PostRestService", + function ($rootScope, $scope, $http, postService) { + $scope.types = ["Facebook", "Instagram"]; + $scope.isInit = false; + $scope.defaultPost = null; + $scope.defaultProperty = { + name: null, + dataType: 7, + value: "", }; - - $scope.removeUserConfirmed = async function (id) { - $rootScope.isBusy = true; - var result = await userServices.removeUser(id); - if (result.success) { - $scope.loadUsers(); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); + $scope.data = []; + $scope.errors = []; + $scope.socialSettings = { + app_id: null, + page_id: null, + app_secret: null, + access_token: "", + page: [], + data: [], + posts: [], + show_login: true, + errors: [], + }; + $scope.init = async function () { + window.fbAsyncInit = function () { + FB.init({ + appId: $rootScope.getConfiguration("FacebookAppId"), + autoLogAppEvents: true, + xfbml: true, + version: "v3.2", + }); + }; + $scope.socialSettings = { + app_id: $rootScope.mixConfigurations.data.FacebookAppId, + page_id: $rootScope.mixConfigurations.data.Facebook_Page_Id, + app_secret: $rootScope.mixConfigurations.data.FacebookAppSecret, + access_token: $rootScope.mixConfigurations.data.FacebookAccessToken, + show_login: true, + errors: [], + }; + if ($scope.socialSettings.access_token) { + $scope.socialSettings.show_login = false; + $scope.loadPages(); } + postService.getSingle(["portal"]).then((resp) => { + $scope.defaultPost = resp.data; + }); }; - $scope.save = async function () { - //if (user.avatar !== user.avatarUrl) { - // user.avatar = user.avatarUrl; - //} - $rootScope.isBusy = true; - var resp = await userServices.saveUser($scope.activedUser); - if (resp && resp.success) { - mixDbService.initDbName("sysUserData"); - if ($scope.additionalData) { - $scope.additionalData.parentType = "User"; - $scope.additionalData.parentId = $scope.activedUser.id; - var saveResult = await mixDbService.save($scope.additionalData); - if (saveResult.success) { - $rootScope.showMessage("Additional Data Saved", "success"); - $scope.additionalData = saveResult.data; - } else { - $rootScope.showErrors(result.errors); - } + // This function is called when someone finishes with the Login + // Button. See the onlogin handler attached to it in the sample + // code below. + $scope.login = function () { + FB.login( + function (response) { + // handle the response + $scope.statusChangeCallback(response); + }, + { + scope: "email, manage_pages", + return_scopes: true, } - $rootScope.isBusy = false; + ); + }; - $scope.$apply(); + $scope.statusChangeCallback = function (response) { + // The response object is returned with a status column that lets the + // app know the current login status of the person. + // Full docs on the response object can be found in the documentation + // for FB.getLoginStatus(). + if (response.status === "connected") { + // Logged into your app and Facebook. + $scope.exchangeToken(response); + $scope.loadPages(); + //window.location = '/bo/feed?code=' + response.authResponse.accessToken; } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; + $scope.socialSettings.show_login = true; $scope.$apply(); + // The person is not logged into your app or we are unable to tell. } }; - $scope.saveUserData = async function () { - if ($scope.activedUser.userData) { - $scope.activedUser.userData.parentId = $scope.activedUser.id; - $scope.activedUser.userData.parentType = "User"; - await dataService.save($scope.activedUser.userData); - } + $scope.exchangeToken = function (response) { + var url = + "/oauth/access_token?grant_type=fb_exchange_token&client_id=" + + $scope.socialSettings.app_id + + "&client_secret=" + + $scope.socialSettings.app_secret + + "&fb_exchange_token=" + + response.authResponse.accessToken; + FB.api(url, function (response) { + if (response.access_token) { + $scope.socialSettings.access_token = response.access_token; + } else { + $scope.show_login = true; + $scope.socialSettings.errors = response; + $scope.$apply(); + } + }); }; - - $scope.resendConfirmEmail = async function (id) { - if (id) { - $rootScope.isBusy = true; - var resp = await userServices.resendConfirmEmail(id); - if (resp && resp.success) { - $rootScope.showMessage("Sent mail successfully!", "success"); + $scope.loadFeeds = function (url) { + $scope.socialSettings.errors = ""; + $scope.socialSettings.posts = []; + url = + url || + "/" + + $scope.socialSettings.page_id + + "/posts?access_token=" + + $scope.socialSettings.access_token + + "&columns=type,name,story,full_picture,created_time,permalink_url,message,description,caption,attachments{media,type,target,subattachments},shares.summary(true).limit(0),likes.summary(true).limit(0),comments.summary(true).limit(0)&limit=10"; + $rootScope.isBusy = true; + FB.api(url, function (response) { + if (response.data) { + $scope.socialSettings.data = response.data; + angular.forEach(response.data, function (e, i) { + var post = $scope.parsePost(e); + $scope.socialSettings.posts.push(post); + }); + if (response.paging) { + $scope.socialSettings.nextUrl = response.paging.next; + $scope.socialSettings.prevUrl = response.paging.previous; + } $rootScope.isBusy = false; $scope.$apply(); } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } + $scope.socialSettings.show_login = true; $rootScope.isBusy = false; + $scope.socialSettings.errors = response; $scope.$apply(); } - } + }); + }; + $scope.loadPages = function () { + $scope.socialSettings.errors = ""; + var url = + "/me/accounts?access_token=" + + $scope.socialSettings.access_token + + "&columns=id,name"; + FB.api(url, function (response) { + if (response.data) { + $scope.socialSettings.pages = response.data; + $scope.$apply(); + } else { + $scope.socialSettings.show_login = true; + $scope.socialSettings.errors = response; + } + }); + }; + $scope.setAttr = function (e, attrName, attVal) { + $(e).attr(attrName, attVal); }; + $scope.parsePost = function (post) { + var post = angular.copy($scope.defaultPost); + var prop = angular.copy($scope.defaultProperty); + post.title = "Facebook Id"; + post.name = "facebook_id"; + post.value = post.id; + post.properties.push(prop); - $scope.register = async function (user) { - $rootScope.isBusy = true; - var resp = await userServices.register(user); - if (resp && resp.success) { - $scope.activedUser = resp.data; - $rootScope.showMessage("Update successfully!", "success"); - $rootScope.isBusy = false; - $location.url("/admin/user/list"); - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); + post.title = post.name || post.id; + post.excerpt = post.message; + post.content = post.description; + post.source = "Facebook"; + post.image = post.full_picture; + post.detailUrl = post.permalink_url; + var attachments = post.attachments.data[0]; + + if (attachments.media) { + var media = $scope.parseMedia(attachments.media, attachments.type); + if (media) { + post.mediaNavs.push({ + media: media, + specificulture: $rootScope.mixConfigurations.lang, + image: media.fullPath, + }); } - $rootScope.isBusy = false; - $scope.$apply(); } - }; - $scope.updateRoleStatus = async function (role) { - var userRole = { - userId: $scope.activedUser.id, - roleId: role.id, - roleName: role.name, - isUserInRole: role.isActived, - }; + if (attachments.subattachments) { + var medias = $scope.parseMedias(attachments.subattachments.data); + angular.forEach(medias, function (e, i) { + post.mediaNavs.push({ + media: e, + specificulture: $rootScope.mixConfigurations.lang, + image: e.fullPath, + }); + }); + } + return post; + }; + $scope.parseMedias = function (data) { + var result = []; + if (data) { + angular.forEach(data, function (e, i) { + var media = $scope.parseMedia(e.media, e.type); + if (media) { + result.push(media); + } + }); + } + return result; + }; + $scope.parseMedia = function (media, type) { + if (media) { + var src = ""; + switch (type) { + case "video_autoplay": + src = media.source; + break; + case "profile_media": + case "photo": + default: + src = media.image.src; + break; + } + try { + if (src) { + var index = src.lastIndexOf("/"); + var ext = src.match(/.(?:jpg|gif|png|gif|jpeg|mp4)/)[0]; + // if valid file + if (ext) { + var eIndex = src.indexOf(ext); + var filename = src.substring(index + 1, eIndex); + var media = { + fileName: filename, + fileFolder: "Facebook", + extension: ext, + targetUrl: src, + fullPath: src, + fileType: type, + source: "Facebook", + }; + + return media; + } else { + return null; + } + } else { + return null; + } + } catch (err) { + console.log("Cannot parse media", media); + return null; + } + } + }; + $scope.syncPosts = async function () { $rootScope.isBusy = true; - var resp = await userServices.updateRoleStatus(userRole); + var resp = await postService.saveList($scope.socialSettings.posts); if (resp && resp.success) { - $rootScope.showMessage("Update successfully!", "success"); + $rootScope.showMessage("success", "success"); $rootScope.isBusy = false; - $location.url("/admin/user/list"); $scope.$apply(); } else { if (resp) { @@ -6468,250 +5670,170 @@ app.controller("UserController", [ ]); "use strict"; -app.factory("UserServices", [ - "ApiService", +app.controller("StoreController", [ + "$scope", + "$rootScope", "ngAppSettings", - function (apiService, ngAuthSettings) { - var usersServiceFactory = {}; - var apiUrl = "/rest/mix-account/user"; - - var serviceBase = ngAuthSettings.serviceBase; - - var _resendConfirmEmail = function (id) { - var url = `${apiUrl}/resend-confirm-email/${id}`; - var req = { - method: "GET", - url: serviceBase + url, - }; - - return apiService.sendRequest(req); - }; - var _getUserDemographicInfo = function () { - var url = "/GetUserDemographicInfo"; - var req = { - method: "GET", - url: serviceBase + url, - }; - - return apiService.sendRequest(req); - }; - - var _importUsers = function (strBase64) { - var url = "import-users"; - var req = { - method: "POST", - url: apiUrl + url, - data: JSON.stringify({ strBase64: strBase64 }), - }; - - return apiService.sendRequest(req); - }; - - var _getUsers = function (request) { - var data = _parseQuery(request); - var url = `${apiUrl}/list`; - - if (data) { - url += "?"; - url = url.concat(data); - } - var req = { - method: "GET", - url: url, - data: request, - }; - - return apiService.sendRequest(req); - }; - - var _getUser = async function (id, viewType) { - var url = "/rest/mix-account/user/details"; - if (id) { - url += "/" + id; - } - var req = { - method: "GET", - url: url, - }; - return await apiService.sendRequest(req); - }; - - var _getMyProfile = async function () { - var url = "/rest/mix-account/user/my-profile"; - var req = { - method: "GET", - url: url, - }; - return await apiService.sendRequest(req); - }; - - var _updateRoleStatus = function (userInRole) { - var req = { - method: "POST", - url: serviceBase + "/rest/mix-account/user/user-in-role", - data: JSON.stringify(userInRole), - }; - - return apiService.sendRequest(req); - }; - - var _saveUser = async function (user) { - var apiUrl = "/rest/mix-account/user/save"; - var req = { - method: "POST", - url: apiUrl, - data: JSON.stringify(user), - }; - return await apiService.sendRequest(req); - }; - - var _register = async function (user) { - var apiUrl = "/rest/mix-account/user/"; - var req = { - method: "POST", - url: apiUrl + "register", - data: JSON.stringify(user), - }; - return await apiService.sendRequest(req); - }; - - var _removeUser = function (userId) { - var req = { - method: "DELETE", - url: apiUrl + "/remove-user/" + userId, - }; - - return apiService.sendRequest(req); - }; - - var _parseQuery = function (req) { - var result = ""; - if (req) { - for (var key in req) { - if (angular.isObject(req.query)) { - req.query = JSON.stringify(req.query); - } - if (req.hasOwnProperty(key) && req[key]) { - if (result != "") { - result += "&"; - } - result += `${key}=${req[key]}`; - } - } - return result; - } else { - return result; - } - }; - - usersServiceFactory.importUsers = _importUsers; - usersServiceFactory.getUsers = _getUsers; - usersServiceFactory.getUser = _getUser; - usersServiceFactory.resendConfirmEmail = _resendConfirmEmail; - usersServiceFactory.getMyProfile = _getMyProfile; - usersServiceFactory.saveUser = _saveUser; - usersServiceFactory.register = _register; - usersServiceFactory.removeUser = _removeUser; - usersServiceFactory.updateRoleStatus = _updateRoleStatus; - usersServiceFactory.getUserDemographicInfo = _getUserDemographicInfo; - return usersServiceFactory; + "CryptoService", + "ThemeService", + "StoreService", + function ( + $scope, + $rootScope, + ngAppSettings, + cryptoService, + themeService, + service + ) { }, ]); "use strict"; -app.controller("UrlAliasController", [ +app.controller("TemplateController", [ "$scope", "$rootScope", - "ngAppSettings", "$routeParams", "$location", - "UrlAliasService", - "ApiService", - "CommonService", + "ngAppSettings", + "AuthService", + "TemplateService", function ( $scope, $rootScope, - ngAppSettings, $routeParams, $location, - service, - apiService, - commonService + ngAppSettings, + authService, + service ) { - BaseCtrl.call( + BaseRestCtrl.call( this, $scope, $rootScope, + $location, $routeParams, ngAppSettings, service ); - $scope.cates = ["Site", "System"]; - $scope.others = []; - $scope.mixConfigurations = $rootScope.globalSettings; - $scope.pageId = $routeParams.id; - $scope.canDrag = - $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; - $scope.getList = async function () { - $rootScope.isBusy = true; - var id = $routeParams.id; - $scope.request.query = "&page_id=" + id; - var response = await service.getList($scope.request); - $scope.canDrag = - $scope.request.orderBy !== "Priority" || - $scope.request.direction !== "0"; - if (response.success) { - $scope.data = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } + BaseHub.call(this, $scope); + $scope.folderTypes = [ + "Masters", + "Layouts", + "Pages", + "Modules", + "Forms", + "Edms", + "Products", + "Posts", + "Widgets", + ]; + $scope.isInitHub = false; + $scope.room = null; + $scope.members = []; + $scope.activedPane = null; + $scope.canRename = true; + $scope.user = null; + $scope.selectPane = function (pane) { + $scope.activedPane = pane; }; - $scope.remove = function (id) { - $rootScope.showConfirm( - $scope, - "removeConfirmed", - [id], - null, - "Remove", - "Deleted data will not able to recover, are you sure you want to delete this item?" + $scope.init = async function () { + authService.fillAuthData().then(function () { + $scope.user = { + username: authService.authentication.info.username, + avatar: authService.authentication.info.avatar, + }; + $scope.canEdit = true; + // $scope.startConnection("editFileHub", () => { + // let id = $routeParams.id || $rootScope.generateUUID(); + // $scope.room = `Template-${id}`; + // $scope.joinRoom(); + // }); + }); + }; + $scope.validate = function () { + $scope.viewmodel.displayName = $scope.viewmodel.fileName; + $scope.viewmodel.extension = ".cshtml"; + return true; + }; + $scope.loadFolder = function (d) { + $location.url( + "/admin/template/list/" + + $routeParams.themeId + + "?folderType=" + + encodeURIComponent(d) ); }; - - $scope.removeConfirmed = async function (id) { + $scope.loadParams = async function () { $rootScope.isBusy = true; - var result = await service.delete(id); - if (result.success) { - if ($scope.removeCallback) { - $rootScope.executeFunctionByName( - "removeCallback", - $scope.removeCallbackArgs, - $scope - ); + $scope.themeId = $routeParams.themeId; + $scope.folderType = $routeParams.folderType; + }; + $scope.getSingle = async function () { + $rootScope.isBusy = true; + var id = $routeParams.id; + $scope.folderType = $routeParams.folderType; + + if (id) { + var resp = await service.getSingle([id], { + folderType: $scope.folderType, + }); + if (resp && resp.success) { + $scope.viewmodel = resp.data; + if (!$scope.viewmodel.content) { + $scope.viewmodel.content = "
"; + } + $scope.listUrl = + "/admin/template/list/" + + $scope.viewmodel.themeId + + "?folderType=" + + encodeURIComponent($scope.viewmodel.folderType); + $scope.canRename = + $scope.viewmodel.id === 0 || + $scope.viewmodel.fileName.indexOf("Copy") === 0; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); } - $scope.getList(); } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); + var themeId = $routeParams.themeId; + var resp = await service.getDefault(); + if (resp && resp.success) { + resp.data.mixThemeId = themeId; + resp.data.folderType = $scope.folderType; + $scope.viewmodel = resp.data; + if (!$scope.viewmodel.content) { + $scope.viewmodel.content = "
"; + } + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } } }; - - $scope.updateInfos = async function (index) { - $scope.data.items.splice(index, 1); + $scope.copy = async function (id) { $rootScope.isBusy = true; - var startIndex = $scope.data.items[0].priority - 1; - for (var i = 0; i < $scope.data.items.length; i++) { - $scope.data.items[i].priority = startIndex + i + 1; - } - var resp = await service.updateInfos($scope.data.items); + $scope.folderType = $routeParams.folderType; // ? $routeParams.folderType : 'Masters'; + var themeId = $routeParams.themeId; + $scope.listUrl = + "/admin/template/list/" + + themeId + + "?folderType=" + + encodeURIComponent($scope.folderType); + var resp = await service.copy(id); if (resp && resp.success) { - $scope.activedPage = resp.data; - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; + $location.url( + `/admin/template/details/${$scope.folderType}/${resp.data.id}` + ); $scope.$apply(); } else { if (resp) { @@ -6721,2144 +5843,3021 @@ app.controller("UrlAliasController", [ $scope.$apply(); } }; + $scope.getList = async function (pageIndex, themeId) { + $scope.request.themeId = themeId || $routeParams.themeId; + $scope.request.folderType = $routeParams.folderType; + $scope.request.status = null; + $scope.folderType = $routeParams.folderType; + if ($scope.folderType) { + if (pageIndex !== undefined) { + $scope.request.pageIndex = pageIndex; + } + if ($scope.request.fromDate !== null) { + var df = new Date($scope.request.fromDate); + $scope.request.fromDate = df.toISOString(); + } + if ($scope.request.toDate !== null) { + var dt = new Date($scope.request.toDate); + $scope.request.toDate = dt.toISOString(); + } + var resp = await service.getList($scope.request, [$scope.themeId]); + if (resp && resp.success) { + $scope.data = resp.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + } else { + $rootScope.isBusy = false; + } + }; + $scope.updateTemplateContent = function (content) { + $scope.viewmodel.content = content; + }; + $scope.updateStyleContent = function (content) { + $scope.viewmodel.scripts = content; + }; + $scope.updateScriptContent = function (content) { + $scope.viewmodel.styles = content; + }; + $scope.joinRoom = function () { + $scope.connection.invoke("JoinRoom", $scope.room, $scope.user); + }; + $scope.receiveMessage = function (msg) { + switch (msg.type) { + case "MemberList": + $scope.members = msg.data; + $scope.initMembersData(); + $scope.canEdit = $scope.members.length == 1; + if (!$scope.canEdit) { + $scope.errors = [ + "Cannot modify if there is another user opening this template", + ]; + } else { + $scope.errors = []; + } + $scope.$apply(); + break; + + default: + break; + } + console.log(msg); + }; + $scope.initMembersData = function () { + angular.forEach($scope.members, function (e) { + if (!e.Avatar) { + e.Avatar = "/mix-app/assets/img/user.png"; + } + }); + }; }, ]); "use strict"; -app.factory("UrlAliasService", [ - "$rootScope", - "ApiService", - "CommonService", - "BaseRestService", - function ($rootScope, apiService, commonService, baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.initService("/rest/mix-portal", "mix-url-alias"); - - var _updateInfos = async function (pages) { - var req = { - method: "POST", - url: this.prefixUrl + "/update-infos", - data: JSON.stringify(pages), - }; - return await apiService.sendRequest(req); - }; - serviceFactory.updateInfos = _updateInfos; - return serviceFactory; - }, -]); +app.controller("ThemeController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$routeParams", + "$location", + "ThemeService", + "ApiService", + "CommonService", + function ( + $scope, + $rootScope, + ngAppSettings, + $routeParams, + $location, + service, + commonService + ) { + BaseRestCtrl.call( + this, + $scope, + $rootScope, + $location, + $routeParams, + ngAppSettings, + service + ); + $scope.exportData = null; + $scope.exportThemeDto = { + isIncludeAssets: true, + isIncludeTemplates: true, + isIncludeConfigurations: true, + isIncludePermissions: true, + cultureIds: [], + content: { + pageIds: [], + pageContentIds: [], + postIds: [], + postContentIds: [], + moduleIds: [], + moduleContentIds: [], + mixDatabaseIds: [], + }, + associations: { + pageIds: [], + pageContentIds: [], + postIds: [], + postContentIds: [], + moduleIds: [], + moduleContentIds: [], + mixDatabaseIds: [], + }, + }; -"use strict"; -function PageDetailsController($scope, $element, $attrs) { - var ctrl = this; - ctrl.activedPage = null; - ctrl.relatedPages = []; - ctrl.data = []; - ctrl.errors = []; - ctrl.range = function (max) { - var input = []; - for (var i = 1; i <= max; i += 1) input.push(i); - return input; - }; - ctrl.loadPage = function (pageId) { - ctrl.isBusy = true; - var url = "/" + ctrl.currentLanguage + "/page/details/be/" + pageId; //byPage/' + pageId; - ctrl.mixConfigurations.method = "GET"; - ctrl.mixConfigurations.url = url; // + '/true'; - ctrl.mixConfigurations.data = ctrl.request; - $.ajax(ctrl.mixConfigurations).done(function (response) { + $scope.getSingleSuccessCallback = function () { + $scope.assets = null; + $scope.theme = null; + }; + + $scope.syncTemplates = async function (id) { + $rootScope.isBusy = true; + var response = await service.syncTemplates(id); if (response.success) { - ctrl.activedPage = response.data; - ctrl.initEditor(); + $scope.viewmodel = response.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); } - ctrl.isBusy = false; - ctrl.$apply(); - }); - }; - ctrl.loadPages = function (pageIndex) { - ctrl.isBusy = true; - if (pageIndex !== undefined) { - ctrl.request.pageIndex = pageIndex; - } - if (ctrl.request.fromDate !== null) { - ctrl.request.fromDate = ctrl.request.fromDate.toISOString(); - } - if (ctrl.request.toDate !== null) { - ctrl.request.toDate = ctrl.request.toDate.toISOString(); - } - var url = "/" + ctrl.currentLanguage + "/page/list"; //byPage/' + pageId; - ctrl.mixConfigurations.method = "POST"; - ctrl.mixConfigurations.url = url; // + '/true'; - ctrl.mixConfigurations.data = ctrl.request; - $.ajax(ctrl.mixConfigurations).done(function (response) { - ctrl.data = response.data; + }; + $scope.extract = async function () { + $rootScope.isBusy = true; + var frm = new FormData(); + var url = "/rest/mix-tenancy/setup/extract-theme"; + $scope.data.isCreateDefault = $scope.themeType === "materialkit"; + $rootScope.isBusy = true; + // Looping over all files and add it to FormData object + frm.append("theme", theme); + // Adding one more key to FormData object + frm.append("model", angular.toJson($scope.data)); + var response = await service.ajaxSubmitForm(frm, url); + $rootScope.isBusy = false; + if (response.success) { + $rootScope.goToPath("/init/step4"); + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.export = async function () { + $scope.exportThemeDto.themeId = $routeParams.id; + $rootScope.isBusy = true; + var response = await service.export($scope.exportThemeDto); - $.each(ctrl.data.items, function (i, page) { - $.each(ctrl.activedPages, function (i, e) { - if (e.pageId === page.id) { - page.isHidden = true; - } - }); + if (response.success) { + $rootScope.isBusy = false; + window.open(response.data, "_blank"); + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.saveSuccessCallback = function () { + apiService.getAllSettings().then(function () { + // $location.path("/admin/theme/list"); + $rootScope.isBusy = false; + $scope.$apply(); }); - ctrl.isBusy = false; - setTimeout(function () { - $('[data-bs-toggle="popover"]').popover({ - html: true, - content: function () { - var content = $(this).next(".popover-body"); - return $(content).html(); - }, - title: function () { - var title = $(this).attr("data-popover-content"); - return $(title).children(".popover-heading").html(); - }, - }); - }, 200); - ctrl.$apply(); - }); - }; - - ctrl.removePage = function (pageId) { - if (confirm("Are you sure!")) { - var url = "/" + ctrl.currentLanguage + "/page/delete/" + pageId; - $.ajax({ - method: "GET", - url: url, - success: function (data) { - ctrl.loadPages(); - ctrl.$apply(); - }, - error: function (a, b, c) {}, + }; + $scope.removeCallback = function () { + apiService.getAllSettings().then(function () { + $location.path("/admin/theme/list"); }); - } - }; - ctrl.savePage = function (page) { - var url = "/" + ctrl.currentLanguage + "/page/save"; - $.ajax({ - method: "POST", - url: url, - data: page, - success: function (data) { - //ctrl.loadPages(); - if (data.success) { - alert("success"); - } else { - alert("failed! " + data.errors); - } - }, - error: function (a, b, c) {}, - }); - }; + }; - ctrl.changeMedia = function (media) { - var currentItem = null; - if (ctrl.activedPage.mediaNavs === undefined) { - ctrl.activedPage.mediaNavs = []; - } - $.each(ctrl.activedPage.mediaNavs, function (i, e) { - if (e.mediaId === media.id) { - e.isActived = media.isActived; - currentItem = e; - return false; + $scope.getExportData = async function () { + var id = $routeParams.id; + var resp = await service.getExportData(id); + if (resp && resp.success) { + $scope.exportData = resp.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); } - }); - if (currentItem === null) { - currentItem = { - description: media.description !== "undefined" ? media.description : "", - image: media.fullPath, - mediaId: media.id, - page: ctrl.activedPage.id, - specificulture: media.specificulture, - position: 0, - priority: ctrl.activedMedias.length + 1, - isActived: true, - }; - media.isHidden = true; - ctrl.activedPage.mediaNavs.push(currentItem); - } - }; + }; - ctrl.changePage = function (page) { - var currentItem = null; - $.each(ctrl.activedPage.pageNavs, function (i, e) { - if (e.relatedPageId === page.id) { - e.isActived = page.isActived; - currentItem = e; - return false; - } - }); - if (currentItem === null) { - currentItem = { - relatedPageId: page.id, - sourcePageId: $("#page-id").val(), - specificulture: page.specificulture, - priority: ctrl.activedPage.pageNavs.length + 1, - page: page, - isActived: true, - }; - page.isHidden = true; - ctrl.activedPage.pageNavs.push(currentItem); - } - }; - - ctrl.addProperty = function (type) { - var i = $(".property").length; - $.ajax({ - method: "GET", - url: - "/" + - ctrl.currentLanguage + - "/admin/" + - type + - "/AddEmptyProperty/" + - i, - success: function (data) { - $("#tbl-properties > tbody").append(data); - $(data).find(".prop-data-type").trigger("change"); - }, - error: function (a, b, c) {}, - }); - ctrl.updateHero = function (hero, prop, value) { - hero[prop] = value; - }; - - ctrl.deleteHero = function (hero) { - var idx = ctrl.list.indexOf(hero); - if (idx >= 0) { - ctrl.list.splice(idx, 1); - } + $scope.generateSEO = function () { + $scope.viewmodel.name = $rootScope.generateKeyword( + $scope.viewmodel.title, + "-" + ); }; - }; + }, +]); - angular.module(appName).component("pageDetails", { - templateUrl: "pageDetails.html", - controller: PageDetailsController, - }); -} +"use strict"; +app.controller("TenantController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$location", + "$routeParams", + "TenantRestService", + function ( + $scope, + $rootScope, + ngAppSettings, + $location, + $routeParams, + service + ) { + BaseRestCtrl.call( + this, + $scope, + $rootScope, + $location, + $routeParams, + ngAppSettings, + service + ); + $scope.request.columns = [ + "id", + "displayName", + "systemName", + "primaryDomain", + "createdDateTime", + "createdBy", + ]; + $scope.canDrag = + $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; + }, +]); -modules.component("roleAssociations", { - templateUrl: - "/mix-app/views/app-portal/pages/user/role-associations/view.html", - bindings: { - userRoles: "=", - callback: "&", +"use strict"; +app.factory("TenantRestService", [ + "BaseRestService", + function (baseService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("mix-tenant"); + return serviceFactory; }, - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "$location", - "RoleService", - function ($rootScope, $scope, ngAppSettings, $location, roleService) { - var ctrl = this; - ctrl.selected = null; - ctrl.activedIndex = null; - ctrl.$onInit = async () => { - var getRoles = await roleService.getList(); - if (getRoles.success) { - ctrl.roles = getRoles.data.items; - } - if (!ctrl.userRoles) { - ctrl.userRoles = []; - } - angular.forEach(ctrl.roles, (e) => { - e.isActived = ctrl.userRoles.find((u) => u.roleId == e.id) != null; - }); - }; +]); - ctrl.select = async (obj) => { - if (ctrl.callback) { - ctrl.callback({ role: obj }); +"use strict"; +app.controller("ThemeImportController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$routeParams", + "$location", + "ApiService", + "TenancyService", + function ( + $scope, + $rootScope, + ngAppSettings, + $routeParams, + $location, + apiService, + tenancyService + ) { + $scope.importData = null; + $scope.init = function () {}; + $scope.getSingleSuccessCallback = function () { + $scope.assets = null; + $scope.theme = null; + }; + $scope.submit = async function () { + $scope.form = document.getElementById("form-portal"); + let theme = $scope.form["theme"].files[0]; + if (theme) { + await $scope.extract(theme); + document.getElementById("form-portal")["theme"].value = ""; + } else { + $scope.import(); + } + }; + $scope.extract = async function (theme) { + $rootScope.isBusy = true; + var frm = new FormData(); + var url = "/rest/mix-tenancy/setup/extract-theme"; + $rootScope.isBusy = true; + // Looping over all files and add it to FormData object + frm.append("theme", theme); + // Adding one more key to FormData object + frm.append("model", angular.toJson($scope.data)); + var response = await apiService.ajaxSubmitForm(frm, url); + $rootScope.isBusy = false; + if (response.success) { + var getData = await $scope.loadTheme(); + if (getData.success) { + $scope.importThemeDto = getData.data; + $rootScope.isBusy = false; + $scope.$apply(); } - }; - - ctrl.dragStart = function (index) { - ctrl.dragStartIndex = index; - ctrl.minPriority = ctrl.data[0].priority; - }; - ctrl.goToDetails = async function (nav) { - $location.url(ctrl.detailUrl + nav[ctrl.key]); - }; - }, - ], -}); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; -app.component("appSettingsDefault", { - templateUrl: - "/mix-app/views/app-portal/pages/app-settings/components/default/view.html", - controller: [ - "$rootScope", - "ngAppSettings", - function ($rootScope, ngAppSettings) { - var ctrl = this; - ctrl.$onInit = function () { - ctrl.properties = $.parseJSON( - ctrl.appSettings.AppSettings.DefaultPostAttr - ); - ctrl.trackedProperties = $.parseJSON( - ctrl.appSettings.AppSettings.DefaultPostAttr - ); - ctrl.dataTypes = $rootScope.globalSettings.dataTypes; - }; - ctrl.addPostProperty = function () { - ctrl.properties.push({ - priority: 0, - name: "", - value: null, - dataType: "7", - }); + $scope.loadTheme = async function () { + var req = { + method: "GET", + url: "/rest/mix-tenancy/setup/load-theme", }; - ctrl.$doCheck = function () { - if (ctrl.trackedProperties != ctrl.properties) { - ctrl.trackedProperties = angular.copy(ctrl.properties); - ctrl.appSettings.AppSettings.DefaultPostAttr = JSON.stringify( - ctrl.properties - ); - } - }.bind(ctrl); - }, - ], - bindings: { - appSettings: "=", - cultures: "=", - statuses: "=", - onDelete: "&", - onUpdate: "&", - }, -}); + return await apiService.sendRequest(req); + }; -app.component("appSettingsAuth", { - templateUrl: - "/mix-app/views/app-portal/pages/app-settings/components/auth/view.html", - controller: [ - "ngAppSettings", - function (ngAppSettings) { - var ctrl = this; - }, - ], - bindings: { - appSettings: "=", - onDelete: "&", - onUpdate: "&", - }, -}); + $scope.import = async function () { + $scope.importThemeDto.themeId = $routeParams.id; + $rootScope.isBusy = true; + var response = await tenancyService.import($scope.importThemeDto); -app.component("appSettingsGeneral", { - templateUrl: - "/mix-app/views/app-portal/pages/app-settings/components/general/view.html", - controller: [ - "$rootScope", - "$scope", - "CryptoService", - "CommonService", - function ($rootScope, $scope, cryptoService, commonService) { - var ctrl = this; - ctrl.$onInit = () => { - var key = cryptoService.parseKeys(ctrl.appSettings.apiEncryptKey); - ctrl.apiKey = key.key; - ctrl.iv = key.iv; - }; - ctrl.stopApplication = async function () { - $rootScope.isBusy = true; - await commonService.stopApplication(); - $rootScope.showMessage("success", "success"); + if (response.success) { $rootScope.isBusy = false; + window.open("/", "_blank"); $scope.$apply(); - }; - }, - ], - bindings: { - appSettings: "=", - onDelete: "&", - onUpdate: "&", + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; }, -}); +]); -app.component("appSettingsHeart", { - templateUrl: - "/mix-app/views/app-portal/pages/app-settings/components/heart/view.html", - bindings: {}, - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "AppSettingsServices", - "CommonService", - function ( - $rootScope, +"use strict"; +app.controller("UrlAliasController", [ + "$scope", + "$rootScope", + "ngAppSettings", + "$routeParams", + "$location", + "UrlAliasService", + "ApiService", + "CommonService", + function ( + $scope, + $rootScope, + ngAppSettings, + $routeParams, + $location, + service, + apiService, + commonService + ) { + BaseCtrl.call( + this, $scope, + $rootScope, + $routeParams, ngAppSettings, - settingService, - commonService - ) { - var ctrl = this; - ctrl.$onInit = function () { - ctrl.databaseProviders = ngAppSettings.enums.database_providers; - ctrl.cacheModes = ngAppSettings.enums.cache_modes; - settingService.getAppSettings("mix_heart").then((resp) => { - ctrl.appSettings = resp.data; - $scope.$apply; - }); - }; - ctrl.clearCache = async function () { - $rootScope.isBusy = true; - await commonService.clearCache(); - $rootScope.showMessage("success", "success"); + service + ); + $scope.cates = ["Site", "System"]; + $scope.others = []; + $scope.mixConfigurations = $rootScope.globalSettings; + $scope.pageId = $routeParams.id; + $scope.canDrag = + $scope.request.orderBy !== "Priority" || $scope.request.direction !== "0"; + $scope.getList = async function () { + $rootScope.isBusy = true; + var id = $routeParams.id; + $scope.request.query = "&page_id=" + id; + var response = await service.getList($scope.request); + $scope.canDrag = + $scope.request.orderBy !== "Priority" || + $scope.request.direction !== "0"; + if (response.success) { + $scope.data = response.data; $rootScope.isBusy = false; $scope.$apply(); - }; - }, - ], -}); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.remove = function (id) { + $rootScope.showConfirm( + $scope, + "removeConfirmed", + [id], + null, + "Remove", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + }; -app.component("appSettingsSmtp", { - templateUrl: - "/mix-app/views/app-portal/pages/app-settings/components/smtp/view.html", - controller: [ - "ngAppSettings", - function (ngAppSettings) { - var ctrl = this; - }, - ], - bindings: { - appSettings: "=", - }, -}); + $scope.removeConfirmed = async function (id) { + $rootScope.isBusy = true; + var result = await service.delete(id); + if (result.success) { + if ($scope.removeCallback) { + $rootScope.executeFunctionByName( + "removeCallback", + $scope.removeCallbackArgs, + $scope + ); + } + $scope.getList(); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; -modules.component("portalMenus", { - templateUrl: - "/mix-app/views/app-portal/pages/app-settings/components/portal-menus/view.html", - bindings: { - data: "=", - allowedTypes: "=", + $scope.updateInfos = async function (index) { + $scope.data.items.splice(index, 1); + $rootScope.isBusy = true; + var startIndex = $scope.data.items[0].priority - 1; + for (var i = 0; i < $scope.data.items.length; i++) { + $scope.data.items[i].priority = startIndex + i + 1; + } + var resp = await service.updateInfos($scope.data.items); + if (resp && resp.success) { + $scope.activedPage = resp.data; + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; }, - controller: [ +]); + +"use strict"; +app.factory("UrlAliasService", [ "$rootScope", - "$scope", - "$location", "ApiService", "CommonService", - "ngAppSettings", - function ( - $rootScope, - $scope, - $location, - apiService, - commonService, - ngAppSettings - ) { - var ctrl = this; - // ctrl.icons = []; - ctrl.translate = $rootScope.translate; - ctrl.init = function () { - ctrl.icons = ngAppSettings.icons; - }; - }, - ], -}); + "BaseRestService", + function ($rootScope, apiService, commonService, baseService) { + var serviceFactory = Object.create(baseService); + serviceFactory.initService("/rest/mix-portal", "mix-url-alias"); -app.component("customerMain", { - templateUrl: - "/mix-app/views/app-portal/pages/customer/components/main/customer-main.html", - bindings: { - customer: "=", - onDelete: "&", - onUpdate: "&", - }, -}); + var _updateInfos = async function (pages) { + var req = { + method: "POST", + url: this.prefixUrl + "/update-infos", + data: JSON.stringify(pages), + }; + return await apiService.sendRequest(req); + }; + serviceFactory.updateInfos = _updateInfos; + return serviceFactory; + }, +]); -app.component("customerOrders", { - templateUrl: - "/mix-app/views/app-portal/pages/customer/components/orders/customer-orders.html", - controller: [ - "$rootScope", - "OrderServices", - function ($rootScope, orderServices) { - var ctrl = this; - ctrl.removeOrder = function (id) { - $rootScope.showConfirm( - ctrl, - "removeOrderConfirmed", - [id], - null, - "Remove Order", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); - }; +"use strict"; +app.controller("UserController", [ + "$scope", + "$rootScope", + "$location", + "ngAppSettings", + "$routeParams", + "AuthService", + "UserServices", + "RestMixDatabaseDataPortalService", + "MixDbService", + function ( + $scope, + $rootScope, + $location, + ngAppSettings, + $routeParams, + authService, + userServices, + dataService, + mixDbService + ) { + $scope.request = { + pageSize: "10", + pageIndex: 0, + status: "Published", + orderBy: "CreatedDateTime", + direction: "Desc", + fromDate: null, + toDate: null, + keyword: "", + }; - ctrl.removeOrderConfirmed = async function (id) { - var result = await orderServices.removeOrder(id); - if (result.success) { - $rootScope.showMessage("success", "success"); - window.top.location = window.top.location.href; + $scope.mediaFile = { + file: null, + fullPath: "", + folder: "User", + title: "", + description: "", + }; + $scope.activedUser = null; + $scope.relatedUsers = []; + $rootScope.isBusy = false; + $scope.data = { + pageIndex: 0, + pageSize: 1, + totalItems: 0, + }; + $scope.errors = []; + + $scope.range = function (max) { + var input = []; + for (var i = 1; i <= max; i += 1) input.push(i); + return input; + }; + + $scope.loadUser = async function () { + var id = $routeParams.id; + if (id) { + $rootScope.isBusy = true; + var response = await userServices.getUser(id, "portal"); + if (response.success) { + $scope.activedUser = response.data; + $scope.loadAdditionalData(); } else { - $rootScope.showMessage("failed"); + $rootScope.showErrors(response.errors); $rootScope.isBusy = false; $scope.$apply(); } - }; - }, - ], - bindings: { - customer: "=", - onDelete: "&", - onUpdate: "&", - }, -}); - -app.component("mixDatabaseEdm", { - templateUrl: - "/mix-app/views/app-portal/pages/mix-database/components/edm/view.html", - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.mixConfigurations = $rootScope.globalSettings; - }, - ], - bindings: { - model: "=", - }, -}); - -app.component("mixDatabaseMain", { - templateUrl: - "/mix-app/views/app-portal/pages/mix-database/components/main/view.html", - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - - ctrl.$onInit = () => { - ctrl.globalSettings = $rootScope.globalSettings; - ctrl.isInRole = $rootScope.isInRole; - }; - ctrl.gennerateName = function (type) { - if ( - !ctrl.model.id || - ctrl.model.systemName === null || - ctrl.model.systemName === "" - ) { - let prefix = ctrl.model.type == "System" ? "sys" : ""; - ctrl.model.systemName = $rootScope.generateKeyword( - `${prefix} ${ctrl.model.displayName}`, - "", - true, - true + } + }; + $scope.loadAdditionalData = async function () { + mixDbService.initDbName("sysUserData"); + const getData = await mixDbService.getSingleByParent( + "User", + $scope.activedUser.id + ); + if (getData.success) { + $scope.additionalData = getData.data; + if (!$rootScope.isInRole("Owner")) { + $scope.activedUser.roles = $scope.activedUser.roles.filter( + (role) => role.description != "Owner" ); - if (ctrl.schema) { - ctrl.model.systemName = `${ctrl.schema}_${ctrl.model.systemName}`; - } } - }; - }, - ], - bindings: { - model: "=", - schema: "=?", - }, -}); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $scope.additionalData = {}; + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.loadMyProfile = async function () { + $rootScope.isBusy = true; + var response = await userServices.getMyProfile(); + if (response.success) { + $scope.activedUser = response.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; -app.component("mixdbContextDatabases", { - bindings: { - model: "=", - }, - templateUrl: - "/mix-app/views/app-portal/pages/mixdb-context/components/mix-databases/view.html", - controller: [ - "$rootScope", - "$scope", - "RestMixDatabasePortalService", - function ($rootScope, $scope, databaseService) { - var ctrl = this; - ctrl.request = $rootScope.getRequest(); - ctrl.$onInit = () => { - ctrl.globalSettings = $rootScope.globalSettings; - ctrl.isInRole = $rootScope.isInRole; - ctrl.request.mixDatabaseContextId = ctrl.model.id; - ctrl.loadDatabases(); - }; - ctrl.loadDatabases = async function () { - if (ctrl.model.id) { - var resp = await databaseService.getList(ctrl.request); - if (resp && resp.success) { - ctrl.data = resp.data; - $scope.$apply(); - } + $scope.loadUsers = async function (pageIndex) { + authService.fillAuthData().then(() => { + if ($rootScope.isInRoles(["Owner", "Admin"])) { + $scope.createUrl = "/admin/user/create"; } - }; - }, - ], -}); + }); -app.component("moduleMain", { - templateUrl: - "/mix-app/views/app-portal/pages/module/components/main/main.html", - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.localizeSettings = $rootScope.globalSettings; - ctrl.isInRole = $rootScope.isInRole; - ctrl.gennerateName = function () { - if ( - !ctrl.module.id || - ctrl.module.systemName === null || - ctrl.module.systemName === "" - ) { - ctrl.module.systemName = $rootScope.generateKeyword( - ctrl.module.title, - "_", - true, - true + if (pageIndex !== undefined) { + $scope.request.pageIndex = pageIndex; + } + $rootScope.isBusy = true; + var resp = await userServices.getUsers($scope.request); + if (resp && resp.success) { + $scope.data = resp.data; + if (!$rootScope.isInRole("Owner")) { + $scope.data.items = $scope.data.items.filter( + (user) => + user.roles.length == 0 || user.roles[0].role.name != "Owner" ); } - }; - }, - ], - bindings: { - module: "=", - }, -}); - -app.component("moduleContent", { - templateUrl: - "/mix-app/views/app-portal/pages/module/components/module-content/view.html", - bindings: { - model: "=", - additionalData: "=", - }, - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.$onInit = function () { - ctrl.backUrl = `/admin/module/details`; - }; - ctrl.mixConfigurations = $rootScope.globalSettings; - }, - ], -}); + $.each($scope.data.items, function (i, user) { + $.each($scope.data, function (i, e) { + if (e.userId === user.id) { + user.isHidden = true; + } + }); + }); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; -app.component("moduleAdvanced", { - templateUrl: - "/mix-app/views/app-portal/pages/module/components/module-advanced/view.html", - bindings: { - model: "=", - additionalData: "=", - }, - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.mixConfigurations = $rootScope.globalSettings; - ctrl.$onInit = function () { - ctrl.isAdmin = $rootScope.isAdmin; - }; - }, - ], -}); + $scope.removeUser = function (id) { + $rootScope.showConfirm( + $scope, + "removeUserConfirmed", + [id], + null, + "Remove User", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + }; -app.component("moduleType", { - templateUrl: - "/mix-app/views/app-portal/pages/module/components/module-type/view.html", - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.mixConfigurations = $rootScope.globalSettings; - }, - ], - bindings: { - model: "=", - }, -}); + $scope.removeUserConfirmed = async function (id) { + $rootScope.isBusy = true; + var result = await userServices.removeUser(id); + if (result.success) { + $scope.loadUsers(); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; -app.component("pageMain", { - templateUrl: "/mix-app/views/app-portal/pages/page/components/main/main.html", - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - function ($rootScope, $scope) { - var ctrl = this; - ctrl.mixConfigurations = $rootScope.globalSettings; - // ctrl.setPageType = function (type) { - // ctrl.page.type = $index; - // } - ctrl.generateSeo = function () { - if (ctrl.page) { - if (ctrl.page.seoName === null || ctrl.page.seoName === "") { - ctrl.page.seoName = $rootScope.generateKeyword( - ctrl.page.title, - "-" - ); - } - if (ctrl.page.seoTitle === null || ctrl.page.seoTitle === "") { - ctrl.page.seoTitle = ctrl.page.title; - } - if ( - ctrl.page.seoDescription === null || - ctrl.page.seoDescription === "" - ) { - ctrl.page.seoDescription = ctrl.page.excerpt; - } - if (ctrl.page.seoKeywords === null || ctrl.page.seoKeywords === "") { - ctrl.page.seoKeywords = ctrl.page.title; + $scope.save = async function () { + //if (user.avatar !== user.avatarUrl) { + // user.avatar = user.avatarUrl; + //} + $rootScope.isBusy = true; + var resp = await userServices.saveUser($scope.activedUser); + if (resp && resp.success) { + mixDbService.initDbName("sysUserData"); + if ($scope.additionalData) { + $scope.additionalData.parentType = "User"; + $scope.additionalData.parentId = $scope.activedUser.id; + var saveResult = await mixDbService.save($scope.additionalData); + if (saveResult.success) { + $rootScope.showMessage("Additional Data Saved", "success"); + $scope.additionalData = saveResult.data; + } else { + $rootScope.showErrors(result.errors); } } - }; - }, - ], - bindings: { - page: "=", - onDelete: "&", - onUpdate: "&", - }, -}); + $rootScope.isBusy = false; -app.component("pageModules", { - templateUrl: - "/mix-app/views/app-portal/pages/page/components/modules/modules.html", - bindings: { - page: "=", - onDelete: "&?", - onUpdate: "&?", - }, - controller: [ - "$scope", - "ngAppSettings", - "ModuleRestService", - function ($scope, ngAppSettings, moduleService) { - var ctrl = this; - ctrl.modules = []; - ctrl.request = angular.copy(ngAppSettings.request); + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; - ctrl.$onInit = async () => { - ctrl.request.columns = [ - "id", - "title", - "systemName", - "createdDateTime", - "type", - ]; - ctrl.request.culture = ctrl.page.specificulture; - ctrl.loadModules(); - }; - ctrl.loadModules = async () => { - let getModules = await moduleService.getList(ctrl.request); - if (getModules.success) { - ctrl.modules = getModules.data.items; + $scope.saveUserData = async function () { + if ($scope.activedUser.userData) { + $scope.activedUser.userData.parentId = $scope.activedUser.id; + $scope.activedUser.userData.parentType = "User"; + await dataService.save($scope.activedUser.userData); + } + }; + + $scope.resendConfirmEmail = async function (id) { + if (id) { + $rootScope.isBusy = true; + var resp = await userServices.resendConfirmEmail(id); + if (resp && resp.success) { + $rootScope.showMessage("Sent mail successfully!", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; $scope.$apply(); } - }; - ctrl.select = async (associations) => { - ctrl.associations = associations; - if (ctrl.onUpdate) { - ctrl.onUpdate({ associations: associations }); - } - }; - }, - ], -}); + } + }; -app.component("pageAdvanced", { - templateUrl: - "/mix-app/views/app-portal/pages/page/components/page-advanced/view.html", - bindings: { - model: "=", - additionalData: "=", - }, - controller: [ - "$rootScope", - "$scope", - function ($rootScope, $scope) { - var ctrl = this; + $scope.register = async function (user) { + $rootScope.isBusy = true; + var resp = await userServices.register(user); + if (resp && resp.success) { + $scope.activedUser = resp.data; + $rootScope.showMessage("Update successfully!", "success"); + $rootScope.isBusy = false; + $location.url("/admin/user/list"); + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; - ctrl.translate = $rootScope.translate; - ctrl.$onInit = function () { - ctrl.isAdmin = $rootScope.isAdmin; + $scope.updateRoleStatus = async function (role) { + var userRole = { + userId: $scope.activedUser.id, + roleId: role.id, + roleName: role.name, + isUserInRole: role.isActived, }; - }, - ], -}); - -app.component("pageGeneral", { - templateUrl: - "/mix-app/views/app-portal/pages/page/components/general/general.html", - controller: function ($rootScope) { - var ctrl = this; - ctrl.isInRole = $rootScope.isInRole; - ctrl.dataTypes = [ - { - title: "String", - value: "text", - }, - { - title: "Int", - value: "int", - }, - { - title: "Image", - value: "image", - }, - { - title: "Boolean", - value: "boolean", - }, - ]; - ctrl.configurations = { - core: {}, - plugins: { - btnsDef: { - // Customizables dropdowns - image: { - dropdown: ["insertImage", "upload", "base64", "noembed"], - ico: "insertImage", - }, - }, - btns: [ - ["viewHTML"], - ["undo", "redo"], - ["formatting"], - ["strong", "em", "del", "underline"], - ["link"], - ["image"], - ["justifyLeft", "justifyCenter", "justifyRight", "justifyFull"], - ["unorderedList", "orderedList"], - ["foreColor", "backColor"], - ["preformatted"], - ["horizontalRule"], - ["fullscreen"], - ], - plugins: { - // Add imagur parameters to upload plugin - upload: { - serverPath: "https://api.imgur.com/3/image", - fileFieldName: "image", - headers: { - Authorization: "Client-ID 9e57cb1c4791cea", - }, - urlPropertyName: "data.link", - }, - }, - }, - }; - ctrl.addProperty = function (type) { - var i = $(".property").length; - ctrl.page.properties.push({ - priority: 0, - name: "", - value: null, - dataType: 0, - }); - }; - ctrl.initEditor = function () { - setTimeout(function () { - // Init Code editor - $.each($(".code-editor"), function (i, e) { - var container = $(this); - var editor = ace.edit(e); - if (container.hasClass("json")) { - editor.session.setMode("ace/mode/json"); - } else { - editor.session.setMode("ace/mode/razor"); - } - editor.setTheme("ace/theme/chrome"); - //editor.setReadOnly(true); - - editor.session.setUseWrapMode(true); - editor.setOptions({ - maxLines: Infinity, - }); - editor.getSession().on("change", function (e) { - // e.type, etc - $(container).parent().find(".code-content").val(editor.getValue()); - }); - }); - $.each($(".editor-content"), function (i, e) { - var $demoTextarea = $(e); - $demoTextarea.quill(ctrl.configurations.plugins); - }); - }, 200); + $rootScope.isBusy = true; + var resp = await userServices.updateRoleStatus(userRole); + if (resp && resp.success) { + $rootScope.showMessage("Update successfully!", "success"); + $rootScope.isBusy = false; + $location.url("/admin/user/list"); + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } }; }, - bindings: { - page: "=", - onDelete: "&", - onUpdate: "&", - }, -}); +]); -app.component("pageType", { - templateUrl: - "/mix-app/views/app-portal/pages/page/components/page-type/view.html", - bindings: { - model: "=", - }, - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.localizeSettings = $rootScope.globalSettings; - }, - ], -}); +"use strict"; +app.factory("UserServices", [ + "ApiService", + "ngAppSettings", + function (apiService, ngAuthSettings) { + var usersServiceFactory = {}; + var apiUrl = "/rest/mix-account/user"; -app.component("pageContent", { - templateUrl: - "/mix-app/views/app-portal/pages/page/components/page-content/view.html", - bindings: { - additionalData: "=", - model: "=", - }, - controller: [ - "$rootScope", - "$scope", - function ($rootScope, $scope) { - var ctrl = this; - ctrl.translate = $rootScope.translate; - ctrl.$onInit = function () { - ctrl.backUrl = `/admin/page/details`; + var serviceBase = ngAuthSettings.serviceBase; + + var _resendConfirmEmail = function (id) { + var url = `${apiUrl}/resend-confirm-email/${id}`; + var req = { + method: "GET", + url: serviceBase + url, }; - ctrl.generateSeo = function () { - if ($scope.viewmodel) { - if (ctrl.model.seoName === null || ctrl.model.seoName === "") { - ctrl.model.seoName = $rootScope.generateKeyword( - ctrl.model.title, - "-" - ); - } - if (ctrl.model.seoTitle === null || ctrl.model.seoTitle === "") { - ctrl.model.seoTitle = ctrl.model.title; - } - if ( - ctrl.model.seoDescription === null || - ctrl.model.seoDescription === "" - ) { - ctrl.model.seoDescription = ctrl.model.excerpt; - } - if ( - ctrl.model.seoKeywords === null || - ctrl.model.seoKeywords === "" - ) { - ctrl.model.seoKeywords = ctrl.model.title; - } - } + + return apiService.sendRequest(req); + }; + var _getUserDemographicInfo = function () { + var url = "/GetUserDemographicInfo"; + var req = { + method: "GET", + url: serviceBase + url, }; - }, - ], -}); -app.component("pageParents", { - templateUrl: - "/mix-app/views/app-portal/pages/page/components/parents/parents.html", - bindings: { - page: "=", - onDelete: "&", - onUpdate: "&", - }, -}); + return apiService.sendRequest(req); + }; -app.component("pagePlugPlay", { - templateUrl: - "/mix-app/views/app-portal/pages/page/components/plug-play/plug-play.html", - bindings: { - page: "=", - onDelete: "&", - onUpdate: "&", - }, -}); + var _importUsers = function (strBase64) { + var url = "import-users"; + var req = { + method: "POST", + url: apiUrl + url, + data: JSON.stringify({ strBase64: strBase64 }), + }; -app.component("productRelated", { - templateUrl: - "/mix-app/views/app-portal/pages/product/components/related/productRelated.html", - controller: function () { - var ctrl = this; - ctrl.activeProduct = function (pr) { - var currentItem = null; - $.each(ctrl.product.productNavs, function (i, e) { - if (e.relatedProductId === pr.id) { - e.isActived = pr.isActived; - currentItem = e; - return false; - } - }); - if (currentItem === null) { - currentItem = { - relatedProductId: pr.id, - sourceProductId: ctrl.product.id, - specificulture: ctrl.product.specificulture, - priority: ctrl.product.productNavs.length + 1, - relatedProduct: pr, - isActived: true, - }; - pr.isHidden = true; - ctrl.product.productNavs.push(currentItem); - } + return apiService.sendRequest(req); }; - }, - bindings: { - product: "=", - list: "=", - onDelete: "&", - onUpdate: "&", - }, -}); -app.component("pageSeo", { - templateUrl: "/mix-app/views/app-portal/pages/page/components/seo/seo.html", - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.translate = function (keyword) { - return $rootScope.translate(keyword); + var _getUsers = function (request) { + var data = _parseQuery(request); + var url = `${apiUrl}/list`; + + if (data) { + url += "?"; + url = url.concat(data); + } + var req = { + method: "GET", + url: url, + data: request, }; - }, - ], - bindings: { - page: "=", - onDelete: "&", - onUpdate: "&", - }, -}); -app.component("permissionMain", { - templateUrl: - "/mix-app/views/app-portal/pages/permission/components/main/main.html", - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "$routeParams", - function ($rootScope, $scope, ngAppSettings, $routeParams) { - var ctrl = this; - ctrl.mixConfigurations = $rootScope.globalSettings; - ctrl.icons = ngAppSettings.icons; - ctrl.setPageType = function (type) { - ctrl.page.type = $index; + return apiService.sendRequest(req); + }; + + var _getUser = async function (id, viewType) { + var url = "/rest/mix-account/user/details"; + if (id) { + url += "/" + id; + } + var req = { + method: "GET", + url: url, }; - ctrl.generateKeyword = function (text) { - if (!$routeParams.id && text) { - ctrl.page.textKeyword = - "portal_" + - text - .replace(/[^a-zA-Z0-9]+/g, "_") - .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2") - .replace(/([a-z])([A-Z])/g, "$1-$2") - .replace(/([0-9])([^0-9])/g, "$1-$2") - .replace(/([^0-9])([0-9])/g, "$1-$2") - .replace(/-+/g, "_") - .toLowerCase(); - } + return await apiService.sendRequest(req); + }; + + var _getMyProfile = async function () { + var url = "/rest/mix-account/user/my-profile"; + var req = { + method: "GET", + url: url, }; - }, - ], - bindings: { - page: "=", - onDelete: "&", - onUpdate: "&", - }, -}); + return await apiService.sendRequest(req); + }; -app.component("permissionParents", { - templateUrl: - "/mix-app/views/app-portal/pages/permission/components/parents/parents.html", - bindings: { - page: "=", - onDelete: "&", - onUpdate: "&", - }, -}); + var _updateRoleStatus = function (userInRole) { + var req = { + method: "POST", + url: serviceBase + "/rest/mix-account/user/user-in-role", + data: JSON.stringify(userInRole), + }; -app.component("permissionPlugPlay", { - templateUrl: - "/mix-app/views/app-portal/pages/permission/components/plug-play/plug-play.html", - bindings: { - page: "=", - prefixParent: "=", - prefixChild: "=", - searchText: "=", - onDelete: "&", - onUpdate: "&", - }, - controller: [ - "$rootScope", - "$scope", - "$location", - "$element", - "PermissionService", - function ($rootScope, $scope, $location, $element, service) { - var ctrl = this; - ctrl.type = "Children"; - ctrl.goToPath = $rootScope.goToPath; - ctrl.request = { - pageSize: "5", - pageIndex: 0, - status: "Published", - orderBy: "CreatedDateTime", - direction: "Desc", - fromDate: null, - toDate: null, + return apiService.sendRequest(req); + }; + + var _saveUser = async function (user) { + var apiUrl = "/rest/mix-account/user/save"; + var req = { + method: "POST", + url: apiUrl, + data: JSON.stringify(user), }; - ctrl.pages = []; - ctrl.init = function () { - if (ctrl.page) { - ctrl.request.exceptIds = ctrl.page.parentNavs - .map((p) => p.pageId) - .concat(ctrl.page.childNavs.map((p) => p.pageId)); - if (ctrl.request.exceptIds.indexOf(ctrl.page.id) === -1) { - ctrl.request.exceptIds.push(ctrl.page.id); - } - ctrl.getList(); - } + return await apiService.sendRequest(req); + }; + + var _register = async function (user) { + var apiUrl = "/rest/mix-account/user/"; + var req = { + method: "POST", + url: apiUrl + "register", + data: JSON.stringify(user), }; - ctrl.selectPane = function (pane) { - if (ctrl.page) { - ctrl.type = pane.header; - ctrl.request.keyword = ""; - ctrl.init(); - } + return await apiService.sendRequest(req); + }; + + var _removeUser = function (userId) { + var req = { + method: "DELETE", + url: apiUrl + "/remove-user/" + userId, }; - ctrl.selectItem = (nav) => { - if (ctrl.type == "Parents") { - if ( - !$rootScope.findObjectByKey(ctrl.page.parentNavs, "pageId", nav.id) - ) { - ctrl.page.parentNavs.push({ - isActived: true, - pageId: ctrl.page.id, - parentId: nav.id, - description: nav.textDefault, - status: "Published", - parent: nav, - }); + return apiService.sendRequest(req); + }; + + var _parseQuery = function (req) { + var result = ""; + if (req) { + for (var key in req) { + if (angular.isObject(req.query)) { + req.query = JSON.stringify(req.query); } - } else { - if ( - !$rootScope.findObjectByKey(ctrl.page.childNavs, "pageId", nav.id) - ) { - ctrl.page.childNavs.push({ - isActived: true, - pageId: nav.id, - parentId: ctrl.page.id, - description: nav.textDefault, - status: "Published", - page: nav, - }); + if (req.hasOwnProperty(key) && req[key]) { + if (result != "") { + result += "&"; + } + result += `${key}=${req[key]}`; } } - }; + return result; + } else { + return result; + } + }; - ctrl.getList = async function () { - $rootScope.isBusy = true; - var resp = await service.getList(ctrl.request); - if (resp && resp.success) { - ctrl.pages = resp.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors || ["Failed"]); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - }, - ], -}); + usersServiceFactory.importUsers = _importUsers; + usersServiceFactory.getUsers = _getUsers; + usersServiceFactory.getUser = _getUser; + usersServiceFactory.resendConfirmEmail = _resendConfirmEmail; + usersServiceFactory.getMyProfile = _getMyProfile; + usersServiceFactory.saveUser = _saveUser; + usersServiceFactory.register = _register; + usersServiceFactory.removeUser = _removeUser; + usersServiceFactory.updateRoleStatus = _updateRoleStatus; + usersServiceFactory.getUserDemographicInfo = _getUserDemographicInfo; + return usersServiceFactory; + }, +]); -modules.component("postFilterList", { - templateUrl: - "/mix-app/views/app-portal/pages/post/components/filter-list/filter-list.html", - bindings: { - request: "=", - key: "=?", - orders: "=?", - createUrl: "=", - createText: "=", - categories: "=", - postTypes: "=", +"use strict"; +function PageDetailsController($scope, $element, $attrs) { + var ctrl = this; + ctrl.activedPage = null; + ctrl.relatedPages = []; + ctrl.data = []; + ctrl.errors = []; + ctrl.range = function (max) { + var input = []; + for (var i = 1; i <= max; i += 1) input.push(i); + return input; + }; + ctrl.loadPage = function (pageId) { + ctrl.isBusy = true; + var url = "/" + ctrl.currentLanguage + "/page/details/be/" + pageId; //byPage/' + pageId; + ctrl.mixConfigurations.method = "GET"; + ctrl.mixConfigurations.url = url; // + '/true'; + ctrl.mixConfigurations.data = ctrl.request; + $.ajax(ctrl.mixConfigurations).done(function (response) { + if (response.success) { + ctrl.activedPage = response.data; + ctrl.initEditor(); + } + ctrl.isBusy = false; + ctrl.$apply(); + }); + }; + ctrl.loadPages = function (pageIndex) { + ctrl.isBusy = true; + if (pageIndex !== undefined) { + ctrl.request.pageIndex = pageIndex; + } + if (ctrl.request.fromDate !== null) { + ctrl.request.fromDate = ctrl.request.fromDate.toISOString(); + } + if (ctrl.request.toDate !== null) { + ctrl.request.toDate = ctrl.request.toDate.toISOString(); + } + var url = "/" + ctrl.currentLanguage + "/page/list"; //byPage/' + pageId; + ctrl.mixConfigurations.method = "POST"; + ctrl.mixConfigurations.url = url; // + '/true'; + ctrl.mixConfigurations.data = ctrl.request; + $.ajax(ctrl.mixConfigurations).done(function (response) { + ctrl.data = response.data; + + $.each(ctrl.data.items, function (i, page) { + $.each(ctrl.activedPages, function (i, e) { + if (e.pageId === page.id) { + page.isHidden = true; + } + }); + }); + ctrl.isBusy = false; + setTimeout(function () { + $('[data-bs-toggle="popover"]').popover({ + html: true, + content: function () { + var content = $(this).next(".popover-body"); + return $(content).html(); + }, + title: function () { + var title = $(this).attr("data-popover-content"); + return $(title).children(".popover-heading").html(); + }, + }); + }, 200); + ctrl.$apply(); + }); + }; + + ctrl.removePage = function (pageId) { + if (confirm("Are you sure!")) { + var url = "/" + ctrl.currentLanguage + "/page/delete/" + pageId; + $.ajax({ + method: "GET", + url: url, + success: function (data) { + ctrl.loadPages(); + ctrl.$apply(); + }, + error: function (a, b, c) {}, + }); + } + }; + ctrl.savePage = function (page) { + var url = "/" + ctrl.currentLanguage + "/page/save"; + $.ajax({ + method: "POST", + url: url, + data: page, + success: function (data) { + //ctrl.loadPages(); + if (data.success) { + alert("success"); + } else { + alert("failed! " + data.errors); + } + }, + error: function (a, b, c) {}, + }); + }; + + ctrl.changeMedia = function (media) { + var currentItem = null; + if (ctrl.activedPage.mediaNavs === undefined) { + ctrl.activedPage.mediaNavs = []; + } + $.each(ctrl.activedPage.mediaNavs, function (i, e) { + if (e.mediaId === media.id) { + e.isActived = media.isActived; + currentItem = e; + return false; + } + }); + if (currentItem === null) { + currentItem = { + description: media.description !== "undefined" ? media.description : "", + image: media.fullPath, + mediaId: media.id, + page: ctrl.activedPage.id, + specificulture: media.specificulture, + position: 0, + priority: ctrl.activedMedias.length + 1, + isActived: true, + }; + media.isHidden = true; + ctrl.activedPage.mediaNavs.push(currentItem); + } + }; + + ctrl.changePage = function (page) { + var currentItem = null; + $.each(ctrl.activedPage.pageNavs, function (i, e) { + if (e.relatedPageId === page.id) { + e.isActived = page.isActived; + currentItem = e; + return false; + } + }); + if (currentItem === null) { + currentItem = { + relatedPageId: page.id, + sourcePageId: $("#page-id").val(), + specificulture: page.specificulture, + priority: ctrl.activedPage.pageNavs.length + 1, + page: page, + isActived: true, + }; + page.isHidden = true; + ctrl.activedPage.pageNavs.push(currentItem); + } + }; + + ctrl.addProperty = function (type) { + var i = $(".property").length; + $.ajax({ + method: "GET", + url: + "/" + + ctrl.currentLanguage + + "/admin/" + + type + + "/AddEmptyProperty/" + + i, + success: function (data) { + $("#tbl-properties > tbody").append(data); + $(data).find(".prop-data-type").trigger("change"); + }, + error: function (a, b, c) {}, + }); + ctrl.updateHero = function (hero, prop, value) { + hero[prop] = value; + }; + + ctrl.deleteHero = function (hero) { + var idx = ctrl.list.indexOf(hero); + if (idx >= 0) { + ctrl.list.splice(idx, 1); + } + }; + }; + + angular.module(appName).component("pageDetails", { + templateUrl: "pageDetails.html", + controller: PageDetailsController, + }); +} + +modules.component("roleAssociations", { + templateUrl: + "/mix-app/views/app-portal/pages/user/role-associations/view.html", + bindings: { + userRoles: "=", callback: "&", }, controller: [ - "$scope", "$rootScope", + "$scope", "ngAppSettings", - "RestMixDatabaseDataPortalService", - "CultureService", - function ($scope, $rootScope, ngAppSettings, dataService, cultureService) { + "$location", + "RoleService", + function ($rootScope, $scope, ngAppSettings, $location, roleService) { var ctrl = this; - ctrl.dateRange = { - fromDate: null, - toDate: null, - }; - ctrl.request = angular.copy(ngAppSettings.request); - - ctrl.init = function () { - if (!ctrl.orders) { - ctrl.orders = ngAppSettings.orders; + ctrl.selected = null; + ctrl.activedIndex = null; + ctrl.$onInit = async () => { + var getRoles = await roleService.getList(); + if (getRoles.success) { + ctrl.roles = getRoles.data.items; } - ctrl.directions = ngAppSettings.directions; - ctrl.pageSizes = ngAppSettings.pageSizes; - ctrl.statuses = []; - var statuses = ngAppSettings.contentStatuses; - if (ctrl.request && ctrl.request.contentStatuses) { - statuses = ctrl.request.contentStatuses; + if (!ctrl.userRoles) { + ctrl.userRoles = []; } - angular.forEach(statuses, function (val, i) { - ctrl.statuses.push({ - value: val, - title: val, - }); + angular.forEach(ctrl.roles, (e) => { + e.isActived = ctrl.userRoles.find((u) => u.roleId == e.id) != null; }); }; - ctrl.addMetadataQuery = () => { - ctrl.request.metadataQueries.push({ - fieldName: "", - value: "", - isRequired: false, - }); + + ctrl.select = async (obj) => { + if (ctrl.callback) { + ctrl.callback({ role: obj }); + } }; - ctrl.clearMetadataQuery = () => { - ctrl.request.metadataQueries = []; - ctrl.apply(); + + ctrl.dragStart = function (index) { + ctrl.dragStartIndex = index; + ctrl.minPriority = ctrl.data[0].priority; }; - ctrl.changeLang = function (culture) { - if (culture) { - ctrl.selectedCulture = culture; - ctrl.request.culture = culture.specificulture; - } else { - ctrl.selectedCulture = null; - ctrl.request.culture = null; - } - ctrl.apply(0); - }; - ctrl.apply = function (pageIndex) { - $rootScope.setRequest(ctrl.request, ctrl.key); - ctrl.callback({ pageIndex: pageIndex }); - }; - ctrl.updateDate = function () { - if (Date.parse(ctrl.dateRange.fromDate)) { - ctrl.request.fromDate = new Date( - ctrl.dateRange.fromDate - ).toISOString(); - } else { - $scope.request.fromDate = null; - } - if (Date.parse(ctrl.dateRange.toDate)) { - ctrl.request.toDate = new Date(ctrl.dateRange.toDate).toISOString(); - } else { - ctrl.request.toDate = null; - } - $rootScope.setRequest(ctrl.request, ctrl.key); - ctrl.callback({ pageIndex: 0 }); + ctrl.goToDetails = async function (nav) { + $location.url(ctrl.detailUrl + nav[ctrl.key]); }; }, ], }); -app.component("postMain", { - templateUrl: "/mix-app/views/app-portal/pages/post/components/main/view.html", - bindings: { - post: "=", - }, +app.component("appSettingsAuth", { + templateUrl: + "/mix-app/views/app-portal/pages/app-settings/components/auth/view.html", controller: [ - "$rootScope", - "$scope", - function ($rootScope, $scope) { + "ngAppSettings", + function (ngAppSettings) { var ctrl = this; - ctrl.translate = $rootScope.translate; - ctrl.generateSeo = function () { - if (ctrl.post) { - if (!ctrl.post.seoName) { - ctrl.post.seoName = $rootScope.generateKeyword( - ctrl.post.title, - "-" - ); - } - if (!ctrl.post.seoTitle) { - ctrl.post.seoTitle = ctrl.post.title; - } - if (!ctrl.post.seoDescription === null) { - ctrl.post.seoDescription = ctrl.post.excerpt; - } - if (!ctrl.post.seoKeywords) { - ctrl.post.seoKeywords = ctrl.post.title; - } - } - }; }, ], + bindings: { + appSettings: "=", + onDelete: "&", + onUpdate: "&", + }, }); -app.component("postGeneral", { +app.component("appSettingsDefault", { templateUrl: - "/mix-app/views/app-portal/pages/post/components/general/view.html", + "/mix-app/views/app-portal/pages/app-settings/components/default/view.html", controller: [ "$rootScope", "ngAppSettings", function ($rootScope, ngAppSettings) { var ctrl = this; - ctrl.dataTypes = $rootScope.globalSettings.dataTypes; - ctrl.$onInit = function () {}; - ctrl.addProperty = function (type) { - var i = $(".property").length; - ctrl.post.properties.push({ - title: "", + ctrl.$onInit = function () { + ctrl.properties = $.parseJSON( + ctrl.appSettings.AppSettings.DefaultPostAttr + ); + ctrl.trackedProperties = $.parseJSON( + ctrl.appSettings.AppSettings.DefaultPostAttr + ); + ctrl.dataTypes = $rootScope.globalSettings.dataTypes; + }; + ctrl.addPostProperty = function () { + ctrl.properties.push({ + priority: 0, name: "", value: null, - dataType: "text", + dataType: "7", }); }; + ctrl.$doCheck = function () { + if (ctrl.trackedProperties != ctrl.properties) { + ctrl.trackedProperties = angular.copy(ctrl.properties); + ctrl.appSettings.AppSettings.DefaultPostAttr = JSON.stringify( + ctrl.properties + ); + } + }.bind(ctrl); }, ], bindings: { - post: "=", - isAdmin: "=", - onDelete: "&", - onUpdate: "&", - }, -}); - -app.component("postMedias", { - templateUrl: - "/mix-app/views/app-portal/pages/post/components/medias/view.html", - controller: function () { - var ctrl = this; - ctrl.activeMedia = function (media) { - var currentItem = null; - if (ctrl.post.mediaNavs === null) { - ctrl.post.mediaNavs = []; - } - $.each(ctrl.post.mediaNavs, function (i, e) { - if (e.mediaId === media.id) { - e.isActived = media.isActived; - currentItem = e; - return false; - } - }); - if (currentItem === null) { - currentItem = { - description: - media.description !== "undefined" ? media.description : "", - image: media.filePath, - mediaId: media.id, - post: ctrl.post.id, - specificulture: media.specificulture, - position: 0, - priority: ctrl.post.mediaNavs.length + 1, - isActived: true, - }; - media.isHidden = true; - ctrl.post.mediaNavs.push(currentItem); - } - }; - }, - bindings: { - post: "=", - medias: "=", - loadMedia: "&", + appSettings: "=", + cultures: "=", + statuses: "=", onDelete: "&", onUpdate: "&", }, }); -app.component("postModules", { +app.component("appSettingsGeneral", { templateUrl: - "/mix-app/views/app-portal/pages/post/components/modules/view.html", + "/mix-app/views/app-portal/pages/app-settings/components/general/view.html", controller: [ "$rootScope", "$scope", - "ngAppSettings", - "SharedModuleDataService", - function ($rootScope, $scope, ngAppSettings, moduleDataService) { + "CryptoService", + "CommonService", + function ($rootScope, $scope, cryptoService, commonService) { var ctrl = this; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.translate = function (keyword, wrap, defaultValue) { - return $rootScope.translate(keyword, wrap, defaultValue); - }; - - ctrl.removeData = function (id, moduleContentId) { - $rootScope.showConfirm( - ctrl, - "removeDataConfirmed", - [id, moduleContentId], - null, - "Remove Data", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); - }; - ctrl.removeDataConfirmed = async function (id, moduleContentId) { - $rootScope.isBusy = true; - var result = await moduleDataService.removeModuleData(id); - if (result.success) { - ctrl.loadModuleDatas(moduleContentId); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - ctrl.saveDataCallback = function (data) { - if (data) { - ctrl.loadModuleDatas(data.moduleContentId); - } - }; - ctrl.loadModuleDatas = async function (id, pageIndex) { - $rootScope.isBusy = true; - $scope.dataColumns = []; - var request = angular.copy(ngAppSettings.request); - request.query = "?moduleContentId=" + id + "&post_id=" + ctrl.post.id; - if (pageIndex) { - request.pageIndex = pageIndex; - } - var response = await moduleDataService.getModuleDatas(request); - if (response.success) { - var nav = $rootScope.findObjectByKey( - ctrl.post.moduleNavs, - "moduleContentId", - id - ); - if (nav) { - nav.module.data = response.data; - } - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } + ctrl.$onInit = () => { + var key = cryptoService.parseKeys(ctrl.appSettings.apiEncryptKey); + ctrl.apiKey = key.key; + ctrl.iv = key.iv; }; - - ctrl.updateDataInfos = async function (items) { + ctrl.stopApplication = async function () { $rootScope.isBusy = true; - var resp = await moduleDataService.updateInfos(items); - if (resp && resp.success) { - $scope.activedPage = resp.data; - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } + await commonService.stopApplication(); + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); }; }, ], bindings: { - post: "=", - onDelete: "&", - onUpdate: "&", - }, -}); - -app.component("postParents", { - templateUrl: - "/mix-app/views/app-portal/pages/post/components/parents/view.html", - bindings: { - post: "=", + appSettings: "=", onDelete: "&", onUpdate: "&", }, }); -app.component("postAdvanced", { +app.component("appSettingsHeart", { templateUrl: - "/mix-app/views/app-portal/pages/post/components/post-advanced/view.html", - bindings: { - model: "=", - additionalData: "=", - }, - controller: [ + "/mix-app/views/app-portal/pages/app-settings/components/heart/view.html", + bindings: {}, + controller: [ "$rootScope", "$scope", - "$routeParams", - function ($rootScope, $scope, $routeParams) { + "ngAppSettings", + "AppSettingsServices", + "CommonService", + function ( + $rootScope, + $scope, + ngAppSettings, + settingService, + commonService + ) { var ctrl = this; - ctrl.translate = $rootScope.translate; ctrl.$onInit = function () { - ctrl.isAdmin = $rootScope.isAdmin; - if ($routeParams.template) { - ctrl.defaultTemplate = $routeParams.template; - } - if ($routeParams.layout) { - ctrl.defaultLayout = $routeParams.layout; - } + ctrl.databaseProviders = ngAppSettings.enums.database_providers; + ctrl.cacheModes = ngAppSettings.enums.cache_modes; + settingService.getAppSettings("mix_heart").then((resp) => { + ctrl.appSettings = resp.data; + $scope.$apply; + }); + }; + ctrl.clearCache = async function () { + $rootScope.isBusy = true; + await commonService.clearCache(); + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); }; }, ], }); -app.component("postContent", { +modules.component("portalMenus", { templateUrl: - "/mix-app/views/app-portal/pages/post/components/post-content/view.html", + "/mix-app/views/app-portal/pages/app-settings/components/portal-menus/view.html", bindings: { - model: "=", - additionalData: "=", - loadingData: "=", + data: "=", + allowedTypes: "=", }, controller: [ "$rootScope", "$scope", + "$location", + "ApiService", + "CommonService", "ngAppSettings", - "PostRestService", - function ($rootScope, $scope, ngAppSettings, service) { + function ( + $rootScope, + $scope, + $location, + apiService, + commonService, + ngAppSettings + ) { var ctrl = this; - ctrl.request = angular.copy(ngAppSettings.request); + // ctrl.icons = []; ctrl.translate = $rootScope.translate; - ctrl.relatedData = {}; - ctrl.$onInit = function () { - ctrl.backUrl = `/admin/post/details`; - }; - ctrl.generateSeo = function () { - if (ctrl.model) { - if (ctrl.model.seoName === null || ctrl.model.seoName === "") { - ctrl.model.seoName = $rootScope.generateKeyword( - ctrl.model.title, - "-" - ); - } - if (ctrl.model.seoTitle === null || ctrl.model.seoTitle === "") { - ctrl.model.seoTitle = ctrl.model.title; - } - if ( - ctrl.model.seoDescription === null || - ctrl.model.seoDescription === "" - ) { - ctrl.model.seoDescription = ctrl.model.excerpt; - } - if ( - ctrl.model.seoKeywords === null || - ctrl.model.seoKeywords === "" - ) { - ctrl.model.seoKeywords = ctrl.model.title; - } - } + ctrl.init = function () { + ctrl.icons = ngAppSettings.icons; }; - ctrl.getListRelated = async function (pageIndex) { - if (pageIndex !== undefined) { - ctrl.request.pageIndex = pageIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var d = new Date(ctrl.request.toDate); - ctrl.request.toDate = d.toISOString(); - } - var resp = await service.getList(ctrl.request); - if (resp && resp.success) { - ctrl.relatedData = angular.copy(resp.data); - ctrl.relatedData.items = []; - angular.forEach(resp.data.items, (element) => { - var existed = $rootScope.findObjectByKey( - ctrl.model.postNavs, - ["sourceId", "destinationId"], - [ctrl.model.id, element.id] - ); - - var obj = { - description: element.title, - destinationId: element.id, - image: element.image, - isActived: existed !== null, - sourceId: ctrl.model.id, - specificulture: ctrl.model.specificulture, - status: "Published", - }; + }, + ], +}); - ctrl.relatedData.items.push(obj); - }); - console.log(ctrl.relatedData); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(getData.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; +app.component("appSettingsSmtp", { + templateUrl: + "/mix-app/views/app-portal/pages/app-settings/components/smtp/view.html", + controller: [ + "ngAppSettings", + function (ngAppSettings) { + var ctrl = this; }, ], + bindings: { + appSettings: "=", + }, }); -modules.component("relatedPosts", { +app.component("customerMain", { templateUrl: - "/mix-app/views/app-portal/pages/post/components/related-navigations/view.html", + "/mix-app/views/app-portal/pages/customer/components/main/customer-main.html", bindings: { - title: "=", - parentId: "=", - parentType: "=", - description: "=?", - postTypes: "=?", - mixDatabaseName: "=?", - image: "=?", + customer: "=", + onDelete: "&", + onUpdate: "&", }, +}); + +app.component("customerOrders", { + templateUrl: + "/mix-app/views/app-portal/pages/customer/components/orders/customer-orders.html", controller: [ "$rootScope", - "$scope", - "ngAppSettings", - "PostPostRestService", - "PostRestService", - function ($rootScope, $scope, ngAppSettings, service, postService) { + "OrderServices", + function ($rootScope, orderServices) { var ctrl = this; - ctrl.selected = null; - ctrl.posts = { - items: [], - }; - ctrl.data = { - items: [], - }; - ctrl.$onInit = async () => { - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.postRequest = angular.copy(ngAppSettings.request); - ctrl.postRequest.searchColumns = "title,excerpt"; - if (ctrl.mixDatabaseName) { - ctrl.postRequest.mixDatabaseName = ctrl.mixDatabaseName; - } - ctrl.postRequest.pageSize = 5; - await ctrl.loadRelatedPosts(); - await ctrl.loadPosts(); - }; - ctrl.addRelatedPost = async (post) => { - var tmp = ctrl.data.items.find( - (m) => m.child.id == post.id || m.parentId == post.id + ctrl.removeOrder = function (id) { + $rootScope.showConfirm( + ctrl, + "removeOrderConfirmed", + [id], + null, + "Remove Order", + "Deleted data will not able to recover, are you sure you want to delete this item?" ); - if (!tmp) { - if (post) { - let dto = { - parentId: ctrl.parentId, - childId: post.id, - }; - var resp = await service.create(dto); - if (resp.success) { - $rootScope.showMessage("Success", "success"); - await ctrl.loadRelatedPosts(); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(resp.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - } - } else { - $rootScope.showMessage(`${post.title} is existed`, "warning"); - } - }; - - ctrl.remove = function (id) { - if ( - confirm( - "Deleted data will not able to recover, are you sure you want to delete this item?" - ) - ) { - ctrl.removeConfirmed(id); - } }; - ctrl.removeConfirmed = async function (id) { - $rootScope.isBusy = true; - var result = await service.delete([id]); + ctrl.removeOrderConfirmed = async function (id) { + var result = await orderServices.removeOrder(id); if (result.success) { - ctrl.loadRelatedPosts(); + $rootScope.showMessage("success", "success"); + window.top.location = window.top.location.href; } else { - $rootScope.showErrors(result.errors); + $rootScope.showMessage("failed"); $rootScope.isBusy = false; $scope.$apply(); } }; + }, + ], + bindings: { + customer: "=", + onDelete: "&", + onUpdate: "&", + }, +}); - ctrl.loadPosts = async (pageIndex) => { - $rootScope.isBusy = true; - if (pageIndex !== undefined) { - ctrl.postRequest.pageIndex = pageIndex; - } - if (ctrl.postRequest.fromDate !== null) { - var d = new Date(ctrl.postRequest.fromDate); - ctrl.postRequest.fromDate = d.toISOString(); - } - if (ctrl.postRequest.toDate !== null) { - var dt = new Date(ctrl.postRequest.toDate); - ctrl.postRequest.toDate = dt.toISOString(); - } - let getData = await postService.filter(ctrl.postRequest); - if (getData.success) { - ctrl.posts = getData.data; - $rootScope.isBusy = false; - } else { - $rootScope.isBusy = false; - $rootScope.showErrors(getData.errors); - } - $scope.$apply(); - }; - - ctrl.loadRelatedPosts = async (pageIndex) => { - if (ctrl.parentId) { - $rootScope.isBusy = true; - if (pageIndex !== undefined) { - ctrl.request.pageIndex = pageIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.postRequest.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var dt = new Date(ctrl.postRequest.toDate); - ctrl.postRequest.toDate = dt.toISOString(); - } - ctrl.request.parentId = ctrl.parentId; - let getData = await service.search(ctrl.request); - if (getData.success) { - ctrl.data = getData.data; - $rootScope.isBusy = false; - } else { - $rootScope.isBusy = false; - $rootScope.showErrors(getData.errors); - } - $scope.$apply(); - } - }; +app.component("mixDatabaseEdm", { + templateUrl: + "/mix-app/views/app-portal/pages/mix-database/components/edm/view.html", + controller: [ + "$rootScope", + function ($rootScope) { + var ctrl = this; + ctrl.mixConfigurations = $rootScope.globalSettings; }, ], -}); - -app.component("postSeo", { - templateUrl: "/mix-app/views/app-portal/pages/post/components/seo/view.html", bindings: { - post: "=", - onDelete: "&", - onUpdate: "&", + model: "=", }, }); -modules.component("rolePageNav", { +app.component("mixDatabaseMain", { templateUrl: - "/mix-app/views/app-portal/pages/role/components/role-page-navigation/role-page-navigations.html", - bindings: { - prefix: "=", - page: "=", - callback: "&", - }, + "/mix-app/views/app-portal/pages/mix-database/components/main/view.html", controller: [ "$rootScope", - "$scope", - "ngAppSettings", - "RoleService", - function ($rootScope, $scope, ngAppSettings, roleServices) { + function ($rootScope) { var ctrl = this; - ctrl.selected = null; - ctrl.updateOrders = function (index) { - ctrl.data.splice(index, 1); - for (var i = 0; i < ctrl.data.length; i++) { - ctrl.data[i].priority = i + 1; + + ctrl.$onInit = () => { + ctrl.globalSettings = $rootScope.globalSettings; + ctrl.isInRole = $rootScope.isInRole; + }; + ctrl.gennerateName = function (type) { + if ( + !ctrl.model.id || + ctrl.model.systemName === null || + ctrl.model.systemName === "" + ) { + let prefix = ctrl.model.type == "System" ? "sys" : ""; + ctrl.model.systemName = $rootScope.generateKeyword( + `${prefix} ${ctrl.model.displayName}`, + "", + true, + true + ); + if (ctrl.schema) { + ctrl.model.systemName = `${ctrl.schema}_${ctrl.model.systemName}`; + } } }; - //ctrl.change = async function () { - // //var permission = ctrl.page.navPermission; - // //$rootScope.isBusy = true; - // //var resp = await roleServices.updatePermission(permission); - // //if (resp && resp.success) { - // // $rootScope.showMessage('Update successfully!', 'success'); - // // $rootScope.isBusy = false; - // // $scope.$apply(); - // //} - // //else { - // // if (resp) { $rootScope.showErrors(resp.errors); } - // // $rootScope.isBusy = false; - // // $scope.$apply(); - // //} - //}; }, ], + bindings: { + model: "=", + schema: "=?", + }, }); -app.component("serviceMain", { +app.component("moduleMain", { templateUrl: - "/mix-app/views/app-portal/pages/service/components/main/view.html", + "/mix-app/views/app-portal/pages/module/components/main/main.html", controller: [ "$rootScope", function ($rootScope) { var ctrl = this; - ctrl.mixConfigurations = $rootScope.globalSettings; + ctrl.localizeSettings = $rootScope.globalSettings; + ctrl.isInRole = $rootScope.isInRole; ctrl.gennerateName = function () { if ( - !ctrl.model.id || - ctrl.model.name === null || - ctrl.model.name === "" + !ctrl.module.id || + ctrl.module.systemName === null || + ctrl.module.systemName === "" ) { - ctrl.model.name = $rootScope.generateKeyword(ctrl.model.title, "_"); + ctrl.module.systemName = $rootScope.generateKeyword( + ctrl.module.title, + "_", + true, + true + ); } }; }, ], bindings: { - model: "=", + module: "=", }, }); -app.component("themeExportCultures", { - templateUrl: - "/mix-app/views/app-portal/pages/theme/components/theme-export-cultures/view.html", - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - function ($rootScope, $scope, ngAppSettings) { - var ctrl = this; - var service = $rootScope.getRestService("culture"); - ctrl.selectAllContent = false; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.$onInit = async () => { - ctrl.getList(); - }; - ctrl.getList = async (cultureIndex) => { - if (cultureIndex !== undefined) { - ctrl.request.cultureIndex = cultureIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var d = new Date(ctrl.request.toDate); - ctrl.request.toDate = d.toISOString(); - } - let getData = await service.getList(ctrl.request); - if (getData.success) { - ctrl.data = getData.data; - } - }; - ctrl.selectContent = (culture, selected) => { - ctrl.selectAllContent = ctrl.selectAllContent && selected; - ctrl.selectAllData = ctrl.selectAllData && selected; - culture.isExportData = selected && culture.isExportData; - ctrl.updateContent([culture.id], selected); - }; - ctrl.updateContent = function (arr, selected) { - if (selected) { - ctrl.exportThemeDto.cultureIds = ctrl.unionArray( - ctrl.exportThemeDto.cultureIds, - arr - ); - } else { - ctrl.exportThemeDto.cultureIds = - ctrl.exportThemeDto.cultureIds.filter((m) => arr.indexOf(m) < 0); - ctrl.updateData(arr, false); - } - }; - ctrl.selectAll = function (arr) { - // ctrl.selectedList.data = []; - var ids = arr.map(function (obj) { - return obj.id; - }); - ctrl.updateContent(ids, ctrl.selectAllContent); - angular.forEach(arr, function (e) { - e.isActived = ctrl.selectAllContent; - }); - }; - ctrl.unionArray = (a, b) => { - return [...new Set([...a, ...b])]; - }; - }, - ], - bindings: { - exportThemeDto: "=", +app.component("moduleAdvanced", { + templateUrl: + "/mix-app/views/app-portal/pages/module/components/module-advanced/view.html", + bindings: { + model: "=", + additionalData: "=", + }, + controller: [ + "$rootScope", + function ($rootScope) { + var ctrl = this; + ctrl.mixConfigurations = $rootScope.globalSettings; + ctrl.$onInit = function () { + ctrl.isAdmin = $rootScope.isAdmin; + }; }, + ], }); -app.component("themeExportMixDatabases", { +app.component("moduleContent", { templateUrl: - "/mix-app/views/app-portal/pages/theme/components/theme-export-mix-databases/view.html", + "/mix-app/views/app-portal/pages/module/components/module-content/view.html", + bindings: { + model: "=", + additionalData: "=", + }, controller: [ "$rootScope", - "$scope", - "ngAppSettings", - function ($rootScope, $scope, ngAppSettings) { + function ($rootScope) { var ctrl = this; - var service = $rootScope.getRestService("mix-database"); - ctrl.selectAllContent = false; - ctrl.selectAllData = false; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.$onInit = async () => { - ctrl.request.pageSize = null; - ctrl.getList(); - }; - ctrl.getList = async (mixDatabaseIndex) => { - if (mixDatabaseIndex !== undefined) { - ctrl.request.mixDatabaseIndex = mixDatabaseIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var d = new Date(ctrl.request.toDate); - ctrl.request.toDate = d.toISOString(); - } - let getData = await service.getList(ctrl.request); - if (getData.success) { - ctrl.data = getData.data; - } - }; - ctrl.selectContent = (mixDatabase, selected) => { - ctrl.selectAllContent = ctrl.selectAllContent && selected; - ctrl.selectAllData = ctrl.selectAllData && selected; - mixDatabase.isExportData = selected && mixDatabase.isExportData; - ctrl.exportThemeDto.content.mixDatabaseIds = ctrl.updateArray( - ctrl.exportThemeDto.content.mixDatabaseIds, - [mixDatabase.id], - selected - ); - if (!selected) { - ctrl.selectData(mixDatabase, false); - } - }; - ctrl.selectData = (mixDatabase, selected) => { - ctrl.selectAllData = ctrl.selectAllData && selected; - ctrl.exportThemeDto.associations.mixDatabaseIds = ctrl.updateArray( - ctrl.exportThemeDto.associations.mixDatabaseIds, - [mixDatabase.id], - selected - ); - }; - ctrl.updateArray = function (src, arr, selected) { - if (selected) { - src = ctrl.unionArray(src, arr); - } else { - src = src.filter((m) => arr.indexOf(m) < 0); - } - return src; - }; - ctrl.selectAll = function (arr) { - angular.forEach(arr, function (e) { - ctrl.selectContent(e, ctrl.selectAllContent); - ctrl.selectData(e, ctrl.selectAllData); - e.isActived = ctrl.selectAllContent; - e.isExportData = ctrl.selectAllData; - }); - }; - ctrl.unionArray = (a, b) => { - return [...new Set([...a, ...b])]; + ctrl.$onInit = function () { + ctrl.backUrl = `/admin/module/details`; }; + ctrl.mixConfigurations = $rootScope.globalSettings; }, ], - bindings: { - exportThemeDto: "=", - }, }); -app.component("themeExportModules", { +app.component("moduleType", { templateUrl: - "/mix-app/views/app-portal/pages/theme/components/theme-export-modules/view.html", + "/mix-app/views/app-portal/pages/module/components/module-type/view.html", controller: [ "$rootScope", - "$scope", - "ngAppSettings", - function ($rootScope, $scope, ngAppSettings) { + function ($rootScope) { var ctrl = this; - var service = $rootScope.getRestService("mix-module"); - ctrl.selectAllContent = false; - ctrl.selectAllData = false; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.$onInit = async () => { - ctrl.request.pageSize = null; - ctrl.getList(); - }; - ctrl.getList = async (moduleIndex) => { - if (moduleIndex !== undefined) { - ctrl.request.moduleIndex = moduleIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var d = new Date(ctrl.request.toDate); - ctrl.request.toDate = d.toISOString(); - } - let getData = await service.getList(ctrl.request); - if (getData.success) { - ctrl.data = getData.data; - } - }; - ctrl.selectContent = (module, selected) => { - ctrl.selectAllContent = ctrl.selectAllContent && selected; - ctrl.selectAllData = ctrl.selectAllData && selected; - module.isExportData = selected && module.isExportData; - let contentIds = module.contents.map(function (obj) { - return obj.id; - }); - ctrl.exportThemeDto.content.moduleIds = ctrl.updateArray( - ctrl.exportThemeDto.content.moduleIds, - [module.id], - selected - ); - ctrl.exportThemeDto.content.moduleContentIds = ctrl.updateArray( - ctrl.exportThemeDto.content.moduleContentIds, - contentIds, - selected - ); - if (!selected) { - ctrl.selectData(module, false); - } - }; - ctrl.selectData = (module, selected) => { - ctrl.selectAllData = ctrl.selectAllData && selected; - let contentIds = module.contents.map(function (obj) { - return obj.id; - }); - ctrl.exportThemeDto.associations.moduleIds = ctrl.updateArray( - ctrl.exportThemeDto.associations.moduleIds, - [module.id], - selected - ); - ctrl.exportThemeDto.associations.moduleContentIds = ctrl.updateArray( - ctrl.exportThemeDto.associations.moduleContentIds, - contentIds, - selected - ); - }; - ctrl.updateArray = function (src, arr, selected) { - if (selected) { - src = ctrl.unionArray(src, arr); - } else { - src = src.filter((m) => arr.indexOf(m) < 0); - } - return src; - }; - ctrl.selectAll = function (arr) { - angular.forEach(arr, function (e) { - ctrl.selectContent(e, ctrl.selectAllContent); - ctrl.selectData(e, ctrl.selectAllData); - e.isActived = ctrl.selectAllContent; - e.isExportData = ctrl.selectAllData; - }); - }; - ctrl.unionArray = (a, b) => { - return [...new Set([...a, ...b])]; - }; + ctrl.mixConfigurations = $rootScope.globalSettings; }, ], bindings: { - exportThemeDto: "=", + model: "=", }, }); -app.component("themeExportPages", { +app.component("mixdbContextDatabases", { + bindings: { + model: "=", + }, templateUrl: - "/mix-app/views/app-portal/pages/theme/components/theme-export-pages/view.html", + "/mix-app/views/app-portal/pages/mixdb-context/components/mix-databases/view.html", controller: [ "$rootScope", "$scope", - "ngAppSettings", - function ($rootScope, $scope, ngAppSettings) { + "RestMixDatabasePortalService", + function ($rootScope, $scope, databaseService) { var ctrl = this; - var service = $rootScope.getRestService("mix-page"); - ctrl.selectAllContent = false; - ctrl.selectAllData = false; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.$onInit = async () => { - ctrl.request.pageSize = null; - ctrl.getList(); - }; - ctrl.getList = async (pageIndex) => { - if (pageIndex !== undefined) { - ctrl.request.pageIndex = pageIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var d = new Date(ctrl.request.toDate); - ctrl.request.toDate = d.toISOString(); - } - let getData = await service.getList(ctrl.request); - if (getData.success) { - ctrl.data = getData.data; - } - }; - ctrl.selectContent = (page, selected) => { - ctrl.selectAllContent = ctrl.selectAllContent && selected; - ctrl.selectAllData = ctrl.selectAllData && selected; - page.isExportData = selected && page.isExportData; - let contentIds = page.contents.map(function (obj) { - return obj.id; - }); - ctrl.exportThemeDto.content.pageIds = ctrl.updateArray( - ctrl.exportThemeDto.content.pageIds, - [page.id], - selected - ); - ctrl.exportThemeDto.content.pageContentIds = ctrl.updateArray( - ctrl.exportThemeDto.content.pageContentIds, - contentIds, - selected - ); - if (!selected) { - ctrl.selectData(page, false); - } - }; - ctrl.selectData = (page, selected) => { - ctrl.selectAllData = ctrl.selectAllData && selected; - let contentIds = page.contents.map(function (obj) { - return obj.id; - }); - ctrl.exportThemeDto.associations.pageIds = ctrl.updateArray( - ctrl.exportThemeDto.associations.pageIds, - [page.id], - selected - ); - ctrl.exportThemeDto.associations.pageContentIds = ctrl.updateArray( - ctrl.exportThemeDto.associations.pageContentIds, - contentIds, - selected - ); + ctrl.request = $rootScope.getRequest(); + ctrl.$onInit = () => { + ctrl.globalSettings = $rootScope.globalSettings; + ctrl.isInRole = $rootScope.isInRole; + ctrl.request.mixDatabaseContextId = ctrl.model.id; + ctrl.loadDatabases(); }; - ctrl.updateArray = function (src, arr, selected) { - if (selected) { - src = ctrl.unionArray(src, arr); - } else { - src = src.filter((m) => arr.indexOf(m) < 0); + ctrl.loadDatabases = async function () { + if (ctrl.model.id) { + var resp = await databaseService.getList(ctrl.request); + if (resp && resp.success) { + ctrl.data = resp.data; + $scope.$apply(); + } } - return src; - }; - ctrl.selectAll = function (arr) { - angular.forEach(arr, function (e) { - ctrl.selectContent(e, ctrl.selectAllContent); - ctrl.selectData(e, ctrl.selectAllData); - e.isActived = ctrl.selectAllContent; - e.isExportData = ctrl.selectAllData; - }); - }; - ctrl.unionArray = (a, b) => { - return [...new Set([...a, ...b])]; }; }, ], - bindings: { - exportThemeDto: "=", - }, }); -app.component("themeExportPosts", { - templateUrl: - "/mix-app/views/app-portal/pages/theme/components/theme-export-posts/view.html", - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "BaseRestService", - function ($rootScope, $scope, ngAppSettings, baseRestService) { +app.component("pageGeneral", { + templateUrl: + "/mix-app/views/app-portal/pages/page/components/general/general.html", + controller: function ($rootScope) { + var ctrl = this; + ctrl.isInRole = $rootScope.isInRole; + ctrl.dataTypes = [ + { + title: "String", + value: "text", + }, + { + title: "Int", + value: "int", + }, + { + title: "Image", + value: "image", + }, + { + title: "Boolean", + value: "boolean", + }, + ]; + ctrl.configurations = { + core: {}, + plugins: { + btnsDef: { + // Customizables dropdowns + image: { + dropdown: ["insertImage", "upload", "base64", "noembed"], + ico: "insertImage", + }, + }, + btns: [ + ["viewHTML"], + ["undo", "redo"], + ["formatting"], + ["strong", "em", "del", "underline"], + ["link"], + ["image"], + ["justifyLeft", "justifyCenter", "justifyRight", "justifyFull"], + ["unorderedList", "orderedList"], + ["foreColor", "backColor"], + ["preformatted"], + ["horizontalRule"], + ["fullscreen"], + ], + plugins: { + // Add imagur parameters to upload plugin + upload: { + serverPath: "https://api.imgur.com/3/image", + fileFieldName: "image", + headers: { + Authorization: "Client-ID 9e57cb1c4791cea", + }, + urlPropertyName: "data.link", + }, + }, + }, + }; + ctrl.addProperty = function (type) { + var i = $(".property").length; + ctrl.page.properties.push({ + priority: 0, + name: "", + value: null, + dataType: 0, + }); + }; + ctrl.initEditor = function () { + setTimeout(function () { + // Init Code editor + $.each($(".code-editor"), function (i, e) { + var container = $(this); + var editor = ace.edit(e); + if (container.hasClass("json")) { + editor.session.setMode("ace/mode/json"); + } else { + editor.session.setMode("ace/mode/razor"); + } + editor.setTheme("ace/theme/chrome"); + //editor.setReadOnly(true); + + editor.session.setUseWrapMode(true); + editor.setOptions({ + maxLines: Infinity, + }); + editor.getSession().on("change", function (e) { + // e.type, etc + $(container).parent().find(".code-content").val(editor.getValue()); + }); + }); + $.each($(".editor-content"), function (i, e) { + var $demoTextarea = $(e); + $demoTextarea.quill(ctrl.configurations.plugins); + }); + }, 200); + }; + }, + bindings: { + page: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("pageMain", { + templateUrl: "/mix-app/views/app-portal/pages/page/components/main/main.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + function ($rootScope, $scope) { + var ctrl = this; + ctrl.mixConfigurations = $rootScope.globalSettings; + // ctrl.setPageType = function (type) { + // ctrl.page.type = $index; + // } + ctrl.generateSeo = function () { + if (ctrl.page) { + if (ctrl.page.seoName === null || ctrl.page.seoName === "") { + ctrl.page.seoName = $rootScope.generateKeyword( + ctrl.page.title, + "-" + ); + } + if (ctrl.page.seoTitle === null || ctrl.page.seoTitle === "") { + ctrl.page.seoTitle = ctrl.page.title; + } + if ( + ctrl.page.seoDescription === null || + ctrl.page.seoDescription === "" + ) { + ctrl.page.seoDescription = ctrl.page.excerpt; + } + if (ctrl.page.seoKeywords === null || ctrl.page.seoKeywords === "") { + ctrl.page.seoKeywords = ctrl.page.title; + } + } + }; + }, + ], + bindings: { + page: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("pageModules", { + templateUrl: + "/mix-app/views/app-portal/pages/page/components/modules/modules.html", + bindings: { + page: "=", + onDelete: "&?", + onUpdate: "&?", + }, + controller: [ + "$scope", + "ngAppSettings", + "ModuleRestService", + function ($scope, ngAppSettings, moduleService) { + var ctrl = this; + ctrl.modules = []; + ctrl.request = angular.copy(ngAppSettings.request); + + ctrl.$onInit = async () => { + ctrl.request.columns = [ + "id", + "title", + "systemName", + "createdDateTime", + "type", + ]; + ctrl.request.culture = ctrl.page.specificulture; + ctrl.loadModules(); + }; + ctrl.loadModules = async () => { + let getModules = await moduleService.getList(ctrl.request); + if (getModules.success) { + ctrl.modules = getModules.data.items; + $scope.$apply(); + } + }; + ctrl.select = async (associations) => { + ctrl.associations = associations; + if (ctrl.onUpdate) { + ctrl.onUpdate({ associations: associations }); + } + }; + }, + ], +}); + +app.component("pageAdvanced", { + templateUrl: + "/mix-app/views/app-portal/pages/page/components/page-advanced/view.html", + bindings: { + model: "=", + additionalData: "=", + }, + controller: [ + "$rootScope", + "$scope", + function ($rootScope, $scope) { + var ctrl = this; + + ctrl.translate = $rootScope.translate; + ctrl.$onInit = function () { + ctrl.isAdmin = $rootScope.isAdmin; + }; + }, + ], +}); + +app.component("pageContent", { + templateUrl: + "/mix-app/views/app-portal/pages/page/components/page-content/view.html", + bindings: { + additionalData: "=", + model: "=", + }, + controller: [ + "$rootScope", + "$scope", + function ($rootScope, $scope) { + var ctrl = this; + ctrl.translate = $rootScope.translate; + ctrl.$onInit = function () { + ctrl.backUrl = `/admin/page/details`; + }; + ctrl.generateSeo = function () { + if ($scope.viewmodel) { + if (ctrl.model.seoName === null || ctrl.model.seoName === "") { + ctrl.model.seoName = $rootScope.generateKeyword( + ctrl.model.title, + "-" + ); + } + if (ctrl.model.seoTitle === null || ctrl.model.seoTitle === "") { + ctrl.model.seoTitle = ctrl.model.title; + } + if ( + ctrl.model.seoDescription === null || + ctrl.model.seoDescription === "" + ) { + ctrl.model.seoDescription = ctrl.model.excerpt; + } + if ( + ctrl.model.seoKeywords === null || + ctrl.model.seoKeywords === "" + ) { + ctrl.model.seoKeywords = ctrl.model.title; + } + } + }; + }, + ], +}); + +app.component("pageType", { + templateUrl: + "/mix-app/views/app-portal/pages/page/components/page-type/view.html", + bindings: { + model: "=", + }, + controller: [ + "$rootScope", + function ($rootScope) { + var ctrl = this; + ctrl.localizeSettings = $rootScope.globalSettings; + }, + ], +}); + +app.component("pageParents", { + templateUrl: + "/mix-app/views/app-portal/pages/page/components/parents/parents.html", + bindings: { + page: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("pagePlugPlay", { + templateUrl: + "/mix-app/views/app-portal/pages/page/components/plug-play/plug-play.html", + bindings: { + page: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("productRelated", { + templateUrl: + "/mix-app/views/app-portal/pages/product/components/related/productRelated.html", + controller: function () { + var ctrl = this; + ctrl.activeProduct = function (pr) { + var currentItem = null; + $.each(ctrl.product.productNavs, function (i, e) { + if (e.relatedProductId === pr.id) { + e.isActived = pr.isActived; + currentItem = e; + return false; + } + }); + if (currentItem === null) { + currentItem = { + relatedProductId: pr.id, + sourceProductId: ctrl.product.id, + specificulture: ctrl.product.specificulture, + priority: ctrl.product.productNavs.length + 1, + relatedProduct: pr, + isActived: true, + }; + pr.isHidden = true; + ctrl.product.productNavs.push(currentItem); + } + }; + }, + bindings: { + product: "=", + list: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("pageSeo", { + templateUrl: "/mix-app/views/app-portal/pages/page/components/seo/seo.html", + controller: [ + "$rootScope", + function ($rootScope) { + var ctrl = this; + ctrl.translate = function (keyword) { + return $rootScope.translate(keyword); + }; + }, + ], + bindings: { + page: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("permissionMain", { + templateUrl: + "/mix-app/views/app-portal/pages/permission/components/main/main.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "$routeParams", + function ($rootScope, $scope, ngAppSettings, $routeParams) { + var ctrl = this; + ctrl.mixConfigurations = $rootScope.globalSettings; + ctrl.icons = ngAppSettings.icons; + ctrl.setPageType = function (type) { + ctrl.page.type = $index; + }; + ctrl.generateKeyword = function (text) { + if (!$routeParams.id && text) { + ctrl.page.textKeyword = + "portal_" + + text + .replace(/[^a-zA-Z0-9]+/g, "_") + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2") + .replace(/([a-z])([A-Z])/g, "$1-$2") + .replace(/([0-9])([^0-9])/g, "$1-$2") + .replace(/([^0-9])([0-9])/g, "$1-$2") + .replace(/-+/g, "_") + .toLowerCase(); + } + }; + }, + ], + bindings: { + page: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("permissionParents", { + templateUrl: + "/mix-app/views/app-portal/pages/permission/components/parents/parents.html", + bindings: { + page: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("permissionPlugPlay", { + templateUrl: + "/mix-app/views/app-portal/pages/permission/components/plug-play/plug-play.html", + bindings: { + page: "=", + prefixParent: "=", + prefixChild: "=", + searchText: "=", + onDelete: "&", + onUpdate: "&", + }, + controller: [ + "$rootScope", + "$scope", + "$location", + "$element", + "PermissionService", + function ($rootScope, $scope, $location, $element, service) { + var ctrl = this; + ctrl.type = "Children"; + ctrl.goToPath = $rootScope.goToPath; + ctrl.request = { + pageSize: "5", + pageIndex: 0, + status: "Published", + orderBy: "CreatedDateTime", + direction: "Desc", + fromDate: null, + toDate: null, + }; + ctrl.pages = []; + ctrl.init = function () { + if (ctrl.page) { + ctrl.request.exceptIds = ctrl.page.parentNavs + .map((p) => p.pageId) + .concat(ctrl.page.childNavs.map((p) => p.pageId)); + if (ctrl.request.exceptIds.indexOf(ctrl.page.id) === -1) { + ctrl.request.exceptIds.push(ctrl.page.id); + } + ctrl.getList(); + } + }; + ctrl.selectPane = function (pane) { + if (ctrl.page) { + ctrl.type = pane.header; + ctrl.request.keyword = ""; + ctrl.init(); + } + }; + + ctrl.selectItem = (nav) => { + if (ctrl.type == "Parents") { + if ( + !$rootScope.findObjectByKey(ctrl.page.parentNavs, "pageId", nav.id) + ) { + ctrl.page.parentNavs.push({ + isActived: true, + pageId: ctrl.page.id, + parentId: nav.id, + description: nav.textDefault, + status: "Published", + parent: nav, + }); + } + } else { + if ( + !$rootScope.findObjectByKey(ctrl.page.childNavs, "pageId", nav.id) + ) { + ctrl.page.childNavs.push({ + isActived: true, + pageId: nav.id, + parentId: ctrl.page.id, + description: nav.textDefault, + status: "Published", + page: nav, + }); + } + } + }; + + ctrl.getList = async function () { + $rootScope.isBusy = true; + var resp = await service.getList(ctrl.request); + if (resp && resp.success) { + ctrl.pages = resp.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors || ["Failed"]); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + }, + ], +}); + +modules.component("postFilterList", { + templateUrl: + "/mix-app/views/app-portal/pages/post/components/filter-list/filter-list.html", + bindings: { + request: "=", + key: "=?", + orders: "=?", + createUrl: "=", + createText: "=", + categories: "=", + postTypes: "=", + callback: "&", + }, + controller: [ + "$scope", + "$rootScope", + "ngAppSettings", + "RestMixDatabaseDataPortalService", + "CultureService", + function ($scope, $rootScope, ngAppSettings, dataService, cultureService) { + var ctrl = this; + ctrl.dateRange = { + fromDate: null, + toDate: null, + }; + ctrl.request = angular.copy(ngAppSettings.request); + + ctrl.init = function () { + if (!ctrl.orders) { + ctrl.orders = ngAppSettings.orders; + } + ctrl.directions = ngAppSettings.directions; + ctrl.pageSizes = ngAppSettings.pageSizes; + ctrl.statuses = []; + var statuses = ngAppSettings.contentStatuses; + if (ctrl.request && ctrl.request.contentStatuses) { + statuses = ctrl.request.contentStatuses; + } + angular.forEach(statuses, function (val, i) { + ctrl.statuses.push({ + value: val, + title: val, + }); + }); + }; + ctrl.addMetadataQuery = () => { + ctrl.request.metadataQueries.push({ + fieldName: "", + value: "", + isRequired: false, + }); + }; + ctrl.clearMetadataQuery = () => { + ctrl.request.metadataQueries = []; + ctrl.apply(); + }; + ctrl.changeLang = function (culture) { + if (culture) { + ctrl.selectedCulture = culture; + ctrl.request.culture = culture.specificulture; + } else { + ctrl.selectedCulture = null; + ctrl.request.culture = null; + } + ctrl.apply(0); + }; + ctrl.apply = function (pageIndex) { + $rootScope.setRequest(ctrl.request, ctrl.key); + ctrl.callback({ pageIndex: pageIndex }); + }; + ctrl.updateDate = function () { + if (Date.parse(ctrl.dateRange.fromDate)) { + ctrl.request.fromDate = new Date( + ctrl.dateRange.fromDate + ).toISOString(); + } else { + $scope.request.fromDate = null; + } + if (Date.parse(ctrl.dateRange.toDate)) { + ctrl.request.toDate = new Date(ctrl.dateRange.toDate).toISOString(); + } else { + ctrl.request.toDate = null; + } + $rootScope.setRequest(ctrl.request, ctrl.key); + ctrl.callback({ pageIndex: 0 }); + }; + }, + ], +}); + +app.component("postGeneral", { + templateUrl: + "/mix-app/views/app-portal/pages/post/components/general/view.html", + controller: [ + "$rootScope", + "ngAppSettings", + function ($rootScope, ngAppSettings) { + var ctrl = this; + ctrl.dataTypes = $rootScope.globalSettings.dataTypes; + ctrl.$onInit = function () {}; + ctrl.addProperty = function (type) { + var i = $(".property").length; + ctrl.post.properties.push({ + title: "", + name: "", + value: null, + dataType: "text", + }); + }; + }, + ], + bindings: { + post: "=", + isAdmin: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("postMain", { + templateUrl: "/mix-app/views/app-portal/pages/post/components/main/view.html", + bindings: { + post: "=", + }, + controller: [ + "$rootScope", + "$scope", + function ($rootScope, $scope) { + var ctrl = this; + ctrl.translate = $rootScope.translate; + ctrl.generateSeo = function () { + if (ctrl.post) { + if (!ctrl.post.seoName) { + ctrl.post.seoName = $rootScope.generateKeyword( + ctrl.post.title, + "-" + ); + } + if (!ctrl.post.seoTitle) { + ctrl.post.seoTitle = ctrl.post.title; + } + if (!ctrl.post.seoDescription === null) { + ctrl.post.seoDescription = ctrl.post.excerpt; + } + if (!ctrl.post.seoKeywords) { + ctrl.post.seoKeywords = ctrl.post.title; + } + } + }; + }, + ], +}); + +app.component("postMedias", { + templateUrl: + "/mix-app/views/app-portal/pages/post/components/medias/view.html", + controller: function () { + var ctrl = this; + ctrl.activeMedia = function (media) { + var currentItem = null; + if (ctrl.post.mediaNavs === null) { + ctrl.post.mediaNavs = []; + } + $.each(ctrl.post.mediaNavs, function (i, e) { + if (e.mediaId === media.id) { + e.isActived = media.isActived; + currentItem = e; + return false; + } + }); + if (currentItem === null) { + currentItem = { + description: + media.description !== "undefined" ? media.description : "", + image: media.filePath, + mediaId: media.id, + post: ctrl.post.id, + specificulture: media.specificulture, + position: 0, + priority: ctrl.post.mediaNavs.length + 1, + isActived: true, + }; + media.isHidden = true; + ctrl.post.mediaNavs.push(currentItem); + } + }; + }, + bindings: { + post: "=", + medias: "=", + loadMedia: "&", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("postModules", { + templateUrl: + "/mix-app/views/app-portal/pages/post/components/modules/view.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "SharedModuleDataService", + function ($rootScope, $scope, ngAppSettings, moduleDataService) { + var ctrl = this; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.translate = function (keyword, wrap, defaultValue) { + return $rootScope.translate(keyword, wrap, defaultValue); + }; + + ctrl.removeData = function (id, moduleContentId) { + $rootScope.showConfirm( + ctrl, + "removeDataConfirmed", + [id, moduleContentId], + null, + "Remove Data", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + }; + ctrl.removeDataConfirmed = async function (id, moduleContentId) { + $rootScope.isBusy = true; + var result = await moduleDataService.removeModuleData(id); + if (result.success) { + ctrl.loadModuleDatas(moduleContentId); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + ctrl.saveDataCallback = function (data) { + if (data) { + ctrl.loadModuleDatas(data.moduleContentId); + } + }; + ctrl.loadModuleDatas = async function (id, pageIndex) { + $rootScope.isBusy = true; + $scope.dataColumns = []; + var request = angular.copy(ngAppSettings.request); + request.query = "?moduleContentId=" + id + "&post_id=" + ctrl.post.id; + if (pageIndex) { + request.pageIndex = pageIndex; + } + var response = await moduleDataService.getModuleDatas(request); + if (response.success) { + var nav = $rootScope.findObjectByKey( + ctrl.post.moduleNavs, + "moduleContentId", + id + ); + if (nav) { + nav.module.data = response.data; + } + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + + ctrl.updateDataInfos = async function (items) { + $rootScope.isBusy = true; + var resp = await moduleDataService.updateInfos(items); + if (resp && resp.success) { + $scope.activedPage = resp.data; + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + }, + ], + bindings: { + post: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("postParents", { + templateUrl: + "/mix-app/views/app-portal/pages/post/components/parents/view.html", + bindings: { + post: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +app.component("postAdvanced", { + templateUrl: + "/mix-app/views/app-portal/pages/post/components/post-advanced/view.html", + bindings: { + model: "=", + additionalData: "=", + }, + controller: [ + "$rootScope", + "$scope", + "$routeParams", + function ($rootScope, $scope, $routeParams) { + var ctrl = this; + ctrl.translate = $rootScope.translate; + ctrl.$onInit = function () { + ctrl.isAdmin = $rootScope.isAdmin; + if ($routeParams.template) { + ctrl.defaultTemplate = $routeParams.template; + } + if ($routeParams.layout) { + ctrl.defaultLayout = $routeParams.layout; + } + }; + }, + ], +}); + +app.component("postContent", { + templateUrl: + "/mix-app/views/app-portal/pages/post/components/post-content/view.html", + bindings: { + model: "=", + additionalData: "=", + loadingData: "=", + }, + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "PostRestService", + function ($rootScope, $scope, ngAppSettings, service) { + var ctrl = this; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.translate = $rootScope.translate; + ctrl.relatedData = {}; + ctrl.$onInit = function () { + ctrl.backUrl = `/admin/post/details`; + }; + ctrl.generateSeo = function () { + if (ctrl.model) { + if (ctrl.model.seoName === null || ctrl.model.seoName === "") { + ctrl.model.seoName = $rootScope.generateKeyword( + ctrl.model.title, + "-" + ); + } + if (ctrl.model.seoTitle === null || ctrl.model.seoTitle === "") { + ctrl.model.seoTitle = ctrl.model.title; + } + if ( + ctrl.model.seoDescription === null || + ctrl.model.seoDescription === "" + ) { + ctrl.model.seoDescription = ctrl.model.excerpt; + } + if ( + ctrl.model.seoKeywords === null || + ctrl.model.seoKeywords === "" + ) { + ctrl.model.seoKeywords = ctrl.model.title; + } + } + }; + ctrl.getListRelated = async function (pageIndex) { + if (pageIndex !== undefined) { + ctrl.request.pageIndex = pageIndex; + } + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = d.toISOString(); + } + if (ctrl.request.toDate !== null) { + var d = new Date(ctrl.request.toDate); + ctrl.request.toDate = d.toISOString(); + } + var resp = await service.getList(ctrl.request); + if (resp && resp.success) { + ctrl.relatedData = angular.copy(resp.data); + ctrl.relatedData.items = []; + angular.forEach(resp.data.items, (element) => { + var existed = $rootScope.findObjectByKey( + ctrl.model.postNavs, + ["sourceId", "destinationId"], + [ctrl.model.id, element.id] + ); + + var obj = { + description: element.title, + destinationId: element.id, + image: element.image, + isActived: existed !== null, + sourceId: ctrl.model.id, + specificulture: ctrl.model.specificulture, + status: "Published", + }; + + ctrl.relatedData.items.push(obj); + }); + console.log(ctrl.relatedData); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(getData.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + }, + ], +}); + +modules.component("relatedPosts", { + templateUrl: + "/mix-app/views/app-portal/pages/post/components/related-navigations/view.html", + bindings: { + title: "=", + parentId: "=", + parentType: "=", + description: "=?", + postTypes: "=?", + mixDatabaseName: "=?", + image: "=?", + }, + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "PostPostRestService", + "PostRestService", + function ($rootScope, $scope, ngAppSettings, service, postService) { + var ctrl = this; + ctrl.selected = null; + ctrl.posts = { + items: [], + }; + ctrl.data = { + items: [], + }; + ctrl.$onInit = async () => { + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.postRequest = angular.copy(ngAppSettings.request); + ctrl.postRequest.searchColumns = "title,excerpt"; + if (ctrl.mixDatabaseName) { + ctrl.postRequest.mixDatabaseName = ctrl.mixDatabaseName; + } + ctrl.postRequest.pageSize = 5; + await ctrl.loadRelatedPosts(); + await ctrl.loadPosts(); + }; + ctrl.addRelatedPost = async (post) => { + var tmp = ctrl.data.items.find( + (m) => m.child.id == post.id || m.parentId == post.id + ); + if (!tmp) { + if (post) { + let dto = { + parentId: ctrl.parentId, + childId: post.id, + }; + var resp = await service.create(dto); + if (resp.success) { + $rootScope.showMessage("Success", "success"); + await ctrl.loadRelatedPosts(); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(resp.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + } + } else { + $rootScope.showMessage(`${post.title} is existed`, "warning"); + } + }; + + ctrl.remove = function (id) { + if ( + confirm( + "Deleted data will not able to recover, are you sure you want to delete this item?" + ) + ) { + ctrl.removeConfirmed(id); + } + }; + + ctrl.removeConfirmed = async function (id) { + $rootScope.isBusy = true; + var result = await service.delete([id]); + if (result.success) { + ctrl.loadRelatedPosts(); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + + ctrl.loadPosts = async (pageIndex) => { + $rootScope.isBusy = true; + if (pageIndex !== undefined) { + ctrl.postRequest.pageIndex = pageIndex; + } + if (ctrl.postRequest.fromDate !== null) { + var d = new Date(ctrl.postRequest.fromDate); + ctrl.postRequest.fromDate = d.toISOString(); + } + if (ctrl.postRequest.toDate !== null) { + var dt = new Date(ctrl.postRequest.toDate); + ctrl.postRequest.toDate = dt.toISOString(); + } + let getData = await postService.filter(ctrl.postRequest); + if (getData.success) { + ctrl.posts = getData.data; + $rootScope.isBusy = false; + } else { + $rootScope.isBusy = false; + $rootScope.showErrors(getData.errors); + } + $scope.$apply(); + }; + + ctrl.loadRelatedPosts = async (pageIndex) => { + if (ctrl.parentId) { + $rootScope.isBusy = true; + if (pageIndex !== undefined) { + ctrl.request.pageIndex = pageIndex; + } + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.postRequest.fromDate); + ctrl.request.fromDate = d.toISOString(); + } + if (ctrl.request.toDate !== null) { + var dt = new Date(ctrl.postRequest.toDate); + ctrl.postRequest.toDate = dt.toISOString(); + } + ctrl.request.parentId = ctrl.parentId; + let getData = await service.search(ctrl.request); + if (getData.success) { + ctrl.data = getData.data; + $rootScope.isBusy = false; + } else { + $rootScope.isBusy = false; + $rootScope.showErrors(getData.errors); + } + $scope.$apply(); + } + }; + }, + ], +}); + +app.component("postSeo", { + templateUrl: "/mix-app/views/app-portal/pages/post/components/seo/view.html", + bindings: { + post: "=", + onDelete: "&", + onUpdate: "&", + }, +}); + +modules.component("rolePageNav", { + templateUrl: + "/mix-app/views/app-portal/pages/role/components/role-page-navigation/role-page-navigations.html", + bindings: { + prefix: "=", + page: "=", + callback: "&", + }, + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "RoleService", + function ($rootScope, $scope, ngAppSettings, roleServices) { + var ctrl = this; + ctrl.selected = null; + ctrl.updateOrders = function (index) { + ctrl.data.splice(index, 1); + for (var i = 0; i < ctrl.data.length; i++) { + ctrl.data[i].priority = i + 1; + } + }; + //ctrl.change = async function () { + // //var permission = ctrl.page.navPermission; + // //$rootScope.isBusy = true; + // //var resp = await roleServices.updatePermission(permission); + // //if (resp && resp.success) { + // // $rootScope.showMessage('Update successfully!', 'success'); + // // $rootScope.isBusy = false; + // // $scope.$apply(); + // //} + // //else { + // // if (resp) { $rootScope.showErrors(resp.errors); } + // // $rootScope.isBusy = false; + // // $scope.$apply(); + // //} + //}; + }, + ], +}); + +app.component("serviceMain", { + templateUrl: + "/mix-app/views/app-portal/pages/service/components/main/view.html", + controller: [ + "$rootScope", + function ($rootScope) { + var ctrl = this; + ctrl.mixConfigurations = $rootScope.globalSettings; + ctrl.gennerateName = function () { + if ( + !ctrl.model.id || + ctrl.model.name === null || + ctrl.model.name === "" + ) { + ctrl.model.name = $rootScope.generateKeyword(ctrl.model.title, "_"); + } + }; + }, + ], + bindings: { + model: "=", + }, +}); + +app.component("themeExportCultures", { + templateUrl: + "/mix-app/views/app-portal/pages/theme/components/theme-export-cultures/view.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + function ($rootScope, $scope, ngAppSettings) { + var ctrl = this; + var service = $rootScope.getRestService("culture"); + ctrl.selectAllContent = false; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.$onInit = async () => { + ctrl.getList(); + }; + ctrl.getList = async (cultureIndex) => { + if (cultureIndex !== undefined) { + ctrl.request.cultureIndex = cultureIndex; + } + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = d.toISOString(); + } + if (ctrl.request.toDate !== null) { + var d = new Date(ctrl.request.toDate); + ctrl.request.toDate = d.toISOString(); + } + let getData = await service.getList(ctrl.request); + if (getData.success) { + ctrl.data = getData.data; + } + }; + ctrl.selectContent = (culture, selected) => { + ctrl.selectAllContent = ctrl.selectAllContent && selected; + ctrl.selectAllData = ctrl.selectAllData && selected; + culture.isExportData = selected && culture.isExportData; + ctrl.updateContent([culture.id], selected); + }; + ctrl.updateContent = function (arr, selected) { + if (selected) { + ctrl.exportThemeDto.cultureIds = ctrl.unionArray( + ctrl.exportThemeDto.cultureIds, + arr + ); + } else { + ctrl.exportThemeDto.cultureIds = + ctrl.exportThemeDto.cultureIds.filter((m) => arr.indexOf(m) < 0); + ctrl.updateData(arr, false); + } + }; + ctrl.selectAll = function (arr) { + // ctrl.selectedList.data = []; + var ids = arr.map(function (obj) { + return obj.id; + }); + ctrl.updateContent(ids, ctrl.selectAllContent); + angular.forEach(arr, function (e) { + e.isActived = ctrl.selectAllContent; + }); + }; + ctrl.unionArray = (a, b) => { + return [...new Set([...a, ...b])]; + }; + }, + ], + bindings: { + exportThemeDto: "=", + }, +}); + +app.component("themeExportMixDatabases", { + templateUrl: + "/mix-app/views/app-portal/pages/theme/components/theme-export-mix-databases/view.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + function ($rootScope, $scope, ngAppSettings) { + var ctrl = this; + var service = $rootScope.getRestService("mix-database"); + ctrl.selectAllContent = false; + ctrl.selectAllData = false; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.$onInit = async () => { + ctrl.request.pageSize = null; + ctrl.getList(); + }; + ctrl.getList = async (mixDatabaseIndex) => { + if (mixDatabaseIndex !== undefined) { + ctrl.request.mixDatabaseIndex = mixDatabaseIndex; + } + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = d.toISOString(); + } + if (ctrl.request.toDate !== null) { + var d = new Date(ctrl.request.toDate); + ctrl.request.toDate = d.toISOString(); + } + let getData = await service.getList(ctrl.request); + if (getData.success) { + ctrl.data = getData.data; + } + }; + ctrl.selectContent = (mixDatabase, selected) => { + ctrl.selectAllContent = ctrl.selectAllContent && selected; + ctrl.selectAllData = ctrl.selectAllData && selected; + mixDatabase.isExportData = selected && mixDatabase.isExportData; + ctrl.exportThemeDto.content.mixDatabaseIds = ctrl.updateArray( + ctrl.exportThemeDto.content.mixDatabaseIds, + [mixDatabase.id], + selected + ); + if (!selected) { + ctrl.selectData(mixDatabase, false); + } + }; + ctrl.selectData = (mixDatabase, selected) => { + ctrl.selectAllData = ctrl.selectAllData && selected; + ctrl.exportThemeDto.associations.mixDatabaseIds = ctrl.updateArray( + ctrl.exportThemeDto.associations.mixDatabaseIds, + [mixDatabase.id], + selected + ); + }; + ctrl.updateArray = function (src, arr, selected) { + if (selected) { + src = ctrl.unionArray(src, arr); + } else { + src = src.filter((m) => arr.indexOf(m) < 0); + } + return src; + }; + ctrl.selectAll = function (arr) { + angular.forEach(arr, function (e) { + ctrl.selectContent(e, ctrl.selectAllContent); + ctrl.selectData(e, ctrl.selectAllData); + e.isActived = ctrl.selectAllContent; + e.isExportData = ctrl.selectAllData; + }); + }; + ctrl.unionArray = (a, b) => { + return [...new Set([...a, ...b])]; + }; + }, + ], + bindings: { + exportThemeDto: "=", + }, +}); + +app.component("themeExportModules", { + templateUrl: + "/mix-app/views/app-portal/pages/theme/components/theme-export-modules/view.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + function ($rootScope, $scope, ngAppSettings) { + var ctrl = this; + var service = $rootScope.getRestService("mix-module"); + ctrl.selectAllContent = false; + ctrl.selectAllData = false; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.$onInit = async () => { + ctrl.request.pageSize = null; + ctrl.getList(); + }; + ctrl.getList = async (moduleIndex) => { + if (moduleIndex !== undefined) { + ctrl.request.moduleIndex = moduleIndex; + } + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = d.toISOString(); + } + if (ctrl.request.toDate !== null) { + var d = new Date(ctrl.request.toDate); + ctrl.request.toDate = d.toISOString(); + } + let getData = await service.getList(ctrl.request); + if (getData.success) { + ctrl.data = getData.data; + } + }; + ctrl.selectContent = (module, selected) => { + ctrl.selectAllContent = ctrl.selectAllContent && selected; + ctrl.selectAllData = ctrl.selectAllData && selected; + module.isExportData = selected && module.isExportData; + let contentIds = module.contents.map(function (obj) { + return obj.id; + }); + ctrl.exportThemeDto.content.moduleIds = ctrl.updateArray( + ctrl.exportThemeDto.content.moduleIds, + [module.id], + selected + ); + ctrl.exportThemeDto.content.moduleContentIds = ctrl.updateArray( + ctrl.exportThemeDto.content.moduleContentIds, + contentIds, + selected + ); + if (!selected) { + ctrl.selectData(module, false); + } + }; + ctrl.selectData = (module, selected) => { + ctrl.selectAllData = ctrl.selectAllData && selected; + let contentIds = module.contents.map(function (obj) { + return obj.id; + }); + ctrl.exportThemeDto.associations.moduleIds = ctrl.updateArray( + ctrl.exportThemeDto.associations.moduleIds, + [module.id], + selected + ); + ctrl.exportThemeDto.associations.moduleContentIds = ctrl.updateArray( + ctrl.exportThemeDto.associations.moduleContentIds, + contentIds, + selected + ); + }; + ctrl.updateArray = function (src, arr, selected) { + if (selected) { + src = ctrl.unionArray(src, arr); + } else { + src = src.filter((m) => arr.indexOf(m) < 0); + } + return src; + }; + ctrl.selectAll = function (arr) { + angular.forEach(arr, function (e) { + ctrl.selectContent(e, ctrl.selectAllContent); + ctrl.selectData(e, ctrl.selectAllData); + e.isActived = ctrl.selectAllContent; + e.isExportData = ctrl.selectAllData; + }); + }; + ctrl.unionArray = (a, b) => { + return [...new Set([...a, ...b])]; + }; + }, + ], + bindings: { + exportThemeDto: "=", + }, +}); + +app.component("themeExportPages", { + templateUrl: + "/mix-app/views/app-portal/pages/theme/components/theme-export-pages/view.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + function ($rootScope, $scope, ngAppSettings) { + var ctrl = this; + var service = $rootScope.getRestService("mix-page"); + ctrl.selectAllContent = false; + ctrl.selectAllData = false; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.$onInit = async () => { + ctrl.request.pageSize = null; + ctrl.getList(); + }; + ctrl.getList = async (pageIndex) => { + if (pageIndex !== undefined) { + ctrl.request.pageIndex = pageIndex; + } + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = d.toISOString(); + } + if (ctrl.request.toDate !== null) { + var d = new Date(ctrl.request.toDate); + ctrl.request.toDate = d.toISOString(); + } + let getData = await service.getList(ctrl.request); + if (getData.success) { + ctrl.data = getData.data; + } + }; + ctrl.selectContent = (page, selected) => { + ctrl.selectAllContent = ctrl.selectAllContent && selected; + ctrl.selectAllData = ctrl.selectAllData && selected; + page.isExportData = selected && page.isExportData; + let contentIds = page.contents.map(function (obj) { + return obj.id; + }); + ctrl.exportThemeDto.content.pageIds = ctrl.updateArray( + ctrl.exportThemeDto.content.pageIds, + [page.id], + selected + ); + ctrl.exportThemeDto.content.pageContentIds = ctrl.updateArray( + ctrl.exportThemeDto.content.pageContentIds, + contentIds, + selected + ); + if (!selected) { + ctrl.selectData(page, false); + } + }; + ctrl.selectData = (page, selected) => { + ctrl.selectAllData = ctrl.selectAllData && selected; + let contentIds = page.contents.map(function (obj) { + return obj.id; + }); + ctrl.exportThemeDto.associations.pageIds = ctrl.updateArray( + ctrl.exportThemeDto.associations.pageIds, + [page.id], + selected + ); + ctrl.exportThemeDto.associations.pageContentIds = ctrl.updateArray( + ctrl.exportThemeDto.associations.pageContentIds, + contentIds, + selected + ); + }; + ctrl.updateArray = function (src, arr, selected) { + if (selected) { + src = ctrl.unionArray(src, arr); + } else { + src = src.filter((m) => arr.indexOf(m) < 0); + } + return src; + }; + ctrl.selectAll = function (arr) { + angular.forEach(arr, function (e) { + ctrl.selectContent(e, ctrl.selectAllContent); + ctrl.selectData(e, ctrl.selectAllData); + e.isActived = ctrl.selectAllContent; + e.isExportData = ctrl.selectAllData; + }); + }; + ctrl.unionArray = (a, b) => { + return [...new Set([...a, ...b])]; + }; + }, + ], + bindings: { + exportThemeDto: "=", + }, +}); + +app.component("themeExportPosts", { + templateUrl: + "/mix-app/views/app-portal/pages/theme/components/theme-export-posts/view.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "BaseRestService", + function ($rootScope, $scope, ngAppSettings, baseRestService) { var ctrl = this; var service = angular.copy(baseRestService); service.initService("/rest/mix-portal", "mix-post"); @@ -9632,6 +9631,17 @@ modules.component("layoutPortalHeader", { bindings: {}, }); +modules.component("layoutPortalModals", { + templateUrl: + "/mix-app/views/app-portal/components/_layout-portal-modals/view.html", + controller: [ + function () { + var ctrl = this; + }, + ], + bindings: {}, +}); + modules.component("layoutPortalSidebar", { templateUrl: "/mix-app/views/app-portal/components/_layout-portal-sidebar/view.html", @@ -9643,15 +9653,165 @@ modules.component("layoutPortalSidebar", { bindings: {}, }); -modules.component("layoutPortalModals", { +modules.component("actions", { + templateUrl: "/mix-app/views/app-portal/components/actions/actions.html", + bindings: { + primaryUrl: "=", + primaryTitle: "=", + primaryIcon: "=", + previewUrl: "=", + backUrl: "=", + contentUrl: "=", + onClearCache: "&?", + onSubmit: "&?", + }, + controller: [ + "$rootScope", + "$scope", + "$location", + function ($rootScope, $scope, $location) { + var ctrl = this; + ctrl.visible = $rootScope.visible; + ctrl.back = function () { + if (ctrl.backUrl) { + $location.url(ctrl.backUrl); + } else { + window.history.back(); + } + }; + ctrl.$onInit = function () { + ctrl.isAdmin = $rootScope.isAdmin; + }; + ctrl.submit = function ($event) { + if (ctrl.onSubmit) { + $event.preventDefault(); + ctrl.onSubmit(); + return; + } + }; + ctrl.clearCache = function () { + ctrl.onClearCache(); + }; + }, + ], +}); + +modules.component("additionalColumn", { templateUrl: - "/mix-app/views/app-portal/components/_layout-portal-modals/view.html", + "/mix-app/views/app-portal/components/additional-column/view.html", + bindings: { + model: "=", + additionalData: "=", + }, controller: [ - function () { + "$rootScope", + "$scope", + "RestMixDatabaseColumnPortalService", + "RestMixDatabaseDataPortalService", + function ($rootScope, $scope, columnService, dataService) { var ctrl = this; + ctrl.value = {}; + ctrl.column = { + dataType: "Text", + mixDatabaseName: "sysAdditionalColumn", + mixDatabaseId: 6, + status: "Published", + }; + ctrl.selectedCol = null; + ctrl.mixConfigurations = $rootScope.globalSettings; + ctrl.$onInit = async function () {}; + ctrl.addAttr = async function () { + if (ctrl.column.name) { + var current = $rootScope.findObjectByKey( + ctrl.additionalData.columns, + "name", + ctrl.column.name + ); + if (current) { + $rootScope.showErrors(["Field " + ctrl.column.name + " existed!"]); + } else { + ctrl.column.priority = ctrl.additionalData.columns.length + 1; + $rootScope.isBusy = true; + var saveField = await columnService.create(ctrl.column); + $rootScope.isBusy = false; + if (saveField.success) { + ctrl.additionalData.columns.push(saveField.data); + if (ctrl.additionalData.parentId) { + await dataService.save(ctrl.additionalData); + } + //reset column option + ctrl.column.title = ""; + ctrl.column.name = ""; + ctrl.column.dataType = "Text"; + } else { + $rootScope.showErrors(saveField.errors); + } + $scope.$apply(); + } + } else { + $rootScope.showErrors(["Please add column Name"]); + } + }; + + ctrl.generateName = function (col) { + col.name = $rootScope.generateKeyword(col.title, "_", true, true); + }; + ctrl.showReferences = function (col) { + ctrl.colRef = col; + $("#modal-navs").modal("show"); + }; + ctrl.referenceCallback = async function (selected) { + if (selected && selected.length) { + ctrl.colRef.reference = selected; + ctrl.colRef.referenceId = selected[0].id; + await columnService.save(ctrl.colRef); + } + $("#modal-navs").modal("hide"); + }; + ctrl.updateOrders = function (index) { + if (index > ctrl.dragStartIndex) { + ctrl.additionalData.columns.splice(ctrl.dragStartIndex, 1); + } else { + ctrl.additionalData.columns.splice(ctrl.dragStartIndex + 1, 1); + } + angular.forEach(ctrl.additionalData.columns, function (e, i) { + e.priority = i; + }); + }; + + ctrl.dragStart = function (index) { + ctrl.dragStartIndex = index; + }; + + ctrl.removeAttribute = function (val, index) { + $rootScope.showConfirm( + ctrl, + "removeAttributeConfirmed", + [val, index], + null, + "Remove Field", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + }; + ctrl.removeAttributeConfirmed = async function (val, index) { + if (val.id) { + $rootScope.isBusy = true; + var result = await columnService.delete([val.id]); + if (result.success) { + ctrl.additionalData.columns.splice(index, 1); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + } else { + ctrl.additionalData.columns.splice(index, 1); + } + }; }, ], - bindings: {}, }); modules.component("aceEditor", { @@ -9813,108 +9973,6 @@ modules.component("additionalValue", { ], }); -modules.component("confirm", { - templateUrl: "/mix-app/views/app-portal/components/confirm/confirm.html", - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - function ($rootScope, $scope) { - var ctrl = this; - ctrl.executeFunctionByName = async function ( - functionName, - args, - context - ) { - var result = await $rootScope.executeFunctionByName( - functionName, - args, - context - ); - if (result) { - $scope.$apply(); - } - }; - }, - ], - bindings: { - message: "=", - }, -}); - -modules.component("filterList", { - templateUrl: - "/mix-app/views/app-portal/components/filter-list/filter-list.html", - controller: [ - "$scope", - "$rootScope", - "ngAppSettings", - "CultureService", - function ($scope, $rootScope, ngAppSettings, cultureService) { - var ctrl = this; - ctrl.dateRange = { - fromDate: null, - toDate: null, - }; - ctrl.searchMethods = ["Equal", "Like"]; - ctrl.init = async function () { - if (!ctrl.arrOrderby) { - ctrl.arrOrderby = [ - "Title", - "Priority", - "CreatedDateTime", - "LastModified", - "Status", - ]; - } - ctrl.request.orderBy = ctrl.request.orderBy || ctrl.arrOrderby[0]; - ctrl.directions = ["Asc", "Desc"]; - ctrl.pageSizes = [5, 10, 15, 20]; - ctrl.statuses = $rootScope.globalSettings.statuses; - }; - ctrl.changeLang = function (culture) { - if (culture) { - ctrl.selectedCulture = culture; - ctrl.request.culture = culture.specificulture; - } else { - ctrl.selectedCulture = null; - ctrl.request.culture = null; - } - ctrl.apply(0); - }; - ctrl.apply = function (pageIndex) { - $rootScope.setRequest(ctrl.request, ctrl.key); - ctrl.callback({ pageIndex: pageIndex }); - }; - ctrl.updateDate = function () { - ctrl.request.pageIndex = 0; - if (Date.parse(ctrl.dateRange.fromDate)) { - ctrl.request.fromDate = new Date( - ctrl.dateRange.fromDate - ).toISOString(); - } else { - $scope.request.fromDate = null; - } - if (Date.parse(ctrl.dateRange.toDate)) { - ctrl.request.toDate = new Date(ctrl.dateRange.toDate).toISOString(); - } else { - ctrl.request.toDate = null; - } - $rootScope.setRequest(ctrl.request, ctrl.key); - ctrl.callback({ pageIndex: 0 }); - }; - }, - ], - bindings: { - request: "=", - key: "=?", - arrOrderby: "=?", - createUrl: "=", - createText: "=", - callback: "&", - }, -}); - modules.component("customImage", { templateUrl: "/mix-app/views/app-portal/components/custom-image/custom-image.html", @@ -10013,73 +10071,175 @@ modules.component("customImage", { mediaService.openCroppie(ctrl.file, ctrl, true); } }; - - ctrl.uploadFile = async function (file) { - if (file !== null) { - $rootScope.isBusy = true; - var resp = await mediaService.uploadMedia(file); - if (resp && resp.success) { - ctrl.src = resp.data; - ctrl.srcUrl = resp.data; - ctrl.isImage = ctrl.srcUrl - .toLowerCase() - .match(/([/|.|\w|\s|-])*\.(?:jpg|jpeg|gif|png|svg)/g); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } + + ctrl.uploadFile = async function (file) { + if (file !== null) { + $rootScope.isBusy = true; + var resp = await mediaService.uploadMedia(file); + if (resp && resp.success) { + ctrl.src = resp.data; + ctrl.srcUrl = resp.data; + ctrl.isImage = ctrl.srcUrl + .toLowerCase() + .match(/([/|.|\w|\s|-])*\.(?:jpg|jpeg|gif|png|svg)/g); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + } else { + return null; + } + }; + + ctrl.getBase64 = function (file) { + if (file !== null) { + $rootScope.isBusy = true; + var reader = new FileReader(); + reader.readAsDataURL(file); + reader.onload = function () { + var index = reader.result.indexOf(",") + 1; + var base64 = reader.result.substring(index); + if (ctrl.postedFile) { + ctrl.postedFile.fileName = file.name.substring( + 0, + file.name.lastIndexOf(".") + ); + ctrl.postedFile.extension = file.name.substring( + file.name.lastIndexOf(".") + ); + ctrl.postedFile.fileStream = reader.result; + } + ctrl.srcUrl = reader.result; + ctrl.isImage = + ctrl.srcUrl.indexOf("data:image/") >= 0 || + ctrl.srcUrl + .toLowerCase() + .match(/([/|.|\w|\s|-])*\.(?:jpg|jpeg|gif|png|svg)/g); + ctrl.src = reader.result; + $rootScope.isBusy = false; + $scope.$apply(); + }; + reader.onerror = function (error) { + $rootScope.isBusy = false; + $rootScope.showErrors([error]); + }; + } else { + return null; + } + }; + + ctrl.onUploadFileProgress = function (progress) { + ctrl.progress = progress; + }; + }, + ], +}); + +modules.component("confirm", { + templateUrl: "/mix-app/views/app-portal/components/confirm/confirm.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + function ($rootScope, $scope) { + var ctrl = this; + ctrl.executeFunctionByName = async function ( + functionName, + args, + context + ) { + var result = await $rootScope.executeFunctionByName( + functionName, + args, + context + ); + if (result) { + $scope.$apply(); + } + }; + }, + ], + bindings: { + message: "=", + }, +}); + +modules.component("filterList", { + templateUrl: + "/mix-app/views/app-portal/components/filter-list/filter-list.html", + controller: [ + "$scope", + "$rootScope", + "ngAppSettings", + "CultureService", + function ($scope, $rootScope, ngAppSettings, cultureService) { + var ctrl = this; + ctrl.dateRange = { + fromDate: null, + toDate: null, + }; + ctrl.searchMethods = ["Equal", "Like"]; + ctrl.init = async function () { + if (!ctrl.arrOrderby) { + ctrl.arrOrderby = [ + "Title", + "Priority", + "CreatedDateTime", + "LastModified", + "Status", + ]; + } + ctrl.request.orderBy = ctrl.request.orderBy || ctrl.arrOrderby[0]; + ctrl.directions = ["Asc", "Desc"]; + ctrl.pageSizes = [5, 10, 15, 20]; + ctrl.statuses = $rootScope.globalSettings.statuses; + }; + ctrl.changeLang = function (culture) { + if (culture) { + ctrl.selectedCulture = culture; + ctrl.request.culture = culture.specificulture; + } else { + ctrl.selectedCulture = null; + ctrl.request.culture = null; + } + ctrl.apply(0); + }; + ctrl.apply = function (pageIndex) { + $rootScope.setRequest(ctrl.request, ctrl.key); + ctrl.callback({ pageIndex: pageIndex }); + }; + ctrl.updateDate = function () { + ctrl.request.pageIndex = 0; + if (Date.parse(ctrl.dateRange.fromDate)) { + ctrl.request.fromDate = new Date( + ctrl.dateRange.fromDate + ).toISOString(); } else { - return null; + $scope.request.fromDate = null; } - }; - - ctrl.getBase64 = function (file) { - if (file !== null) { - $rootScope.isBusy = true; - var reader = new FileReader(); - reader.readAsDataURL(file); - reader.onload = function () { - var index = reader.result.indexOf(",") + 1; - var base64 = reader.result.substring(index); - if (ctrl.postedFile) { - ctrl.postedFile.fileName = file.name.substring( - 0, - file.name.lastIndexOf(".") - ); - ctrl.postedFile.extension = file.name.substring( - file.name.lastIndexOf(".") - ); - ctrl.postedFile.fileStream = reader.result; - } - ctrl.srcUrl = reader.result; - ctrl.isImage = - ctrl.srcUrl.indexOf("data:image/") >= 0 || - ctrl.srcUrl - .toLowerCase() - .match(/([/|.|\w|\s|-])*\.(?:jpg|jpeg|gif|png|svg)/g); - ctrl.src = reader.result; - $rootScope.isBusy = false; - $scope.$apply(); - }; - reader.onerror = function (error) { - $rootScope.isBusy = false; - $rootScope.showErrors([error]); - }; + if (Date.parse(ctrl.dateRange.toDate)) { + ctrl.request.toDate = new Date(ctrl.dateRange.toDate).toISOString(); } else { - return null; + ctrl.request.toDate = null; } - }; - - ctrl.onUploadFileProgress = function (progress) { - ctrl.progress = progress; + $rootScope.setRequest(ctrl.request, ctrl.key); + ctrl.callback({ pageIndex: 0 }); }; }, ], + bindings: { + request: "=", + key: "=?", + arrOrderby: "=?", + createUrl: "=", + createText: "=", + callback: "&", + }, }); modules.component("funding", { @@ -10110,172 +10270,16 @@ modules.component("funding", { }, { title: "paypalme/mixcore", - href: "https://www.paypal.me/mixcore", - logo: "/mix-app/assets/img/svg/heart.svg", - }, - { - title: "buymeacoffee.com/mixcore", - href: "https://www.buymeacoffee.com/mixcore", - logo: "/mix-app/assets/img/svg/heart.svg", - }, - ]; - ctrl.init = function () {}; - }, - ], - bindings: {}, -}); - -modules.component("additionalColumn", { - templateUrl: - "/mix-app/views/app-portal/components/additional-column/view.html", - bindings: { - model: "=", - additionalData: "=", - }, - controller: [ - "$rootScope", - "$scope", - "RestMixDatabaseColumnPortalService", - "RestMixDatabaseDataPortalService", - function ($rootScope, $scope, columnService, dataService) { - var ctrl = this; - ctrl.value = {}; - ctrl.column = { - dataType: "Text", - mixDatabaseName: "sysAdditionalColumn", - mixDatabaseId: 6, - status: "Published", - }; - ctrl.selectedCol = null; - ctrl.mixConfigurations = $rootScope.globalSettings; - ctrl.$onInit = async function () {}; - ctrl.addAttr = async function () { - if (ctrl.column.name) { - var current = $rootScope.findObjectByKey( - ctrl.additionalData.columns, - "name", - ctrl.column.name - ); - if (current) { - $rootScope.showErrors(["Field " + ctrl.column.name + " existed!"]); - } else { - ctrl.column.priority = ctrl.additionalData.columns.length + 1; - $rootScope.isBusy = true; - var saveField = await columnService.create(ctrl.column); - $rootScope.isBusy = false; - if (saveField.success) { - ctrl.additionalData.columns.push(saveField.data); - if (ctrl.additionalData.parentId) { - await dataService.save(ctrl.additionalData); - } - //reset column option - ctrl.column.title = ""; - ctrl.column.name = ""; - ctrl.column.dataType = "Text"; - } else { - $rootScope.showErrors(saveField.errors); - } - $scope.$apply(); - } - } else { - $rootScope.showErrors(["Please add column Name"]); - } - }; - - ctrl.generateName = function (col) { - col.name = $rootScope.generateKeyword(col.title, "_", true, true); - }; - ctrl.showReferences = function (col) { - ctrl.colRef = col; - $("#modal-navs").modal("show"); - }; - ctrl.referenceCallback = async function (selected) { - if (selected && selected.length) { - ctrl.colRef.reference = selected; - ctrl.colRef.referenceId = selected[0].id; - await columnService.save(ctrl.colRef); - } - $("#modal-navs").modal("hide"); - }; - ctrl.updateOrders = function (index) { - if (index > ctrl.dragStartIndex) { - ctrl.additionalData.columns.splice(ctrl.dragStartIndex, 1); - } else { - ctrl.additionalData.columns.splice(ctrl.dragStartIndex + 1, 1); - } - angular.forEach(ctrl.additionalData.columns, function (e, i) { - e.priority = i; - }); - }; - - ctrl.dragStart = function (index) { - ctrl.dragStartIndex = index; - }; - - ctrl.removeAttribute = function (val, index) { - $rootScope.showConfirm( - ctrl, - "removeAttributeConfirmed", - [val, index], - null, - "Remove Field", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); - }; - ctrl.removeAttributeConfirmed = async function (val, index) { - if (val.id) { - $rootScope.isBusy = true; - var result = await columnService.delete([val.id]); - if (result.success) { - ctrl.additionalData.columns.splice(index, 1); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - } else { - ctrl.additionalData.columns.splice(index, 1); - } - }; - }, - ], -}); - -modules.component("githubContributers", { - templateUrl: - "/mix-app/views/app-portal/components/github-contributers/view.html", - controller: [ - "$rootScope", - "$http", - function ($rootScope, $http) { - var ctrl = this; - ctrl.items = []; - ctrl.init = function () { - var req = { - method: "GET", - url: "https://api.github.com/repos/mixcore/mix.core/contributors", - }; - ctrl.getGithubApiResult(req); - }; - - ctrl.getGithubApiResult = async function (req) { - return $http(req).then( - function (resp) { - if (resp.status == "200") { - ctrl.items = resp.data; - } else { - } - }, - function (error) { - return { - success: false, - errors: [error.statusText || error.status], - }; - } - ); - }; + href: "https://www.paypal.me/mixcore", + logo: "/mix-app/assets/img/svg/heart.svg", + }, + { + title: "buymeacoffee.com/mixcore", + href: "https://www.buymeacoffee.com/mixcore", + logo: "/mix-app/assets/img/svg/heart.svg", + }, + ]; + ctrl.init = function () {}; }, ], bindings: {}, @@ -10318,358 +10322,43 @@ modules.component("githubReleases", { bindings: {}, }); -modules.component("googleAnalytic", { - templateUrl: "/mix-app/views/app-portal/components/google-analytic/view.html", - bindings: { - Google_Client_Id: "=?", - Google_Client_Ids: "=?", - Google_Analytic_Ids: "=?", - }, +modules.component("githubContributers", { + templateUrl: + "/mix-app/views/app-portal/components/github-contributers/view.html", controller: [ "$rootScope", - "ApiService", - "CommonService", - function ($rootScope, apiService, commonService) { + "$http", + function ($rootScope, $http) { var ctrl = this; + ctrl.items = []; ctrl.init = function () { - if (gapi) { - gapi.analytics.ready(function () { - if (ctrl.Google_Client_Id) { - /** - * Authorize the user immediately if the user has already granted access. - * If no access has been created, render an authorize button inside the - * element with the ID "embed-api-auth-container". - */ - gapi.analytics.auth.authorize({ - container: "embed-api-auth-container", - //REPLACE WITH YOUR CLIENT ID - clientid: ctrl.Google_Client_Id, - }); - - /** - * Create a ViewSelector for the first view to be rendered inside of an - * element with the id "view-selector-1-container". - */ - var viewSelector1 = new gapi.analytics.ViewSelector({ - container: "view-selector-1-container", - }); - - /** - * Create a ViewSelector for the second view to be rendered inside of an - * element with the id "view-selector-2-container". - */ - var viewSelector2 = new gapi.analytics.ViewSelector({ - container: "view-selector-2-container", - }); - - /** - * Create a new ActiveUsers instance to be rendered inside of an - * element with the id "active-users-container" and poll for changes every - * five seconds. - */ - var activeUsers = new gapi.analytics.ext.ActiveUsers({ - container: "active-users-container", - pollingInterval: 5, - }); - /** - * Add CSS animation to visually show the when users come and go. - */ - activeUsers.once("success", function () { - var element = this.container.firstChild; - var timeout; - - this.on("change", function (data) { - var element = this.container.firstChild; - var animationClass = - data.delta > 0 ? "is-increasing" : "is-decreasing"; - element.className += " " + animationClass; - - clearTimeout(timeout); - timeout = setTimeout(function () { - element.className = element.className.replace( - / is-(increasing|decreasing)/g, - "" - ); - }, 3000); - }); - }); - - /** - * Create a ViewSelector for the second view to be rendered inside of an - * element with the id "view-selector-2-container". - */ - var viewSelector2 = new gapi.analytics.ViewSelector({ - container: "view-selector-2-container", - }); - - // Render both view selectors to the page. - // viewSelector1.execute(); - // viewSelector2.execute(); - - /** - * Create the first DataChart for top countries over the past 30 days. - * It will be rendered inside an element with the id "chart-1-container". - */ - var dataChart1 = new gapi.analytics.googleCharts.DataChart({ - query: { - // ids: ctrl.Google_Client_Ids, - metrics: "ga:sessions", - dimensions: "ga:date", - "start-date": "30daysAgo", - "end-date": "yesterday", - }, - chart: { - container: "chart-1-container", - type: "LINE", - options: { - width: "95%", - legendTextStyle: { color: "#333" }, - titleTextStyle: { color: "#333" }, - backgroundColor: { fill: "transparent" }, - hAxis: { - textStyle: { color: "#333" }, - }, - vAxis: { - textStyle: { color: "#333" }, - }, - series: { - 0: { - color: - $rootScope.globalSettings.portalThemeSettings - .primaryColor, - }, - 1: { color: "#e7711b" }, - 2: { color: "#f1ca3a" }, - 3: { color: "#6f9654" }, - 4: { color: "#1c91c0" }, - 5: { color: "#43459d" }, - }, - }, - }, - }); - - /** - * Create the second DataChart for top countries over the past 30 days. - * It will be rendered inside an element with the id "chart-2-container". - */ - var dataChart2 = new gapi.analytics.googleCharts.DataChart({ - query: { - // ids: ctrl.Google_Analytic_Ids, - metrics: "ga:sessions", - dimensions: "ga:country", - "start-date": "90daysAgo", - "end-date": "yesterday", - "max-results": 6, - sort: "-ga:sessions", - }, - chart: { - container: "chart-2-container", - type: "GEO", - options: { - width: "95%", - pieHole: 4 / 9, - }, - }, - }); - - dataChart1 - .set({ - query: { - ids: ctrl.Google_Analytic_Ids, - }, - }) - .execute(); - dataChart2 - .set({ - query: { - ids: ctrl.Google_Analytic_Ids, - }, - }) - .execute(); - activeUsers - .set({ - ids: ctrl.Google_Analytic_Ids, - }) - .execute(); - - // /** - // * Update the first dataChart when the first view selecter is changed. - // */ - // viewSelector1.on('change', function (ids) { - // dataChart1.set({ query: { ids: ids } }).execute(); - // // Start tracking active users for this view. - // activeUsers.set({ ids: ids }).execute(); - // }); - - // /** - // * Update the first dataChart when the first view selecter is changed. - // */ - // viewSelector2.on('change', function (ids) { - // dataChart2.set({ query: { ids: ids } }).execute(); - // // Start tracking active users for this view. - // activeUsers.set({ ids: ids }).execute(); - // }); - - // /** - // * Update the second dataChart when the second view selecter is changed. - // */ - // viewSelector2.on('change', function (ids) { - // dataChart2.set({ query: { ids: ids } }).execute(); - // }); - } - }); - } - }; - }, - ], -}); - -modules.component("actions", { - templateUrl: "/mix-app/views/app-portal/components/actions/actions.html", - bindings: { - primaryUrl: "=", - primaryTitle: "=", - primaryIcon: "=", - previewUrl: "=", - backUrl: "=", - contentUrl: "=", - onClearCache: "&?", - onSubmit: "&?", - }, - controller: [ - "$rootScope", - "$scope", - "$location", - function ($rootScope, $scope, $location) { - var ctrl = this; - ctrl.visible = $rootScope.visible; - ctrl.back = function () { - if (ctrl.backUrl) { - $location.url(ctrl.backUrl); - } else { - window.history.back(); - } - }; - ctrl.$onInit = function () { - ctrl.isAdmin = $rootScope.isAdmin; - }; - ctrl.submit = function ($event) { - if (ctrl.onSubmit) { - $event.preventDefault(); - ctrl.onSubmit(); - return; - } - }; - ctrl.clearCache = function () { - ctrl.onClearCache(); + var req = { + method: "GET", + url: "https://api.github.com/repos/mixcore/mix.core/contributors", + }; + ctrl.getGithubApiResult(req); }; - }, - ], -}); -(function (angular) { - app.component("headerNav", { - templateUrl: - "/mix-app/views/app-portal/components/header-nav/headerNav.html", - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "localStorageService", - "CommonService", - "ApiService", - "AuthService", - "CultureService", - function ( - $rootScope, - $scope, - ngAppSettings, - localStorageService, - commonService, - apiService, - authService, - cultureService - ) { - var ctrl = this; - ctrl.appSettings = $rootScope.globalSettings; - ctrl.isInRole = $rootScope.isInRole; - this.$onInit = function () { - ctrl.isAdmin = $rootScope.isAdmin; - ctrl.mixConfigurations = $rootScope.mixConfigurations; - cultureService.getList(ngAppSettings.request).then((resp) => { - ctrl.cultures = resp.data.items; - ctrl.selectedCulture = ctrl.cultures.find( - (m) => - m.specificulture == $rootScope.globalSettings.defaultCulture - ); - $scope.$apply(); - }); - authService.fillAuthData().then(() => { - if ( - authService.authentication && - authService.authentication.info.userData - ) { - ctrl.avatar = authService.authentication.info.userData.avatar; + ctrl.getGithubApiResult = async function (req) { + return $http(req).then( + function (resp) { + if (resp.status == "200") { + ctrl.items = resp.data; + } else { } - }); - }; - ctrl.translate = $rootScope.translate; - ctrl.getConfiguration = function (keyword, isWrap, defaultText) { - return $rootScope.getConfiguration(keyword, isWrap, defaultText); - }; - ctrl.changeLang = function (culture) { - $rootScope.globalSettings.defaultCulture = culture.specificulture; - localStorageService.set("globalSettings", $rootScope.globalSettings); - window.top.location = location.href; - }; - ctrl.logOut = function () { - $rootScope.logOut(); - }; - ctrl.addPermission = function () { - $("#dlg-permission").modal("show"); - }; - ctrl.addBookmark = function () { - $("#dlg-bookmark").modal("show"); - }; - ctrl.toggleSidebar = function () { - $(".main-sidebar").toggle(); - $(".sub-sidebar").toggle(); - // $('.navbar-brand').toggle(); - }; - ctrl.clearCache = async function () { - $rootScope.isBusy = true; - await commonService.clearCache(); - $rootScope.showMessage("success", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - }; - ctrl.showHelper = function (url) { - $rootScope.helperUrl = url; - $("#dev-helper-modal").modal("show"); - }; - ctrl.generateSitemap = async function () { - $rootScope.isBusy = true; - var resp = await commonService.genrateSitemap(); - if (resp) { - window.top.location.href = - "/admin/file/details?folder=" + - resp.fileFolder + - "&filename=" + - resp.filename + - resp.extension; - } else { - $rootScope.isBusy = false; - $rootScope.showErrors(["Server error"]); + }, + function (error) { + return { + success: false, + errors: [error.statusText || error.status], + }; } - }; - }, - ], - bindings: { - breadCrumbs: "=", - settings: "=", + ); + }; }, - }); -})(window.angular); + ], + bindings: {}, +}); modules.component("highFrequencyMessages", { templateUrl: @@ -10731,8 +10420,7 @@ app.controller("HighFrequencyMessagesController", [ $scope.connection.invoke("UploadStream", $scope.subject, $scope.room); $scope.intervalHandle = setInterval($scope.updateMouse, updateRate); }; - $scope.receiveMessage = function (data) { - var msg = JSON.parse(data); + $scope.receiveMessage = function (msg) { switch (msg.title) { case "MouseMove": let mouse = $scope.mouses.find( @@ -10848,150 +10536,315 @@ app.controller("HighFrequencyMessagesController", [ }, ]); -modules.component("hubMessages", { - templateUrl: - "/mix-app/views/app-portal/components/hub-messages/hub-messages.html", - controller: "HubMessagesController", - bindings: {}, -}); -app.controller("HubMessagesController", [ - "$scope", - "$rootScope", - "AuthService", - function ($scope, $rootScope, authService) { - BaseHub.call(this, $scope); - authService.fillAuthData(); - $scope.newMsgCount = 0; - $scope.messages = []; - $scope.onConnected = () => { - // $scope.joinRoom("portal"); - }; - $scope.init = function () { - $scope.startConnection( - "portalHub", - authService.authentication.accessToken, - (err) => { - if ( - authService.authentication.refreshToken && - err.message.indexOf("401") >= 0 - ) { - authService.refreshToken().then(async () => { - $scope.startConnection( - "portalHub", - authService.authentication.accessToken - ); - }); - } - } - ); - }; - $scope.readMessages = function () { - $scope.newMsgCount = 0; - $("#modal-hub-messages").modal("show"); - }; - $scope.receiveMessage = function (msg) { - switch (msg.action) { - case "MyConnection": - $scope.hubRequest.from = msg.data; - $scope.$apply(); - break; - case "MemberList": - // filter unique member by username - $scope.members = msg.data.filter( - (value, index, array) => - array.indexOf(array.find((u) => u.username == value.username)) === - index - ); - $scope.$apply(); - break; - case "NewMember": - $scope.newMember(msg.data); - break; - case "MemberOffline": - $scope.removeMember(msg.data); - case "NewMessage": - $scope.newMessage(msg); - break; - } - }; - $scope.newMessage = function (msg) { - msg.style = $scope.getMessageType(msg.type); - if ( - msg.data && - !angular.isObject(msg.data) && - msg.data.indexOf("{") == 0 - ) { - msg.data = JSON.parse(msg.data); - } - $scope.messages.push(msg); - if ( - !msg.from || - msg.from.connectionId != $scope.hubRequest.from.connectionId - ) { - $scope.newMsgCount += 1; - $rootScope.showMessage(msg.title, msg.style); - } - $scope.$apply(); - }; - $scope.removeMember = function (member) { - var index = $scope.members.findIndex( - (x) => x.username === member.username - ); - if (index >= 0) { - $scope.members.splice(index, 1); - } - $scope.$apply(); - }; - - $scope.newMember = function (member) { - var index = $scope.members.findIndex( - (x) => x.username === member.username - ); - if (index < 0) { - $scope.members.splice(0, 0, member); - } - $scope.$apply(); - }; - $scope.getMessageType = function (type) { - switch (type) { - case "Success": - return "success"; - case "Error": - return "danger"; - case "Warning": - return "warning"; - case "Info": - return "info"; - default: - return "default"; - } - }; - }, -]); - -modules.component("jumbotrons", { - templateUrl: - "/mix-app/views/app-portal/components/jumbotrons/jumbotrons.html", +modules.component("googleAnalytic", { + templateUrl: "/mix-app/views/app-portal/components/google-analytic/view.html", + bindings: { + Google_Client_Id: "=?", + Google_Client_Ids: "=?", + Google_Analytic_Ids: "=?", + }, controller: [ "$rootScope", - "$scope", - "$location", - function ($rootScope, $scope, $location) { + "ApiService", + "CommonService", + function ($rootScope, apiService, commonService) { var ctrl = this; - ctrl.translate = function (keyword) { - return $rootScope.translate(keyword); + ctrl.init = function () { + if (gapi) { + gapi.analytics.ready(function () { + if (ctrl.Google_Client_Id) { + /** + * Authorize the user immediately if the user has already granted access. + * If no access has been created, render an authorize button inside the + * element with the ID "embed-api-auth-container". + */ + gapi.analytics.auth.authorize({ + container: "embed-api-auth-container", + //REPLACE WITH YOUR CLIENT ID + clientid: ctrl.Google_Client_Id, + }); + + /** + * Create a ViewSelector for the first view to be rendered inside of an + * element with the id "view-selector-1-container". + */ + var viewSelector1 = new gapi.analytics.ViewSelector({ + container: "view-selector-1-container", + }); + + /** + * Create a ViewSelector for the second view to be rendered inside of an + * element with the id "view-selector-2-container". + */ + var viewSelector2 = new gapi.analytics.ViewSelector({ + container: "view-selector-2-container", + }); + + /** + * Create a new ActiveUsers instance to be rendered inside of an + * element with the id "active-users-container" and poll for changes every + * five seconds. + */ + var activeUsers = new gapi.analytics.ext.ActiveUsers({ + container: "active-users-container", + pollingInterval: 5, + }); + /** + * Add CSS animation to visually show the when users come and go. + */ + activeUsers.once("success", function () { + var element = this.container.firstChild; + var timeout; + + this.on("change", function (data) { + var element = this.container.firstChild; + var animationClass = + data.delta > 0 ? "is-increasing" : "is-decreasing"; + element.className += " " + animationClass; + + clearTimeout(timeout); + timeout = setTimeout(function () { + element.className = element.className.replace( + / is-(increasing|decreasing)/g, + "" + ); + }, 3000); + }); + }); + + /** + * Create a ViewSelector for the second view to be rendered inside of an + * element with the id "view-selector-2-container". + */ + var viewSelector2 = new gapi.analytics.ViewSelector({ + container: "view-selector-2-container", + }); + + // Render both view selectors to the page. + // viewSelector1.execute(); + // viewSelector2.execute(); + + /** + * Create the first DataChart for top countries over the past 30 days. + * It will be rendered inside an element with the id "chart-1-container". + */ + var dataChart1 = new gapi.analytics.googleCharts.DataChart({ + query: { + // ids: ctrl.Google_Client_Ids, + metrics: "ga:sessions", + dimensions: "ga:date", + "start-date": "30daysAgo", + "end-date": "yesterday", + }, + chart: { + container: "chart-1-container", + type: "LINE", + options: { + width: "95%", + legendTextStyle: { color: "#333" }, + titleTextStyle: { color: "#333" }, + backgroundColor: { fill: "transparent" }, + hAxis: { + textStyle: { color: "#333" }, + }, + vAxis: { + textStyle: { color: "#333" }, + }, + series: { + 0: { + color: + $rootScope.globalSettings.portalThemeSettings + .primaryColor, + }, + 1: { color: "#e7711b" }, + 2: { color: "#f1ca3a" }, + 3: { color: "#6f9654" }, + 4: { color: "#1c91c0" }, + 5: { color: "#43459d" }, + }, + }, + }, + }); + + /** + * Create the second DataChart for top countries over the past 30 days. + * It will be rendered inside an element with the id "chart-2-container". + */ + var dataChart2 = new gapi.analytics.googleCharts.DataChart({ + query: { + // ids: ctrl.Google_Analytic_Ids, + metrics: "ga:sessions", + dimensions: "ga:country", + "start-date": "90daysAgo", + "end-date": "yesterday", + "max-results": 6, + sort: "-ga:sessions", + }, + chart: { + container: "chart-2-container", + type: "GEO", + options: { + width: "95%", + pieHole: 4 / 9, + }, + }, + }); + + dataChart1 + .set({ + query: { + ids: ctrl.Google_Analytic_Ids, + }, + }) + .execute(); + dataChart2 + .set({ + query: { + ids: ctrl.Google_Analytic_Ids, + }, + }) + .execute(); + activeUsers + .set({ + ids: ctrl.Google_Analytic_Ids, + }) + .execute(); + + // /** + // * Update the first dataChart when the first view selecter is changed. + // */ + // viewSelector1.on('change', function (ids) { + // dataChart1.set({ query: { ids: ids } }).execute(); + // // Start tracking active users for this view. + // activeUsers.set({ ids: ids }).execute(); + // }); + + // /** + // * Update the first dataChart when the first view selecter is changed. + // */ + // viewSelector2.on('change', function (ids) { + // dataChart2.set({ query: { ids: ids } }).execute(); + // // Start tracking active users for this view. + // activeUsers.set({ ids: ids }).execute(); + // }); + + // /** + // * Update the second dataChart when the second view selecter is changed. + // */ + // viewSelector2.on('change', function (ids) { + // dataChart2.set({ query: { ids: ids } }).execute(); + // }); + } + }); + } }; - // ctrl.back = function () { - // ctrl.backUrl = ctrl.backUrl || '/admin'; - // $location.path(ctrl.backUrl); - // }; }, - ], - bindings: { - tagName: "=", - tagType: "=", - }, -}); + ], +}); + +(function (angular) { + app.component("headerNav", { + templateUrl: + "/mix-app/views/app-portal/components/header-nav/headerNav.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "localStorageService", + "CommonService", + "ApiService", + "AuthService", + "CultureService", + function ( + $rootScope, + $scope, + ngAppSettings, + localStorageService, + commonService, + apiService, + authService, + cultureService + ) { + var ctrl = this; + ctrl.appSettings = $rootScope.globalSettings; + ctrl.isInRole = $rootScope.isInRole; + this.$onInit = function () { + ctrl.isAdmin = $rootScope.isAdmin; + ctrl.mixConfigurations = $rootScope.mixConfigurations; + cultureService.getList(ngAppSettings.request).then((resp) => { + ctrl.cultures = resp.data.items; + ctrl.selectedCulture = ctrl.cultures.find( + (m) => + m.specificulture == $rootScope.globalSettings.defaultCulture + ); + $scope.$apply(); + }); + authService.fillAuthData().then(() => { + if ( + authService.authentication && + authService.authentication.info.userData + ) { + ctrl.avatar = authService.authentication.info.userData.avatar; + } + }); + }; + ctrl.translate = $rootScope.translate; + ctrl.getConfiguration = function (keyword, isWrap, defaultText) { + return $rootScope.getConfiguration(keyword, isWrap, defaultText); + }; + ctrl.changeLang = function (culture) { + $rootScope.globalSettings.defaultCulture = culture.specificulture; + localStorageService.set("globalSettings", $rootScope.globalSettings); + window.top.location = location.href; + }; + ctrl.logOut = function () { + $rootScope.logOut(); + }; + ctrl.addPermission = function () { + $("#dlg-permission").modal("show"); + }; + ctrl.addBookmark = function () { + $("#dlg-bookmark").modal("show"); + }; + ctrl.toggleSidebar = function () { + $(".main-sidebar").toggle(); + $(".sub-sidebar").toggle(); + // $('.navbar-brand').toggle(); + }; + ctrl.clearCache = async function () { + $rootScope.isBusy = true; + await commonService.clearCache(); + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + }; + ctrl.showHelper = function (url) { + $rootScope.helperUrl = url; + $("#dev-helper-modal").modal("show"); + }; + ctrl.generateSitemap = async function () { + $rootScope.isBusy = true; + var resp = await commonService.genrateSitemap(); + if (resp) { + window.top.location.href = + "/admin/file/details?folder=" + + resp.fileFolder + + "&filename=" + + resp.filename + + resp.extension; + } else { + $rootScope.isBusy = false; + $rootScope.showErrors(["Server error"]); + } + }; + }, + ], + bindings: { + breadCrumbs: "=", + settings: "=", + }, + }); +})(window.angular); modules.component("jsonBuilder", { templateUrl: "/mix-app/views/app-portal/components/json-builder/view.html", @@ -11284,6 +11137,127 @@ modules.component("jsonBuilder", { ], }); +modules.component("hubMessages", { + templateUrl: + "/mix-app/views/app-portal/components/hub-messages/hub-messages.html", + controller: "HubMessagesController", + bindings: {}, +}); +app.controller("HubMessagesController", [ + "$scope", + "$rootScope", + "AuthService", + function ($scope, $rootScope, authService) { + BaseHub.call(this, $scope); + authService.fillAuthData(); + $scope.newMsgCount = 0; + $scope.messages = []; + $scope.onConnected = () => { + // $scope.joinRoom("portal"); + }; + $scope.init = function () { + $scope.startConnection( + "portalHub", + authService.authentication.accessToken, + (err) => { + if ( + authService.authentication.refreshToken && + err.message.indexOf("401") >= 0 + ) { + authService.refreshToken().then(async () => { + $scope.startConnection( + "portalHub", + authService.authentication.accessToken + ); + }); + } + } + ); + }; + $scope.readMessages = function () { + $scope.newMsgCount = 0; + $("#modal-hub-messages").modal("show"); + }; + $scope.receiveMessage = function (msg) { + switch (msg.action) { + case "MyConnection": + $scope.hubRequest.from = msg.data; + $scope.$apply(); + break; + case "MemberList": + // filter unique member by username + $scope.members = msg.data.filter( + (value, index, array) => + array.indexOf(array.find((u) => u.username == value.username)) === + index + ); + $scope.$apply(); + break; + case "NewMember": + $scope.newMember(msg.data); + break; + case "MemberOffline": + $scope.removeMember(msg.data); + case "NewMessage": + $scope.newMessage(msg); + break; + } + }; + $scope.newMessage = function (msg) { + msg.style = $scope.getMessageType(msg.type); + if ( + msg.data && + !angular.isObject(msg.data) && + msg.data.indexOf("{") == 0 + ) { + msg.data = JSON.parse(msg.data); + } + $scope.messages.push(msg); + if ( + !msg.from || + msg.from.connectionId != $scope.hubRequest.from.connectionId + ) { + $scope.newMsgCount += 1; + $rootScope.showMessage(msg.title, msg.style); + } + $scope.$apply(); + }; + $scope.removeMember = function (member) { + var index = $scope.members.findIndex( + (x) => x.username === member.username + ); + if (index >= 0) { + $scope.members.splice(index, 1); + } + $scope.$apply(); + }; + + $scope.newMember = function (member) { + var index = $scope.members.findIndex( + (x) => x.username === member.username + ); + if (index < 0) { + $scope.members.splice(0, 0, member); + } + $scope.$apply(); + }; + $scope.getMessageType = function (type) { + switch (type) { + case "Success": + return "success"; + case "Error": + return "danger"; + case "Warning": + return "warning"; + case "Info": + return "info"; + default: + return "default"; + } + }; + }, +]); + // const { data } = require("jquery"); modules.component("listMixColumn", { @@ -11587,6 +11561,30 @@ app.controller("LogStreamController", [ }, ]); +modules.component("jumbotrons", { + templateUrl: + "/mix-app/views/app-portal/components/jumbotrons/jumbotrons.html", + controller: [ + "$rootScope", + "$scope", + "$location", + function ($rootScope, $scope, $location) { + var ctrl = this; + ctrl.translate = function (keyword) { + return $rootScope.translate(keyword); + }; + // ctrl.back = function () { + // ctrl.backUrl = ctrl.backUrl || '/admin'; + // $location.path(ctrl.backUrl); + // }; + }, + ], + bindings: { + tagName: "=", + tagType: "=", + }, +}); + modules.component("mainSideBar", { templateUrl: "/mix-app/views/app-portal/components/main-side-bar/main-side-bar.html", @@ -11622,6 +11620,47 @@ modules.component("mainSideBar", { }, }); +modules.component("mainSideBarDynamic", { + templateUrl: + "/mix-app/views/app-portal/components/main-side-bar-dynamic/main-side-bar-dynamic.html", + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "CommonService", + "TranslatorService", + "AuthService", + function ( + $rootScope, + $scope, + ngAppSettings, + commonService, + translatorService, + authService + ) { + var ctrl = this; + ctrl.init = function () { + // commonService.getPermissions().then(function (response) { + // if (response && response.success) { + // ctrl.isInit = true; + // ctrl.roles = response.data; + // if (ctrl.roles.data) { + // ctrl.role = ctrl.roles.data[0]; + // } + // $rootScope.isBusy = false; + // $scope.$apply(); + // } + // }); + }; + }, + ], + bindings: { + roles: "=", + activedRole: "=", + translate: "&", + }, +}); + modules.component("mainSideBarItem", { templateUrl: "/mix-app/views/app-portal/components/main-side-bar-item/main-side-bar-item.html", @@ -11645,6 +11684,24 @@ modules.component("mainSideBarItem", { }, }); +modules.component("mainSideBarItemDynamic", { + templateUrl: + "/mix-app/views/app-portal/components/main-side-bar-item-dynamic/main-side-bar-item-dynamic.html", + controller: [ + "$rootScope", + function ($rootScope) { + var ctrl = this; + ctrl.translate = $rootScope.translate; + }, + ], + bindings: { + iconSize: "=", + linkStyle: "=", + itemStyle: "=", + item: "=", + }, +}); + modules.component("mediaFileUpload", { templateUrl: "/mix-app/views/app-portal/components/media-file-upload/view.html", @@ -11808,65 +11865,6 @@ modules.component("mediaFileUpload", { ], }); -modules.component("mainSideBarItemDynamic", { - templateUrl: - "/mix-app/views/app-portal/components/main-side-bar-item-dynamic/main-side-bar-item-dynamic.html", - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.translate = $rootScope.translate; - }, - ], - bindings: { - iconSize: "=", - linkStyle: "=", - itemStyle: "=", - item: "=", - }, -}); - -modules.component("mainSideBarDynamic", { - templateUrl: - "/mix-app/views/app-portal/components/main-side-bar-dynamic/main-side-bar-dynamic.html", - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "CommonService", - "TranslatorService", - "AuthService", - function ( - $rootScope, - $scope, - ngAppSettings, - commonService, - translatorService, - authService - ) { - var ctrl = this; - ctrl.init = function () { - // commonService.getPermissions().then(function (response) { - // if (response && response.success) { - // ctrl.isInit = true; - // ctrl.roles = response.data; - // if (ctrl.roles.data) { - // ctrl.role = ctrl.roles.data[0]; - // } - // $rootScope.isBusy = false; - // $scope.$apply(); - // } - // }); - }; - }, - ], - bindings: { - roles: "=", - activedRole: "=", - translate: "&", - }, -}); - modules.component("mediaUpload", { templateUrl: "/mix-app/views/app-portal/components/media-upload/media-upload.html", @@ -11963,7 +11961,224 @@ modules.component("mediumNews", { }; }, ], - bindings: {}, + bindings: {}, +}); + +modules.component("mixDatabaseDataValueEditor", { + templateUrl: + "/mix-app/views/app-portal/components/mix-database-data-value-editor/view.html", + bindings: { + mixDatabaseDataValue: "=?", + parentType: "=?", + parentId: "=?", + isShowTitle: "=?", + }, + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "$location", + "RestRelatedMixDatabasePortalService", + "RestMixDatabaseDataPortalService", + function ( + $rootScope, + $scope, + ngAppSettings, + $location, + navService, + dataService + ) { + var ctrl = this; + ctrl.goToPath = $rootScope.goToPath; + ctrl.icons = ngAppSettings.icons; + ctrl.refData = null; + ctrl.defaultDataModel = null; + ctrl.refDataModel = { + id: null, + data: null, + }; + ctrl.refRequest = angular.copy(ngAppSettings.request); + ctrl.refRequest.pageSize = 100; + ctrl.dataTypes = $rootScope.globalSettings.dataTypes; + ctrl.previousId = null; + ctrl.$doCheck = function () { + if ( + ctrl.mixDatabaseDataValue && + ctrl.previousId !== ctrl.mixDatabaseDataValue.id + ) { + ctrl.previousId = ctrl.mixDatabaseDataValue.id; + ctrl.initData(); + } + }.bind(ctrl); + ctrl.$onInit = function () { + ctrl.initData(); + }; + ctrl.initData = async function () { + setTimeout(() => { + if (!ctrl.mixDatabaseDataValue.id) { + ctrl.initDefaultValue(); + } + switch (ctrl.mixDatabaseDataValue.dataType.toLowerCase()) { + case "datetime": + case "date": + case "time": + if (ctrl.mixDatabaseDataValue.dateTimeValue) { + ctrl.mixDatabaseDataValue.dateObj = new Date( + ctrl.mixDatabaseDataValue.dateTimeValue + ); + $scope.$apply(); + } + break; + case "reference": // reference + if ( + ctrl.mixDatabaseDataValue.column.referenceId && + ctrl.parentId + ) { + ctrl.mixDatabaseDataValue.integerValue = + ctrl.mixDatabaseDataValue.column.referenceId; + // navService.getSingle(["default"]).then((resp) => { + // ctrl.defaultDataModel = resp; + // ctrl.defaultDataModel.mixDatabaseId = + // ctrl.mixDatabaseDataValue.column.referenceId; + // ctrl.refDataModel = angular.copy(ctrl.defaultDataModel); + // }); + // ctrl.loadRefData(); + } + break; + default: + if ( + ctrl.mixDatabaseDataValue.column && + ctrl.mixDatabaseDataValue.column.isEncrypt && + ctrl.mixDatabaseDataValue.encryptValue + ) { + var encryptedData = { + key: ctrl.mixDatabaseDataValue.encryptKey, + data: ctrl.mixDatabaseDataValue.encryptValue, + }; + ctrl.mixDatabaseDataValue.stringValue = + $rootScope.decrypt(encryptedData); + } + if ( + ctrl.mixDatabaseDataValue.column && + !ctrl.mixDatabaseDataValue.stringValue + ) { + ctrl.mixDatabaseDataValue.stringValue = + ctrl.mixDatabaseDataValue.column.defaultValue; + $scope.$apply(); + } + break; + } + }, 200); + }; + ctrl.initDefaultValue = async function () { + switch (ctrl.mixDatabaseDataValue.dataType) { + case "datetime": + case "date": + case "time": + if (ctrl.mixDatabaseDataValue.column.defaultValue) { + ctrl.mixDatabaseDataValue.dateObj = new Date( + ctrl.mixDatabaseDataValue.column.defaultValue + ); + ctrl.mixDatabaseDataValue.stringValue = + ctrl.mixDatabaseDataValue.column.defaultValue; + } + break; + case "double": + if (ctrl.mixDatabaseDataValue.column.defaultValue) { + ctrl.mixDatabaseDataValue.doubleValue = parseFloat( + ctrl.mixDatabaseDataValue.column.defaultValue + ); + ctrl.mixDatabaseDataValue.stringValue = + ctrl.mixDatabaseDataValue.column.defaultValue; + } + break; + case "boolean": + if (ctrl.mixDatabaseDataValue.column.defaultValue) { + ctrl.mixDatabaseDataValue.booleanValue = + ctrl.mixDatabaseDataValue.column.defaultValue == "true"; + ctrl.mixDatabaseDataValue.stringValue = + ctrl.mixDatabaseDataValue.column.defaultValue; + } + break; + + default: + if (ctrl.mixDatabaseDataValue.column.defaultValue) { + ctrl.mixDatabaseDataValue.stringValue = + ctrl.mixDatabaseDataValue.column.defaultValue; + } + break; + } + }; + ctrl.updateStringValue = async function (dataType) { + switch (dataType.toLowerCase()) { + case "datetime": + case "date": + case "time": + if (ctrl.mixDatabaseDataValue.dateObj) { + ctrl.mixDatabaseDataValue.dateTimeValue = + ctrl.mixDatabaseDataValue.dateObj.toISOString(); + ctrl.mixDatabaseDataValue.stringValue = + ctrl.mixDatabaseDataValue.dateTimeValue; + } + break; + case "double": + if (ctrl.mixDatabaseDataValue.doubleValue) { + ctrl.mixDatabaseDataValue.stringValue = + ctrl.mixDatabaseDataValue.doubleValue.toString(); + } + break; + case "boolean": + if (ctrl.mixDatabaseDataValue.booleanValue != null) { + ctrl.mixDatabaseDataValue.stringValue = + ctrl.mixDatabaseDataValue.booleanValue.toString(); + } + break; + + default: + break; + } + }; + + ctrl.updateRefData = function (nav) { + ctrl.goToPath(`/admin/mix-database-data/details?dataContentId=${nav.data.id} + &mixDatabaseId=${nav.data.mixDatabaseId} + &parentId=${ctrl.parentId} + &parentType=${ctrl.parentType}`); + // ctrl.refDataModel = nav; + // var e = $(".pane-form-" + ctrl.mixDatabaseDataValue.column.referenceId)[0]; + // angular.element(e).triggerHandler('click'); + // $location.url('/admin/mix-database-data/details?dataContentId='+ item.id +'&mixDatabaseId=' + item.mixDatabaseId+'&parentType=' + item.parentType+'&parentId=' + item.parentId); + }; + + ctrl.removeRefData = async function (nav) { + $rootScope.showConfirm( + ctrl, + "removeRefDataConfirmed", + [nav], + null, + "Remove", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + }; + ctrl.removeRefDataConfirmed = async function (nav) { + $rootScope.isBusy = true; + var result = await navService.delete([ + nav.parentId, + nav.parentType, + nav.id, + ]); + if (result.success) { + $rootScope.removeObjectByKey(ctrl.refData, "id", nav.id); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErros(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + }, + ], }); app.component("mixMetadata", { @@ -12072,321 +12287,87 @@ app.component("mixMetadata", { undefined ); }; - ctrl.addMetadata = async () => { - if (ctrl.keyword) { - var tmp = ctrl.data.items.find( - (m) => m.metadata.content == ctrl.keyword - ); - if (!tmp) { - let metadata = await ctrl.getOrCreateMetadata(); - if (metadata) { - let dto = { - metadataId: metadata.id, - contentId: ctrl.parentId, - contentType: ctrl.parentType, - description: ctrl.description, - image: ctrl.image, - }; - var resp = await metadataService.createMetadataContentAssociation( - dto - ); - if (resp.success) { - $rootScope.showMessage("Success", "success"); - await ctrl.loadMetadata(); - await ctrl.loadSuggestions(); - ctrl.reset(); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(resp.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - } - } else { - tmp.isActived = true; - ctrl.select(tmp); - } - } - }; - - ctrl.reset = () => { - ctrl.keyword = ""; - $scope.$apply(); - }; - - ctrl.getOrCreateMetadata = async () => { - $rootScope.isBusy = true; - let dto = { - content: ctrl.keyword, - type: ctrl.metadataType, - }; - var resp = await metadataService.getOrCreateMetadata(dto); - if (resp.success) { - $rootScope.isBusy = false; - return resp.data; - } else { - $rootScope.showErrors(resp.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - - ctrl.remove = function (id) { - if ( - confirm( - "Deleted data will not able to recover, are you sure you want to delete this item?" - ) - ) { - ctrl.removeConfirmed(id); - } - }; - - ctrl.removeConfirmed = async function (id) { - $rootScope.isBusy = true; - var result = await metadataService.deleteMetadataContentAssociation(id); - if (result.success) { - await ctrl.loadMetadata(); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - }, - ], -}); - -modules.component("mixDatabaseColumn", { - templateUrl: - "/mix-app/views/app-portal/components/mix-database-column/view.html", - bindings: { - column: "=", - }, - controller: [ - "$rootScope", - "$scope", - "RestMixDatabaseColumnPortalService", - function ($rootScope, $scope, columnService) { - var ctrl = this; - ctrl.value = {}; - ctrl.column = { - dataType: "Text", - mixDatabaseName: "sysAdditionalColumn", - mixDatabaseId: 6, - }; - ctrl.selectedCol = null; - ctrl.mixConfigurations = $rootScope.globalSettings; - ctrl.$onInit = async function () {}; - ctrl.addAttr = async function () { - if (ctrl.column.name) { - var current = $rootScope.findObjectByKey( - ctrl.additionalData.columns, - "name", - ctrl.column.name - ); - if (current) { - $rootScope.showErrors(["Field " + ctrl.column.name + " existed!"]); - } else { - ctrl.column.priority = ctrl.additionalData.columns.length + 1; - $rootScope.isBusy = true; - var saveField = await columnService.create(ctrl.column); - $rootScope.isBusy = false; - if (saveField.success) { - ctrl.additionalData.columns.push(saveField.data); - - //reset column option - ctrl.column.title = ""; - ctrl.column.name = ""; - ctrl.column.dataType = "Text"; - $scope.$apply(); - } - } - } else { - $rootScope.showErrors(["Please add column Name"]); - } - }; - - ctrl.generateName = function (col) { - col.systemName = $rootScope.generateKeyword(col.displayName, "_"); - }; - ctrl.showReferences = function (col) { - ctrl.colRef = col; - $("#modal-navs").modal("show"); - }; - ctrl.referenceCallback = function (selected) { - if (selected && selected.length) { - ctrl.colRef.reference = selected; - ctrl.colRef.referenceId = selected[0].id; - } - $("#modal-navs").modal("hide"); - }; - ctrl.updateOrders = function (index) { - if (index > ctrl.dragStartIndex) { - ctrl.columns.splice(ctrl.dragStartIndex, 1); - } else { - ctrl.columns.splice(ctrl.dragStartIndex + 1, 1); - } - angular.forEach(ctrl.columns, function (e, i) { - e.priority = i; - }); - }; - - ctrl.dragStart = function (index) { - ctrl.dragStartIndex = index; - }; - - ctrl.removeAttribute = function (val, index) { - $rootScope.showConfirm( - ctrl, - "removeAttributeConfirmed", - [val, index], - null, - "Remove Field", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); - }; - ctrl.removeAttributeConfirmed = async function (val, index) { - if (val.id) { - $rootScope.isBusy = true; - var result = await columnService.delete([val.id]); - if (result.success) { - ctrl.additionalData.columns.splice(index, 1); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - } else { - ctrl.additionalData.columns.splice(index, 1); - } - }; - }, - ], -}); - -modules.component("mixDatabaseDataFilter", { - templateUrl: - "/mix-app/views/app-portal/components/mix-database-data-filter/view.html", - bindings: { - query: "=", - mixDatabaseName: "=?", - mixDatabaseId: "=?", - selectedList: "=", - initData: "=?", - columns: "=?", - selected: "=", - callback: "&?", - save: "&?", - }, - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "RestMixDatabaseDataPortalService", - function ($rootScope, $scope, ngAppSettings, dataService) { - var ctrl = this; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.types = ["Page", "Post"]; - ctrl.type = "Page"; - ctrl.navs = []; - ctrl.data = { items: [] }; - ctrl.goToPath = $rootScope.goToPath; - ctrl.$onInit = function () { - if (ctrl.initData) { - ctrl.data = ctrl.initData; - } else { - ctrl.loadData(); + ctrl.addMetadata = async () => { + if (ctrl.keyword) { + var tmp = ctrl.data.items.find( + (m) => m.metadata.content == ctrl.keyword + ); + if (!tmp) { + let metadata = await ctrl.getOrCreateMetadata(); + if (metadata) { + let dto = { + metadataId: metadata.id, + contentId: ctrl.parentId, + contentType: ctrl.parentType, + description: ctrl.description, + image: ctrl.image, + }; + var resp = await metadataService.createMetadataContentAssociation( + dto + ); + if (resp.success) { + $rootScope.showMessage("Success", "success"); + await ctrl.loadMetadata(); + await ctrl.loadSuggestions(); + ctrl.reset(); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(resp.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + } + } else { + tmp.isActived = true; + ctrl.select(tmp); + } } }; - ctrl.loadData = async function (pageIndex) { - ctrl.isBusy = true; - // ctrl.request.query = ctrl.query + ctrl.srcId; - ctrl.navs = []; - if (pageIndex !== undefined) { - ctrl.request.pageIndex = pageIndex; - } - if (ctrl.request.fromDate !== null) { - var df = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = df.toISOString(); - } - if (ctrl.request.toDate !== null) { - var dt = new Date(ctrl.request.toDate); - ctrl.request.toDate = dt.toISOString(); - } - if (ctrl.mixDatabaseId) { - ctrl.request.mixDatabaseId = ctrl.mixDatabaseId; - } - if (ctrl.mixDatabaseName) { - ctrl.request.mixDatabaseName = ctrl.mixDatabaseName; - } - if (ctrl.filterType) { - ctrl.request.filterType = ctrl.filterType; - } + ctrl.reset = () => { + ctrl.keyword = ""; + $scope.$apply(); + }; - var response = await dataService.getList(ctrl.request); - if (response.success) { - ctrl.data = response.data; - ctrl.isBusy = false; - $scope.$apply(); + ctrl.getOrCreateMetadata = async () => { + $rootScope.isBusy = true; + let dto = { + content: ctrl.keyword, + type: ctrl.metadataType, + }; + var resp = await metadataService.getOrCreateMetadata(dto); + if (resp.success) { + $rootScope.isBusy = false; + return resp.data; } else { - $rootScope.showErrors(response.errors); - ctrl.isBusy = false; + $rootScope.showErrors(resp.errors); + $rootScope.isBusy = false; $scope.$apply(); } }; - ctrl.edit = function (nav) { - switch (ctrl.type) { - case "Page": - ctrl.goToPath(`/admin/page/details/${nav.id}`); - break; - case "Post": - ctrl.goToPath(`/admin/post/details/${nav.id}`); - break; - case "Module": - ctrl.goToPath(`/admin/module/details/${nav.id}`); - break; + + ctrl.remove = function (id) { + if ( + confirm( + "Deleted data will not able to recover, are you sure you want to delete this item?" + ) + ) { + ctrl.removeConfirmed(id); } }; - ctrl.onClose = function () { - ctrl.callback(); - }; - ctrl.select = function (nav) { - var current = $rootScope.findObjectByKey(ctrl.data.items, "id", nav.id); - if (!nav.isActive && ctrl.callback) { - ctrl.callback({ nav: nav }); - } - if (ctrl.isMultiple) { - current.isActive = !current.isActive; + + ctrl.removeConfirmed = async function (id) { + $rootScope.isBusy = true; + var result = await metadataService.deleteMetadataContentAssociation(id); + if (result.success) { + await ctrl.loadMetadata(); + $rootScope.isBusy = false; + $scope.$apply(); } else { - if (!nav.isActive) { - angular.forEach(ctrl.data.items, (element) => { - element.isActive = false; - }); - } - current.isActive = !nav.isActive; - } - }; - ctrl.saveSelected = function () { - ctrl.selected = $rootScope.filterArray( - ctrl.data, - ["isActived"], - [true] - ); - setTimeout(() => { - ctrl.save().then(() => { - ctrl.loadPosts(); - }); - }, 500); - }; - ctrl.limString = function (str, max) { - if (str) { - return str.length > max ? str.substring(0, max) + " ..." : str; + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); } }; }, @@ -12607,235 +12588,252 @@ modules.component("mixDatabaseDataValues", { if (resp && resp.success) { $scope.activedPage = resp.data; } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } + if (resp) { + $rootScope.showErrors(resp.errors); + } + } + }); + }; + + ctrl.view = function (item) { + var obj = { + columns: ctrl.database.columns, + item: item, + }; + $rootScope.preview("mix-database-data", obj, null, "modal-lg"); + }; + }, + ], +}); + +modules.component("mixDatabaseColumn", { + templateUrl: + "/mix-app/views/app-portal/components/mix-database-column/view.html", + bindings: { + column: "=", + }, + controller: [ + "$rootScope", + "$scope", + "RestMixDatabaseColumnPortalService", + function ($rootScope, $scope, columnService) { + var ctrl = this; + ctrl.value = {}; + ctrl.column = { + dataType: "Text", + mixDatabaseName: "sysAdditionalColumn", + mixDatabaseId: 6, + }; + ctrl.selectedCol = null; + ctrl.mixConfigurations = $rootScope.globalSettings; + ctrl.$onInit = async function () {}; + ctrl.addAttr = async function () { + if (ctrl.column.name) { + var current = $rootScope.findObjectByKey( + ctrl.additionalData.columns, + "name", + ctrl.column.name + ); + if (current) { + $rootScope.showErrors(["Field " + ctrl.column.name + " existed!"]); + } else { + ctrl.column.priority = ctrl.additionalData.columns.length + 1; + $rootScope.isBusy = true; + var saveField = await columnService.create(ctrl.column); + $rootScope.isBusy = false; + if (saveField.success) { + ctrl.additionalData.columns.push(saveField.data); + + //reset column option + ctrl.column.title = ""; + ctrl.column.name = ""; + ctrl.column.dataType = "Text"; + $scope.$apply(); + } + } + } else { + $rootScope.showErrors(["Please add column Name"]); + } + }; + + ctrl.generateName = function (col) { + col.systemName = $rootScope.generateKeyword(col.displayName, "_"); + }; + ctrl.showReferences = function (col) { + ctrl.colRef = col; + $("#modal-navs").modal("show"); + }; + ctrl.referenceCallback = function (selected) { + if (selected && selected.length) { + ctrl.colRef.reference = selected; + ctrl.colRef.referenceId = selected[0].id; + } + $("#modal-navs").modal("hide"); + }; + ctrl.updateOrders = function (index) { + if (index > ctrl.dragStartIndex) { + ctrl.columns.splice(ctrl.dragStartIndex, 1); + } else { + ctrl.columns.splice(ctrl.dragStartIndex + 1, 1); + } + angular.forEach(ctrl.columns, function (e, i) { + e.priority = i; + }); + }; + + ctrl.dragStart = function (index) { + ctrl.dragStartIndex = index; + }; + + ctrl.removeAttribute = function (val, index) { + $rootScope.showConfirm( + ctrl, + "removeAttributeConfirmed", + [val, index], + null, + "Remove Field", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + }; + ctrl.removeAttributeConfirmed = async function (val, index) { + if (val.id) { + $rootScope.isBusy = true; + var result = await columnService.delete([val.id]); + if (result.success) { + ctrl.additionalData.columns.splice(index, 1); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(result.errors); + $rootScope.isBusy = false; + $scope.$apply(); } - }); - }; - - ctrl.view = function (item) { - var obj = { - columns: ctrl.database.columns, - item: item, - }; - $rootScope.preview("mix-database-data", obj, null, "modal-lg"); + } else { + ctrl.additionalData.columns.splice(index, 1); + } }; }, ], }); -modules.component("mixDatabaseDataValueEditor", { +modules.component("mixDatabaseDataFilter", { templateUrl: - "/mix-app/views/app-portal/components/mix-database-data-value-editor/view.html", + "/mix-app/views/app-portal/components/mix-database-data-filter/view.html", bindings: { - mixDatabaseDataValue: "=?", - parentType: "=?", - parentId: "=?", - isShowTitle: "=?", + query: "=", + mixDatabaseName: "=?", + mixDatabaseId: "=?", + selectedList: "=", + initData: "=?", + columns: "=?", + selected: "=", + callback: "&?", + save: "&?", }, controller: [ "$rootScope", "$scope", "ngAppSettings", - "$location", - "RestRelatedMixDatabasePortalService", "RestMixDatabaseDataPortalService", - function ( - $rootScope, - $scope, - ngAppSettings, - $location, - navService, - dataService - ) { + function ($rootScope, $scope, ngAppSettings, dataService) { var ctrl = this; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.types = ["Page", "Post"]; + ctrl.type = "Page"; + ctrl.navs = []; + ctrl.data = { items: [] }; ctrl.goToPath = $rootScope.goToPath; - ctrl.icons = ngAppSettings.icons; - ctrl.refData = null; - ctrl.defaultDataModel = null; - ctrl.refDataModel = { - id: null, - data: null, - }; - ctrl.refRequest = angular.copy(ngAppSettings.request); - ctrl.refRequest.pageSize = 100; - ctrl.dataTypes = $rootScope.globalSettings.dataTypes; - ctrl.previousId = null; - ctrl.$doCheck = function () { - if ( - ctrl.mixDatabaseDataValue && - ctrl.previousId !== ctrl.mixDatabaseDataValue.id - ) { - ctrl.previousId = ctrl.mixDatabaseDataValue.id; - ctrl.initData(); - } - }.bind(ctrl); ctrl.$onInit = function () { - ctrl.initData(); - }; - ctrl.initData = async function () { - setTimeout(() => { - if (!ctrl.mixDatabaseDataValue.id) { - ctrl.initDefaultValue(); - } - switch (ctrl.mixDatabaseDataValue.dataType.toLowerCase()) { - case "datetime": - case "date": - case "time": - if (ctrl.mixDatabaseDataValue.dateTimeValue) { - ctrl.mixDatabaseDataValue.dateObj = new Date( - ctrl.mixDatabaseDataValue.dateTimeValue - ); - $scope.$apply(); - } - break; - case "reference": // reference - if ( - ctrl.mixDatabaseDataValue.column.referenceId && - ctrl.parentId - ) { - ctrl.mixDatabaseDataValue.integerValue = - ctrl.mixDatabaseDataValue.column.referenceId; - // navService.getSingle(["default"]).then((resp) => { - // ctrl.defaultDataModel = resp; - // ctrl.defaultDataModel.mixDatabaseId = - // ctrl.mixDatabaseDataValue.column.referenceId; - // ctrl.refDataModel = angular.copy(ctrl.defaultDataModel); - // }); - // ctrl.loadRefData(); - } - break; - default: - if ( - ctrl.mixDatabaseDataValue.column && - ctrl.mixDatabaseDataValue.column.isEncrypt && - ctrl.mixDatabaseDataValue.encryptValue - ) { - var encryptedData = { - key: ctrl.mixDatabaseDataValue.encryptKey, - data: ctrl.mixDatabaseDataValue.encryptValue, - }; - ctrl.mixDatabaseDataValue.stringValue = - $rootScope.decrypt(encryptedData); - } - if ( - ctrl.mixDatabaseDataValue.column && - !ctrl.mixDatabaseDataValue.stringValue - ) { - ctrl.mixDatabaseDataValue.stringValue = - ctrl.mixDatabaseDataValue.column.defaultValue; - $scope.$apply(); - } - break; - } - }, 200); + if (ctrl.initData) { + ctrl.data = ctrl.initData; + } else { + ctrl.loadData(); + } }; - ctrl.initDefaultValue = async function () { - switch (ctrl.mixDatabaseDataValue.dataType) { - case "datetime": - case "date": - case "time": - if (ctrl.mixDatabaseDataValue.column.defaultValue) { - ctrl.mixDatabaseDataValue.dateObj = new Date( - ctrl.mixDatabaseDataValue.column.defaultValue - ); - ctrl.mixDatabaseDataValue.stringValue = - ctrl.mixDatabaseDataValue.column.defaultValue; - } - break; - case "double": - if (ctrl.mixDatabaseDataValue.column.defaultValue) { - ctrl.mixDatabaseDataValue.doubleValue = parseFloat( - ctrl.mixDatabaseDataValue.column.defaultValue - ); - ctrl.mixDatabaseDataValue.stringValue = - ctrl.mixDatabaseDataValue.column.defaultValue; - } - break; - case "boolean": - if (ctrl.mixDatabaseDataValue.column.defaultValue) { - ctrl.mixDatabaseDataValue.booleanValue = - ctrl.mixDatabaseDataValue.column.defaultValue == "true"; - ctrl.mixDatabaseDataValue.stringValue = - ctrl.mixDatabaseDataValue.column.defaultValue; - } - break; + ctrl.loadData = async function (pageIndex) { + ctrl.isBusy = true; - default: - if (ctrl.mixDatabaseDataValue.column.defaultValue) { - ctrl.mixDatabaseDataValue.stringValue = - ctrl.mixDatabaseDataValue.column.defaultValue; - } - break; + // ctrl.request.query = ctrl.query + ctrl.srcId; + ctrl.navs = []; + if (pageIndex !== undefined) { + ctrl.request.pageIndex = pageIndex; + } + if (ctrl.request.fromDate !== null) { + var df = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = df.toISOString(); + } + if (ctrl.request.toDate !== null) { + var dt = new Date(ctrl.request.toDate); + ctrl.request.toDate = dt.toISOString(); + } + if (ctrl.mixDatabaseId) { + ctrl.request.mixDatabaseId = ctrl.mixDatabaseId; + } + if (ctrl.mixDatabaseName) { + ctrl.request.mixDatabaseName = ctrl.mixDatabaseName; + } + if (ctrl.filterType) { + ctrl.request.filterType = ctrl.filterType; + } + + var response = await dataService.getList(ctrl.request); + if (response.success) { + ctrl.data = response.data; + ctrl.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + ctrl.isBusy = false; + $scope.$apply(); } }; - ctrl.updateStringValue = async function (dataType) { - switch (dataType.toLowerCase()) { - case "datetime": - case "date": - case "time": - if (ctrl.mixDatabaseDataValue.dateObj) { - ctrl.mixDatabaseDataValue.dateTimeValue = - ctrl.mixDatabaseDataValue.dateObj.toISOString(); - ctrl.mixDatabaseDataValue.stringValue = - ctrl.mixDatabaseDataValue.dateTimeValue; - } - break; - case "double": - if (ctrl.mixDatabaseDataValue.doubleValue) { - ctrl.mixDatabaseDataValue.stringValue = - ctrl.mixDatabaseDataValue.doubleValue.toString(); - } + ctrl.edit = function (nav) { + switch (ctrl.type) { + case "Page": + ctrl.goToPath(`/admin/page/details/${nav.id}`); break; - case "boolean": - if (ctrl.mixDatabaseDataValue.booleanValue != null) { - ctrl.mixDatabaseDataValue.stringValue = - ctrl.mixDatabaseDataValue.booleanValue.toString(); - } + case "Post": + ctrl.goToPath(`/admin/post/details/${nav.id}`); break; - - default: + case "Module": + ctrl.goToPath(`/admin/module/details/${nav.id}`); break; } }; - - ctrl.updateRefData = function (nav) { - ctrl.goToPath(`/admin/mix-database-data/details?dataContentId=${nav.data.id} - &mixDatabaseId=${nav.data.mixDatabaseId} - &parentId=${ctrl.parentId} - &parentType=${ctrl.parentType}`); - // ctrl.refDataModel = nav; - // var e = $(".pane-form-" + ctrl.mixDatabaseDataValue.column.referenceId)[0]; - // angular.element(e).triggerHandler('click'); - // $location.url('/admin/mix-database-data/details?dataContentId='+ item.id +'&mixDatabaseId=' + item.mixDatabaseId+'&parentType=' + item.parentType+'&parentId=' + item.parentId); - }; - - ctrl.removeRefData = async function (nav) { - $rootScope.showConfirm( - ctrl, - "removeRefDataConfirmed", - [nav], - null, - "Remove", - "Deleted data will not able to recover, are you sure you want to delete this item?" + ctrl.onClose = function () { + ctrl.callback(); + }; + ctrl.select = function (nav) { + var current = $rootScope.findObjectByKey(ctrl.data.items, "id", nav.id); + if (!nav.isActive && ctrl.callback) { + ctrl.callback({ nav: nav }); + } + if (ctrl.isMultiple) { + current.isActive = !current.isActive; + } else { + if (!nav.isActive) { + angular.forEach(ctrl.data.items, (element) => { + element.isActive = false; + }); + } + current.isActive = !nav.isActive; + } + }; + ctrl.saveSelected = function () { + ctrl.selected = $rootScope.filterArray( + ctrl.data, + ["isActived"], + [true] ); + setTimeout(() => { + ctrl.save().then(() => { + ctrl.loadPosts(); + }); + }, 500); }; - ctrl.removeRefDataConfirmed = async function (nav) { - $rootScope.isBusy = true; - var result = await navService.delete([ - nav.parentId, - nav.parentType, - nav.id, - ]); - if (result.success) { - $rootScope.removeObjectByKey(ctrl.refData, "id", nav.id); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErros(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); + ctrl.limString = function (str, max) { + if (str) { + return str.length > max ? str.substring(0, max) + " ..." : str; } }; }, @@ -12876,274 +12874,60 @@ modules.component("mixDatabaseNavData", { ctrl.loadData(); }); ctrl.navRequest.parentType = ctrl.parentType; - ctrl.navRequest.parentId = ctrl.parentId; - }; - ctrl.selectPane = function (pane) {}; - ctrl.loadData = function () { - navService.getList(ctrl.navRequest).then((resp) => { - if (resp) { - ctrl.data = resp.data; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $scope.$apply(); - } - }); - }; - ctrl.updateData = function (nav) { - ctrl.selected = nav; - var e = $(".pane-form-" + ctrl.nav.data.id)[0]; - angular.element(e).triggerHandler("click"); - // $location.url('/admin/mix-database-data/details?dataContentId='+ item.id +'&mixDatabaseId=' + item.mixDatabaseId+'&parentType=' + item.parentType+'&parentId=' + item.parentId); - }; - ctrl.saveData = function (data) { - $rootScope.isBusy = true; - ctrl.selected.data = data; - dataService.save(data).then((resp) => { - if (resp.success) { - ctrl.selected.dataContentId = resp.data.id; - ctrl.selected.mixDatabaseId = resp.data.mixDatabaseId; - ctrl.selected.mixDatabaseName = resp.data.mixDatabaseName; - ctrl.selected.attributeData = resp.data; - navService.save(ctrl.selected).then((resp) => { - if (resp.success) { - var tmp = $rootScope.findObjectByKey( - ctrl.data, - ["parentId", "parentType", "id"], - [resp.data.parentId, resp.data.parentType, resp.data.id] - ); - if (!tmp) { - ctrl.data.items.push(resp.data); - var e = $(".pane-data-" + ctrl.nav.data.id)[0]; - angular.element(e).triggerHandler("click"); - } - ctrl.selected = angular.copy(ctrl.defautData); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showMessage(resp.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }); - } else { - $rootScope.showErrors(resp.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }); - }; - ctrl.removeData = async function (nav) { - $rootScope.showConfirm( - ctrl, - "removeDataConfirmed", - [nav], - null, - "Remove", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); - }; - ctrl.removeDataConfirmed = async function (nav) { - $rootScope.isBusy = true; - var result = await navService.delete([nav.id]); - if (result.success) { - $rootScope.removeObjectByKey(ctrl.data, "id", nav.id); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(result.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - ctrl.dragStart = function (index) { - ctrl.dragStartIndex = index; - ctrl.minPriority = ctrl.data[0].priority; - }; - ctrl.updateOrders = function (index) { - if (index > ctrl.dragStartIndex) { - ctrl.data.splice(ctrl.dragStartIndex, 1); - } else { - ctrl.data.splice(ctrl.dragStartIndex + 1, 1); - } - var arrNavs = []; - angular.forEach(ctrl.data, function (e, i) { - e.priority = ctrl.minPriority + i; - var keys = { - parentId: e.parentId, - parentType: e.parentType, - id: e.id, - }; - var properties = { - priority: e.priority, - }; - arrNavs.push({ - keys: keys, - properties: properties, - }); - }); - navService.saveProperties("portal", arrNavs).then((resp) => { - $rootScope.isBusy = false; - $scope.$apply(); - }); - }; - }, - ], -}); - -modules.component("mixDatabaseNavValues", { - templateUrl: - "/mix-app/views/app-portal/components/mix-database-nav-values/view.html", - bindings: { - mixDatabaseId: "=", - mixDatabaseName: "=", - guidParentId: "=", - parentType: "=", - columns: "=?", - header: "=", - data: "=?", - maxCol: "=?", - createUrl: "=?", - updateUrl: "=?", - onUpdate: "&?", - onDelete: "&?", - }, - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "RestRelatedAttributeDataPortalService", - "RestMixDatabaseColumnPortalService", - function ($rootScope, $scope, ngAppSettings, navService, columnService) { - var ctrl = this; - ctrl.selectedProp = null; - ctrl.request = angular.copy(ngAppSettings.restRequest); - ctrl.request.orderBy = "Priority"; - ctrl.request.query = "{}"; - - ctrl.request.direction = 0; - ctrl.mixConfigurations = $rootScope.globalSettings; - ctrl.$onInit = async function () { - ctrl.maxCol = ctrl.maxCol || 3; - if (!ctrl.createUrl) { - ctrl.createUrl = "/admin/mix-database-data/create"; - } - if (!ctrl.updateUrl) { - ctrl.updateUrl = "/admin/mix-database-data/details"; - } - if (!ctrl.columns) { - var getFields = await columnService.initData( - ctrl.mixDatabaseName || ctrl.mixDatabaseId - ); - if (getFields.success) { - ctrl.columns = getFields.data; - $scope.$apply(); - } - } - if (!ctrl.data) { - ctrl.loadData(); - } - }; - - ctrl.update = function (data) { - ctrl.onUpdate({ data: data }); - }; - - ctrl.delete = function (data) { - ctrl.onDelete({ data: data }); - }; - - ctrl.filterData = function (item, attributeName) { - return $rootScope.findObjectByKey( - item.data, - "attributeName", - attributeName - ); - }; - - ctrl.dragStart = function (index) { - ctrl.dragStartIndex = index; - ctrl.minPriority = ctrl.data.items[0].priority; - }; - ctrl.updateOrders = function (index) { - if (index > ctrl.dragStartIndex) { - ctrl.data.items.splice(ctrl.dragStartIndex, 1); - } else { - ctrl.data.items.splice(ctrl.dragStartIndex + 1, 1); - } - angular.forEach(ctrl.data.items, function (e, i) { - e.priority = ctrl.minPriority + i; - navService.saveFields(e.id, { priority: e.priority }).then((resp) => { - $rootScope.isBusy = false; - $scope.$apply(); - }); - }); + ctrl.navRequest.parentId = ctrl.parentId; }; - + ctrl.selectPane = function (pane) {}; ctrl.loadData = function () { - ctrl.request.mixDatabaseId = ctrl.mixDatabaseId || 0; - ctrl.request.mixDatabaseName = ctrl.mixDatabaseName || null; - ctrl.request.guidParentId = ctrl.guidParentId; - ctrl.request.intParentId = ctrl.intParentId; - ctrl.request.parentType = ctrl.parentType; - navService.getList(ctrl.request).then((resp) => { + navService.getList(ctrl.navRequest).then((resp) => { if (resp) { ctrl.data = resp.data; - $rootScope.isBusy = false; $scope.$apply(); } else { if (resp) { - $rootScope.showErrors("Failed"); + $rootScope.showErrors(resp.errors); } - ctrl.refData = []; - $rootScope.isBusy = false; $scope.$apply(); } }); }; ctrl.updateData = function (nav) { - $rootScope.goToPath( - `${ctrl.updateUrl}?dataContentId=${nav.childDataContent.id}&mixDatabaseId=${nav.mixDatabaseId}&guidParentId=${ctrl.guidParentId}&parentType=${ctrl.parentType}` - ); - // ctrl.refDataModel = nav; - // var e = $(".pane-form-" + ctrl.mixDatabaseDataValue.column.referenceId)[0]; - // angular.element(e).triggerHandler('click'); + ctrl.selected = nav; + var e = $(".pane-form-" + ctrl.nav.data.id)[0]; + angular.element(e).triggerHandler("click"); // $location.url('/admin/mix-database-data/details?dataContentId='+ item.id +'&mixDatabaseId=' + item.mixDatabaseId+'&parentType=' + item.parentType+'&parentId=' + item.parentId); }; ctrl.saveData = function (data) { $rootScope.isBusy = true; - ctrl.refDataModel.data = data; - dataService.save("portal", data).then((resp) => { + ctrl.selected.data = data; + dataService.save(data).then((resp) => { if (resp.success) { - ctrl.refDataModel.id = resp.data.id; - ctrl.refDataModel.data = resp.data; - navService.save("portal", ctrl.refDataModel).then((resp) => { + ctrl.selected.dataContentId = resp.data.id; + ctrl.selected.mixDatabaseId = resp.data.mixDatabaseId; + ctrl.selected.mixDatabaseName = resp.data.mixDatabaseName; + ctrl.selected.attributeData = resp.data; + navService.save(ctrl.selected).then((resp) => { if (resp.success) { var tmp = $rootScope.findObjectByKey( - ctrl.refData, + ctrl.data, ["parentId", "parentType", "id"], [resp.data.parentId, resp.data.parentType, resp.data.id] ); if (!tmp) { - ctrl.refData.push(resp.data); + ctrl.data.items.push(resp.data); + var e = $(".pane-data-" + ctrl.nav.data.id)[0]; + angular.element(e).triggerHandler("click"); } - ctrl.refDataModel = angular.copy(ctrl.defaultDataModel); - var e = $( - ".pane-data-" + ctrl.mixDatabaseDataValue.column.referenceId - )[0]; - angular.element(e).triggerHandler("click"); + ctrl.selected = angular.copy(ctrl.defautData); $rootScope.isBusy = false; $scope.$apply(); } else { - $rootScope.showMessage("failed"); + $rootScope.showMessage(resp.errors); $rootScope.isBusy = false; $scope.$apply(); } }); } else { - $rootScope.showMessage("failed"); + $rootScope.showErrors(resp.errors); $rootScope.isBusy = false; $scope.$apply(); } @@ -13163,21 +12947,45 @@ modules.component("mixDatabaseNavValues", { $rootScope.isBusy = true; var result = await navService.delete([nav.id]); if (result.success) { - $rootScope.removeObjectByKey(ctrl.data.items, "id", nav.id); + $rootScope.removeObjectByKey(ctrl.data, "id", nav.id); $rootScope.isBusy = false; $scope.$apply(); } else { - $rootScope.showMessage("failed"); + $rootScope.showErrors(result.errors); $rootScope.isBusy = false; $scope.$apply(); } }; - ctrl.view = function (item) { - var obj = { - columns: ctrl.columns, - item: item, - }; - $rootScope.preview("mix-database-data", obj, null, "modal-lg"); + ctrl.dragStart = function (index) { + ctrl.dragStartIndex = index; + ctrl.minPriority = ctrl.data[0].priority; + }; + ctrl.updateOrders = function (index) { + if (index > ctrl.dragStartIndex) { + ctrl.data.splice(ctrl.dragStartIndex, 1); + } else { + ctrl.data.splice(ctrl.dragStartIndex + 1, 1); + } + var arrNavs = []; + angular.forEach(ctrl.data, function (e, i) { + e.priority = ctrl.minPriority + i; + var keys = { + parentId: e.parentId, + parentType: e.parentType, + id: e.id, + }; + var properties = { + priority: e.priority, + }; + arrNavs.push({ + keys: keys, + properties: properties, + }); + }); + navService.saveProperties("portal", arrNavs).then((resp) => { + $rootScope.isBusy = false; + $scope.$apply(); + }); }; }, ], @@ -13431,65 +13239,255 @@ modules.component("mixDatabaseForm", { $scope.$apply(); } } - } + } + }; + ctrl.saveAssociation = async function (data) { + ctrl.association.childId = data.id; + return await associationService.save(ctrl.association); + }; + ctrl.validate = function () { + var isValid = true; + ctrl.errors = []; + angular.forEach(ctrl.columns, function (column) { + if (column.regex) { + var regex = RegExp(column.regex, "g"); + isValid = regex.test(ctrl.mixDataContent.data[column.name]); + if (!isValid) { + ctrl.errors.push(`${column.name} is not match Regex`); + } + } + if (!isValid) { + $rootScope.showErrors(ctrl.errors); + } + if (isValid && column.isEncrypt) { + ctrl.mixDataContent.data[column.name] = $rootScope.encrypt( + ctrl.mixDataContent.data[column.name] + ); + } + }); + return isValid; + }; + ctrl.showContentFilter = function ($event) { + $rootScope.showContentFilter(ctrl.loadSelectedLink); + }; + ctrl.loadSelectedLink = function (data, type) { + if (data) { + ctrl.mixDataContent.data.target_id = data.id; + ctrl.mixDataContent.data.title = data.title; + ctrl.mixDataContent.data.type = type; + ctrl.mixDataContent.data.uri = data.detailUrl; + } + }; + ctrl.filterData = function (attributeName) { + if (ctrl.mixDataContent) { + var attr = $rootScope.findObjectByKey( + ctrl.mixDataContent.data, + "mixDatabaseColumnName", + attributeName + ); + if (!attr) { + attr = angular.copy( + $rootScope.findObjectByKey( + ctrl.defaultData.data, + "mixDatabaseColumnName", + attributeName + ) + ); + mixDatabaseColumn; + ctrl.mixDataContent.data.push(attr); + } + return attr; + } + }; + }, + ], +}); + +modules.component("mixDatabaseNavValues", { + templateUrl: + "/mix-app/views/app-portal/components/mix-database-nav-values/view.html", + bindings: { + mixDatabaseId: "=", + mixDatabaseName: "=", + guidParentId: "=", + parentType: "=", + columns: "=?", + header: "=", + data: "=?", + maxCol: "=?", + createUrl: "=?", + updateUrl: "=?", + onUpdate: "&?", + onDelete: "&?", + }, + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "RestRelatedAttributeDataPortalService", + "RestMixDatabaseColumnPortalService", + function ($rootScope, $scope, ngAppSettings, navService, columnService) { + var ctrl = this; + ctrl.selectedProp = null; + ctrl.request = angular.copy(ngAppSettings.restRequest); + ctrl.request.orderBy = "Priority"; + ctrl.request.query = "{}"; + + ctrl.request.direction = 0; + ctrl.mixConfigurations = $rootScope.globalSettings; + ctrl.$onInit = async function () { + ctrl.maxCol = ctrl.maxCol || 3; + if (!ctrl.createUrl) { + ctrl.createUrl = "/admin/mix-database-data/create"; + } + if (!ctrl.updateUrl) { + ctrl.updateUrl = "/admin/mix-database-data/details"; + } + if (!ctrl.columns) { + var getFields = await columnService.initData( + ctrl.mixDatabaseName || ctrl.mixDatabaseId + ); + if (getFields.success) { + ctrl.columns = getFields.data; + $scope.$apply(); + } + } + if (!ctrl.data) { + ctrl.loadData(); + } + }; + + ctrl.update = function (data) { + ctrl.onUpdate({ data: data }); + }; + + ctrl.delete = function (data) { + ctrl.onDelete({ data: data }); + }; + + ctrl.filterData = function (item, attributeName) { + return $rootScope.findObjectByKey( + item.data, + "attributeName", + attributeName + ); + }; + + ctrl.dragStart = function (index) { + ctrl.dragStartIndex = index; + ctrl.minPriority = ctrl.data.items[0].priority; + }; + ctrl.updateOrders = function (index) { + if (index > ctrl.dragStartIndex) { + ctrl.data.items.splice(ctrl.dragStartIndex, 1); + } else { + ctrl.data.items.splice(ctrl.dragStartIndex + 1, 1); + } + angular.forEach(ctrl.data.items, function (e, i) { + e.priority = ctrl.minPriority + i; + navService.saveFields(e.id, { priority: e.priority }).then((resp) => { + $rootScope.isBusy = false; + $scope.$apply(); + }); + }); + }; + + ctrl.loadData = function () { + ctrl.request.mixDatabaseId = ctrl.mixDatabaseId || 0; + ctrl.request.mixDatabaseName = ctrl.mixDatabaseName || null; + ctrl.request.guidParentId = ctrl.guidParentId; + ctrl.request.intParentId = ctrl.intParentId; + ctrl.request.parentType = ctrl.parentType; + navService.getList(ctrl.request).then((resp) => { + if (resp) { + ctrl.data = resp.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors("Failed"); + } + ctrl.refData = []; + $rootScope.isBusy = false; + $scope.$apply(); + } + }); }; - ctrl.saveAssociation = async function (data) { - ctrl.association.childId = data.id; - return await associationService.save(ctrl.association); + ctrl.updateData = function (nav) { + $rootScope.goToPath( + `${ctrl.updateUrl}?dataContentId=${nav.childDataContent.id}&mixDatabaseId=${nav.mixDatabaseId}&guidParentId=${ctrl.guidParentId}&parentType=${ctrl.parentType}` + ); + // ctrl.refDataModel = nav; + // var e = $(".pane-form-" + ctrl.mixDatabaseDataValue.column.referenceId)[0]; + // angular.element(e).triggerHandler('click'); + // $location.url('/admin/mix-database-data/details?dataContentId='+ item.id +'&mixDatabaseId=' + item.mixDatabaseId+'&parentType=' + item.parentType+'&parentId=' + item.parentId); }; - ctrl.validate = function () { - var isValid = true; - ctrl.errors = []; - angular.forEach(ctrl.columns, function (column) { - if (column.regex) { - var regex = RegExp(column.regex, "g"); - isValid = regex.test(ctrl.mixDataContent.data[column.name]); - if (!isValid) { - ctrl.errors.push(`${column.name} is not match Regex`); - } - } - if (!isValid) { - $rootScope.showErrors(ctrl.errors); - } - if (isValid && column.isEncrypt) { - ctrl.mixDataContent.data[column.name] = $rootScope.encrypt( - ctrl.mixDataContent.data[column.name] - ); + ctrl.saveData = function (data) { + $rootScope.isBusy = true; + ctrl.refDataModel.data = data; + dataService.save("portal", data).then((resp) => { + if (resp.success) { + ctrl.refDataModel.id = resp.data.id; + ctrl.refDataModel.data = resp.data; + navService.save("portal", ctrl.refDataModel).then((resp) => { + if (resp.success) { + var tmp = $rootScope.findObjectByKey( + ctrl.refData, + ["parentId", "parentType", "id"], + [resp.data.parentId, resp.data.parentType, resp.data.id] + ); + if (!tmp) { + ctrl.refData.push(resp.data); + } + ctrl.refDataModel = angular.copy(ctrl.defaultDataModel); + var e = $( + ".pane-data-" + ctrl.mixDatabaseDataValue.column.referenceId + )[0]; + angular.element(e).triggerHandler("click"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showMessage("failed"); + $rootScope.isBusy = false; + $scope.$apply(); + } + }); + } else { + $rootScope.showMessage("failed"); + $rootScope.isBusy = false; + $scope.$apply(); } }); - return isValid; }; - ctrl.showContentFilter = function ($event) { - $rootScope.showContentFilter(ctrl.loadSelectedLink); + ctrl.removeData = async function (nav) { + $rootScope.showConfirm( + ctrl, + "removeDataConfirmed", + [nav], + null, + "Remove", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); }; - ctrl.loadSelectedLink = function (data, type) { - if (data) { - ctrl.mixDataContent.data.target_id = data.id; - ctrl.mixDataContent.data.title = data.title; - ctrl.mixDataContent.data.type = type; - ctrl.mixDataContent.data.uri = data.detailUrl; + ctrl.removeDataConfirmed = async function (nav) { + $rootScope.isBusy = true; + var result = await navService.delete([nav.id]); + if (result.success) { + $rootScope.removeObjectByKey(ctrl.data.items, "id", nav.id); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showMessage("failed"); + $rootScope.isBusy = false; + $scope.$apply(); } }; - ctrl.filterData = function (attributeName) { - if (ctrl.mixDataContent) { - var attr = $rootScope.findObjectByKey( - ctrl.mixDataContent.data, - "mixDatabaseColumnName", - attributeName - ); - if (!attr) { - attr = angular.copy( - $rootScope.findObjectByKey( - ctrl.defaultData.data, - "mixDatabaseColumnName", - attributeName - ) - ); - mixDatabaseColumn; - ctrl.mixDataContent.data.push(attr); - } - return attr; - } + ctrl.view = function (item) { + var obj = { + columns: ctrl.columns, + item: item, + }; + $rootScope.preview("mix-database-data", obj, null, "modal-lg"); }; }, ], @@ -13771,76 +13769,193 @@ modules.component("mixFileUpload", { "FileServices", function ($rootScope, $scope, ngAppSettings, fileService) { var ctrl = this; - ctrl.mediaFile = {}; - ctrl.isAdmin = $rootScope.isAdmin; - ctrl.mediaNavs = []; - ctrl.$onInit = function () { - ctrl.id = Math.floor(Math.random() * 100); + ctrl.mediaFile = {}; + ctrl.isAdmin = $rootScope.isAdmin; + ctrl.mediaNavs = []; + ctrl.$onInit = function () { + ctrl.id = Math.floor(Math.random() * 100); + }; + ctrl.selectFile = function (files) { + if (files !== undefined && files !== null && files.length > 0) { + const file = files[0]; + ctrl.file = file; + ctrl.mediaFile.folder = ctrl.folder ? ctrl.folder : "Media"; + ctrl.mediaFile.title = ctrl.title ? ctrl.title : ""; + ctrl.mediaFile.description = ctrl.description ? ctrl.description : ""; + ctrl.mediaFile.file = file; + if (ctrl.auto == "true") { + ctrl.uploadFile(file); + } else { + ctrl.getBase64(file); + } + } + }; + + ctrl.getBase64 = function (file) { + if (file !== null) { + $rootScope.isBusy = true; + var reader = new FileReader(); + reader.readAsDataURL(file); + reader.onload = function () { + if (ctrl.mediaFile) { + ctrl.mediaFile.fileName = file.name.substring( + 0, + file.name.lastIndexOf(".") + ); + ctrl.mediaFile.extension = file.name.substring( + file.name.lastIndexOf(".") + ); + ctrl.mediaFile.fileStream = reader.result; + } + $rootScope.isBusy = false; + $scope.$apply(); + }; + reader.onerror = function (error) { + $rootScope.isBusy = false; + $rootScope.showErrors([error]); + }; + } else { + return null; + } + }; + + ctrl.uploadFile = async function () { + if (ctrl.file) { + $rootScope.isBusy = true; + var response = await fileService.uploadFile(ctrl.file, ctrl.folder); + if (response) { + if (ctrl.onSuccess) { + ctrl.onSuccess(); + } + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(['Cannot upload file']); + $rootScope.isBusy = false; + $scope.$apply(); + } + } else { + $rootScope.showErrors(["Please choose file"]); + } + }; + }, + ], +}); + +modules.component("mixSelectIcons", { + templateUrl: + "/mix-app/views/app-portal/components/mix-select-icons/mix-select-icons.html", + controller: [ + "$rootScope", + "$scope", + "$location", + "$element", + function ($rootScope, $scope, $location, $element) { + var ctrl = this; + ctrl.limitTo = 20; + ctrl.container = $element[0].querySelector(".list-icon"); + ctrl.translate = function (keyword) { + return $rootScope.translate(keyword); + }; + ctrl.showMore = () => { + if ( + ctrl.container.scrollTop >= ctrl.container.scrollHeight - 200 && + ctrl.limitTo < ctrl.options.length + ) { + ctrl.limitTo *= 2; + } + }; + ctrl.select = function (ico) { + ctrl.data = ico.class; + }; + }, + ], + bindings: { + data: "=", + prefix: "=", + options: "=", + }, +}); + +modules.component("mixTemplateEditor", { + templateUrl: + "/mix-app/views/app-portal/components/mix-template-editor/view.html", + bindings: { + template: "=", + folderType: "=", + isReadonly: "=?", + lineCount: "=?", + hideJs: "=?", + hideCss: "=?", + }, + controller: [ + "$scope", + "$rootScope", + "$routeParams", + "ngAppSettings", + "AppSettingsService", + "TemplateService", + function ( + $scope, + $rootScope, + $routeParams, + ngAppSettings, + appSettingsService, + service + ) { + BaseCtrl.call( + this, + $scope, + $rootScope, + $routeParams, + ngAppSettings, + service + ); + var ctrl = this; + ctrl.isNull = false; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.selectPane = function (pane) { + ctrl.activedPane = pane; }; - ctrl.selectFile = function (files) { - if (files !== undefined && files !== null && files.length > 0) { - const file = files[0]; - ctrl.file = file; - ctrl.mediaFile.folder = ctrl.folder ? ctrl.folder : "Media"; - ctrl.mediaFile.title = ctrl.title ? ctrl.title : ""; - ctrl.mediaFile.description = ctrl.description ? ctrl.description : ""; - ctrl.mediaFile.file = file; - if (ctrl.auto == "true") { - ctrl.uploadFile(file); - } else { - ctrl.getBase64(file); - } - } + ctrl.selectTemplate = function (template) { + ctrl.template = template; + $scope.$broadcast("updateContentCodeEditors", []); }; - - ctrl.getBase64 = function (file) { - if (file !== null) { - $rootScope.isBusy = true; - var reader = new FileReader(); - reader.readAsDataURL(file); - reader.onload = function () { - if (ctrl.mediaFile) { - ctrl.mediaFile.fileName = file.name.substring( - 0, - file.name.lastIndexOf(".") - ); - ctrl.mediaFile.extension = file.name.substring( - file.name.lastIndexOf(".") - ); - ctrl.mediaFile.fileStream = reader.result; - } - $rootScope.isBusy = false; - $scope.$apply(); - }; - reader.onerror = function (error) { - $rootScope.isBusy = false; - $rootScope.showErrors([error]); - }; - } else { - return null; - } + ctrl.new = function () { + ctrl.template.id = 0; }; + ctrl.init = async function () { + if (ctrl.folderType) { + var themeId = $rootScope.mixConfigurations.data.ThemeId; + ctrl.request.key = ctrl.folderType; + var resp = await service.getList(ctrl.request, [themeId]); - ctrl.uploadFile = async function () { - if (ctrl.file) { - $rootScope.isBusy = true; - var response = await fileService.uploadFile(ctrl.file, ctrl.folder); - if (response) { - if (ctrl.onSuccess) { - ctrl.onSuccess(); + if (resp && resp.success) { + ctrl.templates = resp.data.items; + if (!ctrl.template) { + ctrl.template = ctrl.templates[0]; } - $rootScope.showMessage("success", "success"); $rootScope.isBusy = false; $scope.$apply(); } else { - $rootScope.showErrors(['Cannot upload file']); - $rootScope.isBusy = false; - $scope.$apply(); + if (resp) { + $rootScope.showErrors(resp.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } } - } else { - $rootScope.showErrors(["Please choose file"]); } }; + ctrl.updateTemplateContent = function (content) { + ctrl.template.content = content; + }; + ctrl.updateStyleContent = function (content) { + ctrl.template.scripts = content; + }; + ctrl.updateScriptContent = function (content) { + ctrl.template.styles = content; + }; }, ], }); @@ -13899,185 +14014,296 @@ app.controller("MixNavigationController", [ if (resp) { $rootScope.showErrors(resp.errors); } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.selectFile = function (file, errFiles) { - if (file !== undefined && file !== null) { - $scope.mediaFile.folder = "Media"; - $scope.mediaFile.file = file; - $scope.getBase64(file); - } - }; - $scope.getBase64 = function (file) { - if (file !== null && $scope.postedFile) { + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.selectFile = function (file, errFiles) { + if (file !== undefined && file !== null) { + $scope.mediaFile.folder = "Media"; + $scope.mediaFile.file = file; + $scope.getBase64(file); + } + }; + $scope.getBase64 = function (file) { + if (file !== null && $scope.postedFile) { + $rootScope.isBusy = true; + var reader = new FileReader(); + reader.readAsDataURL(file); + reader.onload = function () { + var index = reader.result.indexOf(",") + 1; + var base64 = reader.result.substring(index); + $scope.activedMedia.mediaFile.fileName = $rootScope.generateKeyword( + file.name.substring(0, file.name.lastIndexOf(".")), + "-" + ); + $scope.activedMedia.mediaFile.extension = file.name.substring( + file.name.lastIndexOf(".") + ); + $scope.activedMedia.mediaFile.fileStream = reader.result; + $rootScope.isBusy = false; + $scope.$apply(); + }; + reader.onerror = function (error) { + $rootScope.showErrors([error]); + $rootScope.isBusy = false; + }; + } else { + return null; + } + }; + $scope.togglePreview = function (item) { + item.isPreview = item.isPreview === undefined ? true : !item.isPreview; + }; + $scope.clone = async function (id) { + $rootScope.isBusy = true; + var resp = await service.cloneMedia(id); + if (resp && resp.success) { + $scope.activedMedia = resp.data; + $rootScope.showMessage("Update successfully!", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + //$location.path('/admin/media/details/' + resp.data.id); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + $scope.saveSuccessCallback = function () { + $scope.getList(); + }; + $scope.removeCallback = function () { + $scope.getList(); + }; + }, +]); + +modules.component("modalContentFilter", { + templateUrl: + "/mix-app/views/app-portal/components/modal-content-filter/modal-content-filter.html", + bindings: { + query: "=", + initData: "=?", + selected: "=", + callback: "&?", + save: "&?", + }, + controller: [ + "$rootScope", + "$scope", + "ngAppSettings", + "PostRestService", + "PageRestService", + "ModuleRestService", + function ( + $rootScope, + $scope, + ngAppSettings, + postService, + pageService, + moduleService + ) { + var ctrl = this; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.types = ["Page", "Post", "Module"]; + ctrl.moduleContentId = null; + ctrl.type = "Page"; + ctrl.navs = []; + ctrl.data = { + items: [], + }; + // ctrl.goToPath = $rootScope.goToPath; + ctrl.$onInit = function () { + $("#modal-content-filter").on("shown.bs.modal", function () { + if (ctrl.initData) { + ctrl.data = ctrl.initData; + } else { + if (!ctrl.data.items.length) { + ctrl.loadData(); + } + } + }); + }; + ctrl.closeDialog = function () { + $("#modal-content-filter").modal("hide"); + }; + ctrl.loadData = async function (pageIndex) { + ctrl.request.query = ctrl.query + ctrl.srcId; + ctrl.navs = []; + if (pageIndex !== undefined) { + ctrl.request.pageIndex = pageIndex; + } + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = d.toISOString(); + } + if (ctrl.request.toDate !== null) { + var d = new Date(ctrl.request.toDate); + ctrl.request.toDate = d.toISOString(); + } + + switch (ctrl.type) { + case "Page": + ctrl.loadPages(); + break; + case "Post": + ctrl.loadPosts(); + break; + case "Module": + ctrl.loadModules(); + break; + } + }; + ctrl.edit = function (nav) { + switch (ctrl.type) { + case "Page": + ctrl.goToPath(`/admin/page/details/${nav.id}`); + break; + case "Post": + ctrl.goToPath(`/admin/post/details/${nav.id}`); + break; + case "Module": + ctrl.goToPath(`/admin/module/details/${nav.id}`); + break; + } + }; + ctrl.loadModules = async function () { $rootScope.isBusy = true; - var reader = new FileReader(); - reader.readAsDataURL(file); - reader.onload = function () { - var index = reader.result.indexOf(",") + 1; - var base64 = reader.result.substring(index); - $scope.activedMedia.mediaFile.fileName = $rootScope.generateKeyword( - file.name.substring(0, file.name.lastIndexOf(".")), - "-" - ); - $scope.activedMedia.mediaFile.extension = file.name.substring( - file.name.lastIndexOf(".") - ); - $scope.activedMedia.mediaFile.fileStream = reader.result; + var response = await moduleService.getList(ctrl.request); + if (response.success) { + ctrl.data = response.data; $rootScope.isBusy = false; $scope.$apply(); - }; - reader.onerror = function (error) { - $rootScope.showErrors([error]); + } else { + $rootScope.showErrors(response.errors); $rootScope.isBusy = false; - }; - } else { - return null; - } - }; - $scope.togglePreview = function (item) { - item.isPreview = item.isPreview === undefined ? true : !item.isPreview; - }; - $scope.clone = async function (id) { - $rootScope.isBusy = true; - var resp = await service.cloneMedia(id); - if (resp && resp.success) { - $scope.activedMedia = resp.data; - $rootScope.showMessage("Update successfully!", "success"); - $rootScope.isBusy = false; - $scope.$apply(); - //$location.path('/admin/media/details/' + resp.data.id); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); + $scope.$apply(); } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - $scope.saveSuccessCallback = function () { - $scope.getList(); - }; - $scope.removeCallback = function () { - $scope.getList(); - }; - }, -]); - -modules.component("mixSelectIcons", { - templateUrl: - "/mix-app/views/app-portal/components/mix-select-icons/mix-select-icons.html", - controller: [ - "$rootScope", - "$scope", - "$location", - "$element", - function ($rootScope, $scope, $location, $element) { - var ctrl = this; - ctrl.limitTo = 20; - ctrl.container = $element[0].querySelector(".list-icon"); - ctrl.translate = function (keyword) { - return $rootScope.translate(keyword); }; - ctrl.showMore = () => { - if ( - ctrl.container.scrollTop >= ctrl.container.scrollHeight - 200 && - ctrl.limitTo < ctrl.options.length - ) { - ctrl.limitTo *= 2; + ctrl.loadPosts = async function () { + $rootScope.isBusy = true; + var response = await postService.getList(ctrl.request); + if (response.success) { + ctrl.data = response.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); } }; - ctrl.select = function (ico) { - ctrl.data = ico.class; + ctrl.loadPages = async function () { + $rootScope.isBusy = true; + var response = await pageService.getList(ctrl.request); + if (response.success) { + ctrl.data = response.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + ctrl.select = function (nav) { + var current = $rootScope.findObjectByKey(ctrl.data.items, "id", nav.id); + if (!nav.isActive && ctrl.callback) { + ctrl.callback({ + nav: nav, + type: ctrl.type, + }); + } + if (ctrl.isMultiple) { + current.isActive = !current.isActive; + } else { + if (!nav.isActive) { + angular.forEach(ctrl.data.items, (element) => { + element.isActive = false; + }); + } + current.isActive = !nav.isActive; + } + }; + ctrl.saveSelected = function () { + ctrl.selected = $rootScope.filterArray( + ctrl.data, + ["isActived"], + [true] + ); + setTimeout(() => { + ctrl.save().then(() => { + ctrl.loadPosts(); + }); + }, 500); + }; + ctrl.limString = function (str, max) { + if (str) { + return str.length > max ? str.substring(0, max) + " ..." : str; + } }; }, ], - bindings: { - data: "=", - prefix: "=", - options: "=", - }, }); -modules.component("mixTemplateEditor", { +modules.component("modalBookmark", { templateUrl: - "/mix-app/views/app-portal/components/mix-template-editor/view.html", - bindings: { - template: "=", - folderType: "=", - isReadonly: "=?", - lineCount: "=?", - hideJs: "=?", - hideCss: "=?", - }, + "/mix-app/views/app-portal/components/modal-bookmark/modal-bookmark.html", controller: [ - "$scope", "$rootScope", + "$scope", + "localStorageService", "$routeParams", - "ngAppSettings", - "AppSettingsService", - "TemplateService", + "$location", function ( - $scope, $rootScope, + $scope, + localStorageService, $routeParams, - ngAppSettings, - appSettingsService, - service + $location ) { - BaseCtrl.call( - this, - $scope, - $rootScope, - $routeParams, - ngAppSettings, - service - ); var ctrl = this; - ctrl.isNull = false; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.selectPane = function (pane) { - ctrl.activedPane = pane; - }; - ctrl.selectTemplate = function (template) { - ctrl.template = template; - $scope.$broadcast("updateContentCodeEditors", []); + ctrl.searchText = ""; + ctrl.defaultModel = { + url: "", + title: "", }; - ctrl.new = function () { - ctrl.template.id = 0; + ctrl.bookmarks = []; + ctrl.model = null; + ctrl.$onInit = function () { + ctrl.model = angular.copy(ctrl.defaultModel); + ctrl.getCurrentUrl(); + ctrl.bookmarks = localStorageService.get("bookmarks") || []; }; - ctrl.init = async function () { - if (ctrl.folderType) { - var themeId = $rootScope.mixConfigurations.data.ThemeId; - ctrl.request.key = ctrl.folderType; - var resp = await service.getList(ctrl.request, [themeId]); - - if (resp && resp.success) { - ctrl.templates = resp.data.items; - if (!ctrl.template) { - ctrl.template = ctrl.templates[0]; - } - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - } - } + ctrl.goToPath = function (url) { + $rootScope.goToPath(url); + $("#dlg-bookmark").modal("hide"); }; - ctrl.updateTemplateContent = function (content) { - ctrl.template.content = content; + ctrl.getCurrentUrl = function (url) { + url = url || $location.url(); + ctrl.model.url = url; + ctrl.model.title = url; }; - ctrl.updateStyleContent = function (content) { - ctrl.template.scripts = content; + ctrl.removeBookmark = function (url) { + $rootScope.removeObjectByKey(ctrl.bookmarks, "url", url); + localStorageService.set("bookmarks", ctrl.bookmarks); }; - ctrl.updateScriptContent = function (content) { - ctrl.template.styles = content; + ctrl.addBookmark = function () { + var current = $rootScope.findObjectByKey( + ctrl.bookmarks, + "url", + ctrl.model.url + ); + if (current) { + current.title = ctrl.model.title; + } else { + ctrl.bookmarks.push(ctrl.model); + } + localStorageService.set("bookmarks", ctrl.bookmarks); + ctrl.model = angular.copy(ctrl.defaultModel); }; }, ], @@ -14242,66 +14468,6 @@ modules.component("mixValueEditor", { ], }); -modules.component("modalBookmark", { - templateUrl: - "/mix-app/views/app-portal/components/modal-bookmark/modal-bookmark.html", - controller: [ - "$rootScope", - "$scope", - "localStorageService", - "$routeParams", - "$location", - function ( - $rootScope, - $scope, - localStorageService, - $routeParams, - $location - ) { - var ctrl = this; - ctrl.searchText = ""; - ctrl.defaultModel = { - url: "", - title: "", - }; - ctrl.bookmarks = []; - ctrl.model = null; - ctrl.$onInit = function () { - ctrl.model = angular.copy(ctrl.defaultModel); - ctrl.getCurrentUrl(); - ctrl.bookmarks = localStorageService.get("bookmarks") || []; - }; - ctrl.goToPath = function (url) { - $rootScope.goToPath(url); - $("#dlg-bookmark").modal("hide"); - }; - ctrl.getCurrentUrl = function (url) { - url = url || $location.url(); - ctrl.model.url = url; - ctrl.model.title = url; - }; - ctrl.removeBookmark = function (url) { - $rootScope.removeObjectByKey(ctrl.bookmarks, "url", url); - localStorageService.set("bookmarks", ctrl.bookmarks); - }; - ctrl.addBookmark = function () { - var current = $rootScope.findObjectByKey( - ctrl.bookmarks, - "url", - ctrl.model.url - ); - if (current) { - current.title = ctrl.model.title; - } else { - ctrl.bookmarks.push(ctrl.model); - } - localStorageService.set("bookmarks", ctrl.bookmarks); - ctrl.model = angular.copy(ctrl.defaultModel); - }; - }, - ], -}); - modules.component("modalNavDatas", { templateUrl: "/mix-app/views/app-portal/components/modal-nav-datas/view.html", bindings: { @@ -14413,192 +14579,24 @@ modules.component("modalNavDatas", { } }); } - var getData = await dataService.filter(ctrl.request); - ctrl.data = getData.data; - angular.forEach(ctrl.data.items, (e) => { - if (ctrl.selectedIds.includes(e.id)) { - e.isSelected = true; - } - }); - $scope.$apply(); - }; - ctrl.update = function (data) { - let url = `/admin/mix-database-data/details?dataContentId=${ - data.id - }&mixDatabaseName=${ctrl.mixDatabaseName}&mixDatabaseTitle=${ - ctrl.mixDatabaseTitle - }&parentId=${ctrl.parentId || ""}&parentName=${ - ctrl.parentName || "" - }&guidParentId=${ctrl.guidParentId || ""}`; - $location.url(url); - }; - }, - ], -}); - -modules.component("modalContentFilter", { - templateUrl: - "/mix-app/views/app-portal/components/modal-content-filter/modal-content-filter.html", - bindings: { - query: "=", - initData: "=?", - selected: "=", - callback: "&?", - save: "&?", - }, - controller: [ - "$rootScope", - "$scope", - "ngAppSettings", - "PostRestService", - "PageRestService", - "ModuleRestService", - function ( - $rootScope, - $scope, - ngAppSettings, - postService, - pageService, - moduleService - ) { - var ctrl = this; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.types = ["Page", "Post", "Module"]; - ctrl.moduleContentId = null; - ctrl.type = "Page"; - ctrl.navs = []; - ctrl.data = { - items: [], - }; - // ctrl.goToPath = $rootScope.goToPath; - ctrl.$onInit = function () { - $("#modal-content-filter").on("shown.bs.modal", function () { - if (ctrl.initData) { - ctrl.data = ctrl.initData; - } else { - if (!ctrl.data.items.length) { - ctrl.loadData(); - } - } - }); - }; - ctrl.closeDialog = function () { - $("#modal-content-filter").modal("hide"); - }; - ctrl.loadData = async function (pageIndex) { - ctrl.request.query = ctrl.query + ctrl.srcId; - ctrl.navs = []; - if (pageIndex !== undefined) { - ctrl.request.pageIndex = pageIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var d = new Date(ctrl.request.toDate); - ctrl.request.toDate = d.toISOString(); - } - - switch (ctrl.type) { - case "Page": - ctrl.loadPages(); - break; - case "Post": - ctrl.loadPosts(); - break; - case "Module": - ctrl.loadModules(); - break; - } - }; - ctrl.edit = function (nav) { - switch (ctrl.type) { - case "Page": - ctrl.goToPath(`/admin/page/details/${nav.id}`); - break; - case "Post": - ctrl.goToPath(`/admin/post/details/${nav.id}`); - break; - case "Module": - ctrl.goToPath(`/admin/module/details/${nav.id}`); - break; - } - }; - ctrl.loadModules = async function () { - $rootScope.isBusy = true; - var response = await moduleService.getList(ctrl.request); - if (response.success) { - ctrl.data = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - ctrl.loadPosts = async function () { - $rootScope.isBusy = true; - var response = await postService.getList(ctrl.request); - if (response.success) { - ctrl.data = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - ctrl.loadPages = async function () { - $rootScope.isBusy = true; - var response = await pageService.getList(ctrl.request); - if (response.success) { - ctrl.data = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - ctrl.select = function (nav) { - var current = $rootScope.findObjectByKey(ctrl.data.items, "id", nav.id); - if (!nav.isActive && ctrl.callback) { - ctrl.callback({ - nav: nav, - type: ctrl.type, - }); - } - if (ctrl.isMultiple) { - current.isActive = !current.isActive; - } else { - if (!nav.isActive) { - angular.forEach(ctrl.data.items, (element) => { - element.isActive = false; - }); - } - current.isActive = !nav.isActive; - } - }; - ctrl.saveSelected = function () { - ctrl.selected = $rootScope.filterArray( - ctrl.data, - ["isActived"], - [true] - ); - setTimeout(() => { - ctrl.save().then(() => { - ctrl.loadPosts(); - }); - }, 500); - }; - ctrl.limString = function (str, max) { - if (str) { - return str.length > max ? str.substring(0, max) + " ..." : str; - } + var getData = await dataService.filter(ctrl.request); + ctrl.data = getData.data; + angular.forEach(ctrl.data.items, (e) => { + if (ctrl.selectedIds.includes(e.id)) { + e.isSelected = true; + } + }); + $scope.$apply(); + }; + ctrl.update = function (data) { + let url = `/admin/mix-database-data/details?dataContentId=${ + data.id + }&mixDatabaseName=${ctrl.mixDatabaseName}&mixDatabaseTitle=${ + ctrl.mixDatabaseTitle + }&parentId=${ctrl.parentId || ""}&parentName=${ + ctrl.parentName || "" + }&guidParentId=${ctrl.guidParentId || ""}`; + $location.url(url); }; }, ], @@ -14812,91 +14810,6 @@ modules.component("modalNavPages", { ], }); -modules.component("modalNavPosts", { - templateUrl: - "/mix-app/views/app-portal/components/modal-nav-posts/modal-nav-posts.html", - bindings: { - srcColumn: "=", - srcId: "=", - query: "=", - selected: "=", - save: "&", - }, - controller: [ - "$rootScope", - "$scope", - "$routeParams", - "ngAppSettings", - "PostRestService", - function ($rootScope, $scope, $routeParams, ngAppSettings, postService) { - var ctrl = this; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.navs = []; - ctrl.associations = []; - ctrl.data = { items: [] }; - ctrl.loadPosts = async function (pageIndex) { - // ctrl.request.query = ctrl.query + ctrl.srcId; - if (pageIndex !== undefined) { - ctrl.request.pageIndex = pageIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var d = new Date(ctrl.request.toDate); - ctrl.request.toDate = d.toISOString(); - } - if ($routeParams.type) { - ctrl.request.postType = $routeParams.type; - } else { - ctrl.request.postType = ""; - } - var response = await postService.getList(ctrl.request); - if (response.success) { - ctrl.data = response.data; - // ctrl.navs = []; - // angular.forEach(response.data.items, function (e) { - // var item = { - // priority: e.priority, - // description: e.title, - // postId: e.id, - // image: e.thumbnailUrl, - // specificulture: e.specificulture, - // post: e, - // status: "Published", - // isActived: false, - // }; - // item[ctrl.srcColumn] = ctrl.srcId; - // ctrl.navs.push(item); - // }); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - ctrl.select = async (associations) => { - ctrl.associations = associations; - }; - ctrl.saveSelected = function () { - ctrl.selected = $rootScope.filterArray( - ctrl.navs, - ["isActived"], - [true] - ); - setTimeout(() => { - ctrl.save().then(() => { - ctrl.loadPosts(); - }); - }, 500); - }; - }, - ], -}); - modules.component("modalNavMetas", { templateUrl: "/mix-app/views/app-portal/components/modal-nav-metas/view.html", bindings: { @@ -15191,381 +15104,219 @@ modules.component("modalNavMetas", { ], }); -modules.component("modalNavs", { - templateUrl: "/mix-app/views/app-portal/components/modal-navs/view.html", - bindings: { - modelName: "=", - viewType: "=", - selects: "=", - isSingle: "=?", - isGlobal: "=?", - save: "&", - }, - controller: [ - "$rootScope", - "$scope", - "$routeParams", - "ngAppSettings", - function ($rootScope, $scope, $routeParams, ngAppSettings) { - var ctrl = this; - ctrl.request = angular.copy(ngAppSettings.request); - ctrl.contentStatuses = angular.copy(ngAppSettings.contentStatuses); - ctrl.viewmodel = null; - ctrl.data = null; - ctrl.isInit = false; - ctrl.isValid = true; - ctrl.errors = []; - ctrl.selected = []; - - ctrl.init = function () { - ctrl.service = $rootScope.getRestService(ctrl.modelName, ctrl.isGlobal); - ctrl.prefix = "modal_navs_" + ctrl.modelName; - ctrl.cols = ctrl.selects.split(","); - ctrl.getList(); - }; - - ctrl.getList = async function (pageIndex) { - if (pageIndex !== undefined) { - ctrl.request.pageIndex = pageIndex; - } - if (ctrl.request.fromDate !== null) { - var d = new Date(ctrl.request.fromDate); - ctrl.request.fromDate = d.toISOString(); - } - if (ctrl.request.toDate !== null) { - var d = new Date(ctrl.request.toDate); - ctrl.request.toDate = d.toISOString(); - } - var resp = await ctrl.service.getList(ctrl.request); - if (resp.success) { - ctrl.data = resp.data; - $.each(ctrl.data.items, function (i, data) { - $.each(ctrl.viewmodels, function (i, e) { - if (e.dataContentId === data.id) { - data.isHidden = true; - } - }); - }); - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - - // ctrl.loadData = async function (pageIndex) { - // ctrl.request.query = ctrl.query + ctrl.srcId; - // if (pageIndex !== undefined) { - // ctrl.request.pageIndex = pageIndex; - // } - // if (ctrl.request.fromDate !== null) { - // var d = new Date(ctrl.request.fromDate); - // ctrl.request.fromDate = d.toISOString(); - // } - // if (ctrl.request.toDate !== null) { - // var d = new Date(ctrl.request.toDate); - // ctrl.request.toDate = d.toISOString(); - // } - // var response = await pageService.getList(ctrl.request); - // if (response.success) { - // ctrl.data = response.data; - // ctrl.navs = []; - // angular.forEach(response.data.items, function (e) { - // var item = { - // priority: e.priority, - // description: e.title, - // pageId: e.id, - // image: e.thumbnailUrl, - // specificulture: e.specificulture, - // status: 'Published', - // isActived: false - // }; - // item[ctrl.srcField] = ctrl.srcId; - // ctrl.navs.push(item); - // }); - // $rootScope.isBusy = false; - // $scope.$apply(); - // } - // else { - // $rootScope.showErrors(response.errors); - // $rootScope.isBusy = false; - // $scope.$apply(); - // } - // } - ctrl.selectAll = function (isSelectAll) { - angular.forEach(ctrl.data.items, (element) => { - element.isActived = isSelectAll; - }); - }; - ctrl.selectChange = function (item) { - if (ctrl.isSingle == "true" && item.isActived) { - angular.forEach(ctrl.data.items, (element) => { - element.isActived = false; - }); - item.isActived = true; - } - }; - ctrl.saveSelected = function () { - ctrl.selected = $rootScope.filterArray( - ctrl.data.items, - ["isActived"], - [true] - ); - if (ctrl.save) { - ctrl.save({ selected: ctrl.selected }); - } - }; - }, - ], -}); - -modules.component("modalPermission", { +modules.component("modalNavPosts", { templateUrl: - "/mix-app/views/app-portal/components/modal-permission/modal-permission.html", - controller: "PermissionController", - bindings: { - message: "=", - }, -}); - -modules.component("monacoEditor", { - templateUrl: "/mix-app/views/app-portal/components/monaco-editor/view.html", + "/mix-app/views/app-portal/components/modal-nav-posts/modal-nav-posts.html", bindings: { - editor: "=?", - content: "=", - defaultContent: "=?", - contentId: "=", - isVisible: "=", - isReadonly: "=?", - lineCount: "=?", - ext: "=", - updateContent: "&", + srcColumn: "=", + srcId: "=", + query: "=", + selected: "=", + save: "&", }, controller: [ "$rootScope", "$scope", - "$element", - function ($rootScope, $scope, $element) { + "$routeParams", + "ngAppSettings", + "PostRestService", + function ($rootScope, $scope, $routeParams, ngAppSettings, postService) { var ctrl = this; - ctrl.previousId = null; - ctrl.minHeight = 400; - ctrl.isFull = false; - ctrl.id = Math.floor(Math.random() * 100) + 1; - ctrl.$onInit = function () { - setTimeout(() => { - if (!ctrl.content) { - ctrl.content = "\r\n"; - } - }, 100); - }; - ctrl.$onChanges = function (changes) { - if (changes.content) { - ctrl.updateContent(changes.content); + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.navs = []; + ctrl.associations = []; + ctrl.data = { items: [] }; + ctrl.loadPosts = async function (pageIndex) { + // ctrl.request.query = ctrl.query + ctrl.srcId; + if (pageIndex !== undefined) { + ctrl.request.pageIndex = pageIndex; } - if (changes.isVisible || changes.isReadonly) { - ctrl.updateEditors(); + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = d.toISOString(); } - }; - - ctrl.showHelper = function (url) { - $rootScope.showHelper(url); - }; - - this.$doCheck = function () { - if (ctrl.previousId != null && ctrl.previousId !== ctrl.contentId) { - ctrl.previousId = ctrl.contentId; - ctrl.updateContent(ctrl.content); + if (ctrl.request.toDate !== null) { + var d = new Date(ctrl.request.toDate); + ctrl.request.toDate = d.toISOString(); } - if (ctrl.isReadonly !== ctrl._readonly && ctrl.editor) { - ctrl._readonly = ctrl.isReadonly; - ctrl.editor.updateOptions({ readOnly: ctrl._readonly }); + if ($routeParams.type) { + ctrl.request.postType = $routeParams.type; + } else { + ctrl.request.postType = ""; } - if (ctrl.isVisible && ctrl.editor) { - setTimeout(() => { - var h = ctrl.lineCount - ? ctrl.lineCount - : ctrl.editor.getModel().getLineCount() * 18; - $($element).height(h); - ctrl.editor.layout(); - }, 100); + var response = await postService.getList(ctrl.request); + if (response.success) { + ctrl.data = response.data; + // ctrl.navs = []; + // angular.forEach(response.data.items, function (e) { + // var item = { + // priority: e.priority, + // description: e.title, + // postId: e.id, + // image: e.thumbnailUrl, + // specificulture: e.specificulture, + // post: e, + // status: "Published", + // isActived: false, + // }; + // item[ctrl.srcColumn] = ctrl.srcId; + // ctrl.navs.push(item); + // }); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); } - }.bind(this); - - ctrl.initEditor = function () { - // ctrl.lineCount = parseInt(ctrl.lineCount) || 100; - setTimeout(() => { - ctrl.previousId = ctrl.contentId; - ctrl.updateEditors(); - }, 100); - }; - - ctrl.updateContent = function (content) { - ctrl.editor.setValue(content); - // lineCount = ctrl.editor.getModel().getLineCount(); - - // var h = ctrl.editor.getModel().getLineCount() * 18; - var h = ctrl.lineCount * 18; - $($element).height(h); - ctrl.editor.layout(); }; - ctrl.updateEditors = function () { - $.each($($element).find(".code-editor"), function (i, e) { - if (e) { - var model = { - value: ctrl.content || ctrl.defaultContent, - readOnly: ctrl.isReadonly === "true" || ctrl.isReadonly, - - lineNumbers: "on", - roundedSelection: false, - scrollBeyondLastLine: false, - contextmenu: false, - // theme: "vs-dark", - formatOnType: true, - formatOnPaste: true, - // wordWrap: "on", - automaticLayout: true, // the important part - }; - switch (ctrl.ext) { - case ".json": - // ctrl.content = JSON.stringify(ctrl.content); - model.language = "json"; - break; - case ".webmanifest": - model.language = "json"; - break; - case ".js": - model.language = "javascript"; - break; - case ".css": - model.language = "css"; - break; - case ".cshtml": - model.language = "razor"; - break; - case ".cs": - model.language = "csharp"; - break; - default: - model.language = "razor"; - break; - } - ctrl.editor = monaco.editor.create(e, model); - - ctrl.editor.getModel().onDidChangeContent(() => { - ctrl.content = ctrl.editor.getModel().getValue(); - ctrl.updateContent({ content: ctrl.content }); - }); - ctrl.editor.addCommand( - monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, - function () { - var btn = document.getElementById("btnToSubmit"); - btn.click(); - } - ); - - if (ctrl.isFull) { - $(e).height(window.innerHeight); - } else { - $(e).height(ctrl.minHeight); - } - - // setTimeout(() => { - // // var h = ctrl.editor.getModel().getLineCount() * 18; - // // h = h < ctrl.minHeight ? ctrl.minHeight : h; - // var h = ctrl.lineCount * 20; - // $(e).height(h); - // ctrl.editor.layout(); - // }, 200); - } - }); + ctrl.select = async (associations) => { + ctrl.associations = associations; }; - - ctrl.fullscreen = function (event) { - // const element = $(event.target).parents(".monaco-editor"); - - // event.target.addEventListener('click', () => { - // if (screenfull.isEnabled) { - // screenfull.request(element); - // } - // }); - // $.each($($element).find('.code-editor'), function (i, e) { - // //var container = $(this); - // if (e) {} - // }); - // console.log($(event.target)); - - $(event.target) - .parents(".monaco-editor") - .toggleClass("monaco-editor-full"); - - ctrl.isFull = !ctrl.isFull; - - ctrl.editor.dispose(); - - // var h; - - // ctrl.editor.dispose(); - // if ($(".monaco-editor.container-code-editor.monaco-editor-full")[0]) { - // // Do something if class exists - // h = window.innerHeight; - // $( - // ".monaco-editor.container-code-editor.monaco-editor-full .code-editor" - // ).height(h); - // document.body.style.overflow = "hidden"; - // } else { - // // Do something if class does not exist - // h = ctrl.lineCount * 20; - // $(".monaco-editor .code-editor").height(h); - // document.body.style.overflow = "visible"; - // } - // ctrl.editor.layout(); - - ctrl.updateEditors(); + ctrl.saveSelected = function () { + ctrl.selected = $rootScope.filterArray( + ctrl.navs, + ["isActived"], + [true] + ); + setTimeout(() => { + ctrl.save().then(() => { + ctrl.loadPosts(); + }); + }, 500); }; }, ], }); -modules.component("portalThemeSettings", { - templateUrl: - "/mix-app/views/app-portal/components/portal-theme-settings/view.html", +modules.component("modalNavs", { + templateUrl: "/mix-app/views/app-portal/components/modal-navs/view.html", bindings: { - showLink: "=", + modelName: "=", + viewType: "=", + selects: "=", + isSingle: "=?", + isGlobal: "=?", + save: "&", }, controller: [ "$rootScope", "$scope", - "AppSettingsServices", - function ($rootScope, $scope, appSettingsServices) { - var ctrl = this; - this.$onInit = function () { - ctrl.portalThemeSettings = - $rootScope.globalSettings.portalThemeSettings; - }; - ctrl.applyThemeSettings = function () { - $rootScope.globalSettings.portalThemeSettings = - ctrl.portalThemeSettings; + "$routeParams", + "ngAppSettings", + function ($rootScope, $scope, $routeParams, ngAppSettings) { + var ctrl = this; + ctrl.request = angular.copy(ngAppSettings.request); + ctrl.contentStatuses = angular.copy(ngAppSettings.contentStatuses); + ctrl.viewmodel = null; + ctrl.data = null; + ctrl.isInit = false; + ctrl.isValid = true; + ctrl.errors = []; + ctrl.selected = []; + + ctrl.init = function () { + ctrl.service = $rootScope.getRestService(ctrl.modelName, ctrl.isGlobal); + ctrl.prefix = "modal_navs_" + ctrl.modelName; + ctrl.cols = ctrl.selects.split(","); + ctrl.getList(); }; - ctrl.saveThemeSettings = async function () { - var resp = await appSettingsServices.saveAppSettings( - "PortalThemeSettings", - ctrl.portalThemeSettings - ); - if (resp && resp.success) { - $rootScope.showMessage("success", "success"); + + ctrl.getList = async function (pageIndex) { + if (pageIndex !== undefined) { + ctrl.request.pageIndex = pageIndex; + } + if (ctrl.request.fromDate !== null) { + var d = new Date(ctrl.request.fromDate); + ctrl.request.fromDate = d.toISOString(); + } + if (ctrl.request.toDate !== null) { + var d = new Date(ctrl.request.toDate); + ctrl.request.toDate = d.toISOString(); + } + var resp = await ctrl.service.getList(ctrl.request); + if (resp.success) { + ctrl.data = resp.data; + $.each(ctrl.data.items, function (i, data) { + $.each(ctrl.viewmodels, function (i, e) { + if (e.dataContentId === data.id) { + data.isHidden = true; + } + }); + }); $rootScope.isBusy = false; $scope.$apply(); } else { if (resp) { $rootScope.showErrors(resp.errors); } + $rootScope.isBusy = false; $scope.$apply(); } }; + + // ctrl.loadData = async function (pageIndex) { + // ctrl.request.query = ctrl.query + ctrl.srcId; + // if (pageIndex !== undefined) { + // ctrl.request.pageIndex = pageIndex; + // } + // if (ctrl.request.fromDate !== null) { + // var d = new Date(ctrl.request.fromDate); + // ctrl.request.fromDate = d.toISOString(); + // } + // if (ctrl.request.toDate !== null) { + // var d = new Date(ctrl.request.toDate); + // ctrl.request.toDate = d.toISOString(); + // } + // var response = await pageService.getList(ctrl.request); + // if (response.success) { + // ctrl.data = response.data; + // ctrl.navs = []; + // angular.forEach(response.data.items, function (e) { + // var item = { + // priority: e.priority, + // description: e.title, + // pageId: e.id, + // image: e.thumbnailUrl, + // specificulture: e.specificulture, + // status: 'Published', + // isActived: false + // }; + // item[ctrl.srcField] = ctrl.srcId; + // ctrl.navs.push(item); + // }); + // $rootScope.isBusy = false; + // $scope.$apply(); + // } + // else { + // $rootScope.showErrors(response.errors); + // $rootScope.isBusy = false; + // $scope.$apply(); + // } + // } + ctrl.selectAll = function (isSelectAll) { + angular.forEach(ctrl.data.items, (element) => { + element.isActived = isSelectAll; + }); + }; + ctrl.selectChange = function (item) { + if (ctrl.isSingle == "true" && item.isActived) { + angular.forEach(ctrl.data.items, (element) => { + element.isActived = false; + }); + item.isActived = true; + } + }; + ctrl.saveSelected = function () { + ctrl.selected = $rootScope.filterArray( + ctrl.data.items, + ["isActived"], + [true] + ); + if (ctrl.save) { + ctrl.save({ selected: ctrl.selected }); + } + }; }, ], }); @@ -15612,138 +15363,208 @@ modules.component("modalTemplate", { ], }); -modules.component("navigators", { +modules.component("modalPermission", { templateUrl: - "/mix-app/views/app-portal/components/navigations/navigations.html", + "/mix-app/views/app-portal/components/modal-permission/modal-permission.html", + controller: "PermissionController", bindings: { - modelName: "=", - parentId: "=", - associations: "=", - titleField: "=?", + message: "=", + }, +}); - prefix: "=", - detailUrl: "=", - data: "=", - titleMaxLength: "=?", - callback: "&?", +modules.component("monacoEditor", { + templateUrl: "/mix-app/views/app-portal/components/monaco-editor/view.html", + bindings: { + editor: "=?", + content: "=", + defaultContent: "=?", + contentId: "=", + isVisible: "=", + isReadonly: "=?", + lineCount: "=?", + ext: "=", + updateContent: "&", }, controller: [ "$rootScope", "$scope", - "ngAppSettings", - "$location", - function ($rootScope, $scope, ngAppSettings, $location) { + "$element", + function ($rootScope, $scope, $element) { var ctrl = this; - var service; - ctrl.selected = null; - ctrl.activedIndex = null; - ctrl.$onInit = async () => { - ctrl.titleField = ctrl.titleField || "title"; - service = $rootScope.getRestService(ctrl.modelName); - ctrl.associationRequest = angular.copy(ngAppSettings.request); - ctrl.associationRequest.orderBy = "Priority"; - ctrl.associationRequest.direction = "Asc"; - ctrl.associationRequest.parentId = ctrl.parentId; - await ctrl.loadAssociations(); - ctrl.loadData(); - }; - ctrl.loadAssociations = async () => { - var getAssociations = await service.getList(ctrl.associationRequest); - ctrl.associations = getAssociations.data.items; - }; - ctrl.loadData = async () => { - var maxPriority = 0; - if (ctrl.associations.length > 0) { - maxPriority = - ctrl.associations[ctrl.associations.length - 1].priority || 0; - } - angular.forEach(ctrl.data, function (e, i) { - let nav = ctrl.associations.filter((m) => m.childId == e.id)[0]; - if (nav) { - if (nav.priority == undefined) { - nav.priority = maxPriority + 1; - maxPriority++; - } - e.isActived = true; - e.priority = nav.priority || 0; - } else { - e.isActived = false; - e.priority = maxPriority + 1; - maxPriority++; + ctrl.previousId = null; + ctrl.minHeight = 400; + ctrl.isFull = false; + ctrl.id = Math.floor(Math.random() * 100) + 1; + ctrl.$onInit = function () { + setTimeout(() => { + if (!ctrl.content) { + ctrl.content = "\r\n"; } - e.isActived = nav != null; - }); - ctrl.data = $rootScope.sortArray(ctrl.data, "priority"); + }, 100); }; - ctrl.select = async (obj) => { - if (obj.isActived) { - ctrl.selectItem(obj); - } else { - ctrl.removeItem(obj); + ctrl.$onChanges = function (changes) { + if (changes.content) { + ctrl.updateContent(changes.content); } - if (ctrl.callback) { - ctrl.callback({ associations: ctrl.associations }); - await ctrl.loadAssociations(); + if (changes.isVisible || changes.isReadonly) { + ctrl.updateEditors(); } }; - ctrl.removeItem = async (obj) => { - var nav = ctrl.associations.filter((m) => m.childId == obj.id)[0]; - $rootScope.removeObjectByKey(ctrl.associations, "childId", obj.id); - if (nav && nav.id) { - await service.delete([nav.id]); - $rootScope.showMessage("saved", "success"); - } + + ctrl.showHelper = function (url) { + $rootScope.showHelper(url); }; - ctrl.selectItem = async (obj) => { - var nav = { - parentId: ctrl.parentId, - childId: obj.id, - priority: obj.priority, - }; - if (ctrl.parentId) { - var result = await service.save(nav); - nav.id = result.data.id; - $rootScope.showMessage("saved", "success"); + + this.$doCheck = function () { + if (ctrl.previousId != null && ctrl.previousId !== ctrl.contentId) { + ctrl.previousId = ctrl.contentId; + ctrl.updateContent(ctrl.content); } - ctrl.associations.push(nav); - if (ctrl.callback) { - ctrl.callback({ selected: nav }); + if (ctrl.isReadonly !== ctrl._readonly && ctrl.editor) { + ctrl._readonly = ctrl.isReadonly; + ctrl.editor.updateOptions({ readOnly: ctrl._readonly }); } + if (ctrl.isVisible && ctrl.editor) { + setTimeout(() => { + var h = ctrl.lineCount + ? ctrl.lineCount + : ctrl.editor.getModel().getLineCount() * 18; + $($element).height(h); + ctrl.editor.layout(); + }, 100); + } + }.bind(this); + + ctrl.initEditor = function () { + // ctrl.lineCount = parseInt(ctrl.lineCount) || 100; + setTimeout(() => { + ctrl.previousId = ctrl.contentId; + ctrl.updateEditors(); + }, 100); }; - ctrl.getTitle = (item) => { - return item[ctrl.titleField]; - }; - ctrl.updateOrders = async function (index) { - if (index > ctrl.dragStartIndex) { - ctrl.data.splice(ctrl.dragStartIndex, 1); - } else { - ctrl.data.splice(ctrl.dragStartIndex + 1, 1); - } - angular.forEach(ctrl.data, function (e, i) { - e.priority = ctrl.minPriority + i; - }); - ctrl.saveOrder(); + + ctrl.updateContent = function (content) { + ctrl.editor.setValue(content); + // lineCount = ctrl.editor.getModel().getLineCount(); + + // var h = ctrl.editor.getModel().getLineCount() * 18; + var h = ctrl.lineCount * 18; + $($element).height(h); + ctrl.editor.layout(); }; - ctrl.saveOrder = async () => { - angular.forEach(ctrl.data, function (e, i) { - let nav = ctrl.associations.filter((m) => m.childId == e.id)[0]; - if (nav) { - nav.priority = ctrl.data[i].priority; + ctrl.updateEditors = function () { + $.each($($element).find(".code-editor"), function (i, e) { + if (e) { + var model = { + value: ctrl.content || ctrl.defaultContent, + readOnly: ctrl.isReadonly === "true" || ctrl.isReadonly, + + lineNumbers: "on", + roundedSelection: false, + scrollBeyondLastLine: false, + contextmenu: false, + // theme: "vs-dark", + formatOnType: true, + formatOnPaste: true, + // wordWrap: "on", + automaticLayout: true, // the important part + }; + switch (ctrl.ext) { + case ".json": + // ctrl.content = JSON.stringify(ctrl.content); + model.language = "json"; + break; + case ".webmanifest": + model.language = "json"; + break; + case ".js": + model.language = "javascript"; + break; + case ".css": + model.language = "css"; + break; + case ".cshtml": + model.language = "razor"; + break; + case ".cs": + model.language = "csharp"; + break; + default: + model.language = "razor"; + break; + } + ctrl.editor = monaco.editor.create(e, model); + + ctrl.editor.getModel().onDidChangeContent(() => { + ctrl.content = ctrl.editor.getModel().getValue(); + ctrl.updateContent({ content: ctrl.content }); + }); + ctrl.editor.addCommand( + monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, + function () { + var btn = document.getElementById("btnToSubmit"); + btn.click(); + } + ); + + if (ctrl.isFull) { + $(e).height(window.innerHeight); + } else { + $(e).height(ctrl.minHeight); + } + + // setTimeout(() => { + // // var h = ctrl.editor.getModel().getLineCount() * 18; + // // h = h < ctrl.minHeight ? ctrl.minHeight : h; + // var h = ctrl.lineCount * 20; + // $(e).height(h); + // ctrl.editor.layout(); + // }, 200); } }); - if (ctrl.parentId) { - var result = await service.saveMany(ctrl.associations); - if (result.success) { - $rootScope.showMessage("saved", "success"); - } - } - }; - ctrl.dragStart = function (index) { - ctrl.dragStartIndex = index; - ctrl.minPriority = ctrl.data[0].priority; }; - ctrl.goToDetails = async function (nav) { - $location.url(ctrl.detailUrl + nav[ctrl.key]); + + ctrl.fullscreen = function (event) { + // const element = $(event.target).parents(".monaco-editor"); + + // event.target.addEventListener('click', () => { + // if (screenfull.isEnabled) { + // screenfull.request(element); + // } + // }); + // $.each($($element).find('.code-editor'), function (i, e) { + // //var container = $(this); + // if (e) {} + // }); + // console.log($(event.target)); + + $(event.target) + .parents(".monaco-editor") + .toggleClass("monaco-editor-full"); + + ctrl.isFull = !ctrl.isFull; + + ctrl.editor.dispose(); + + // var h; + + // ctrl.editor.dispose(); + // if ($(".monaco-editor.container-code-editor.monaco-editor-full")[0]) { + // // Do something if class exists + // h = window.innerHeight; + // $( + // ".monaco-editor.container-code-editor.monaco-editor-full .code-editor" + // ).height(h); + // document.body.style.overflow = "hidden"; + // } else { + // // Do something if class does not exist + // h = ctrl.lineCount * 20; + // $(".monaco-editor .code-editor").height(h); + // document.body.style.overflow = "visible"; + // } + // ctrl.editor.layout(); + + ctrl.updateEditors(); }; }, ], @@ -15828,290 +15649,299 @@ modules.component("propertiesStructure", { el.setAttribute("type", "number"); break; - case "multilinetext": - el = document.createElement("textarea"); - break; - - default: - el = document.createElement("input"); - el.setAttribute("type", "text"); - formHtml.appendChild(el); - break; - } - el.setAttribute("ng-model", "data.jItem[" + e.name + "].value"); - el.setAttribute("placeholder", "{{$ctrl.title}}"); - formHtml.appendChild(label); - formHtml.appendChild(el); - }); - ctrl.viewmodel.formView.content = formHtml.innerHTML; - }; - - ctrl.generateName = function (col) { - col.systemName = $rootScope.generateKeyword( - col.displayName, - "", - true, - true - ); - }; - ctrl.removeAttr = function (index) { - if (ctrl.columns) { - ctrl.columns.splice(index, 1); - } - }; - ctrl.dragStart = function (index) { - ctrl.dragStartIndex = index; - }; - ctrl.updateOrders = function (index) { - if (index > ctrl.dragStartIndex) { - ctrl.columns.splice(ctrl.dragStartIndex, 1); - } else { - ctrl.columns.splice(ctrl.dragStartIndex + 1, 1); - } - angular.forEach(ctrl.columns, function (e, i) { - e.priority = i; - }); - }; - }, - ], - bindings: { - header: "=", - columns: "=", - }, -}); - -modules.component("propertiesValue", { - templateUrl: - "/mix-app/views/app-portal/components/properties-value/view.html", - bindings: { - title: "=", - columns: "=", - properties: "=", - }, - controller: [ - "$rootScope", - "$scope", - function ($rootScope, $scope) { - var ctrl = this; - ctrl.defaultAttr = { - title: "", - name: "", - default: null, - options: [], - priority: 0, - dataType: 7, - isGroupBy: false, - isSelect: false, - isDisplay: true, - width: 3, - }; - ctrl.selectedProp = null; - ctrl.mixConfigurations = $rootScope.globalSettings; - - ctrl.$doCheck = function () { - if ( - angular.toJson(ctrl.columns) != angular.toJson(ctrl.trackedColumns) - ) { - ctrl.trackedColumns = angular.copy(ctrl.columns); - ctrl.trackedProperties = angular.copy(ctrl.properties); - ctrl.loadEditors(); - } - }.bind(ctrl); - - ctrl.loadEditors = function () { - ctrl.properties = []; - for (let i = 0; i < ctrl.columns.length; i++) { - var col = ctrl.columns[i]; - var oldObj = - $rootScope.findObjectByKey( - ctrl.trackedProperties, - "name", - col.systemName - ) || {}; - - ctrl.properties.push({ - title: col.displayName, - name: col.systemName, - dataType: col.dataType, - value: oldObj.value || col.defaultValue, - options: col.options, - }); - } + case "multilinetext": + el = document.createElement("textarea"); + break; + + default: + el = document.createElement("input"); + el.setAttribute("type", "text"); + formHtml.appendChild(el); + break; + } + el.setAttribute("ng-model", "data.jItem[" + e.name + "].value"); + el.setAttribute("placeholder", "{{$ctrl.title}}"); + formHtml.appendChild(label); + formHtml.appendChild(el); + }); + ctrl.viewmodel.formView.content = formHtml.innerHTML; }; - ctrl.addAttr = function () { + ctrl.generateName = function (col) { + col.systemName = $rootScope.generateKeyword( + col.displayName, + "", + true, + true + ); + }; + ctrl.removeAttr = function (index) { if (ctrl.columns) { - var t = angular.copy(ctrl.defaultAttr); - ctrl.columns.push(t); + ctrl.columns.splice(index, 1); + } + }; + ctrl.dragStart = function (index) { + ctrl.dragStartIndex = index; + }; + ctrl.updateOrders = function (index) { + if (index > ctrl.dragStartIndex) { + ctrl.columns.splice(ctrl.dragStartIndex, 1); + } else { + ctrl.columns.splice(ctrl.dragStartIndex + 1, 1); } + angular.forEach(ctrl.columns, function (e, i) { + e.priority = i; + }); }; }, ], + bindings: { + header: "=", + columns: "=", + }, }); -modules.component("serviceHubPortal", { +modules.component("navigators", { templateUrl: - "/mix-app/views/app-portal/components/service-hub-portal/view.html", + "/mix-app/views/app-portal/components/navigations/navigations.html", bindings: { - mixDatabaseName: "=", - isSave: "=?", + modelName: "=", + parentId: "=", + associations: "=", + titleField: "=?", + + prefix: "=", + detailUrl: "=", + data: "=", + titleMaxLength: "=?", + callback: "&?", }, controller: [ "$rootScope", "$scope", - "RestMixDatabaseColumnPortalService", - "RestMixDatabaseDataClientService", - "UserServices", - function ($rootScope, $scope, columnService, service, userServices) { + "ngAppSettings", + "$location", + function ($rootScope, $scope, ngAppSettings, $location) { var ctrl = this; - BaseHub.call(this, ctrl); - ctrl.mixConfigurations = $rootScope.globalSettings; - ctrl.user = { - loggedIn: false, - connection: {}, + var service; + ctrl.selected = null; + ctrl.activedIndex = null; + ctrl.$onInit = async () => { + ctrl.titleField = ctrl.titleField || "title"; + service = $rootScope.getRestService(ctrl.modelName); + ctrl.associationRequest = angular.copy(ngAppSettings.request); + ctrl.associationRequest.orderBy = "Priority"; + ctrl.associationRequest.direction = "Asc"; + ctrl.associationRequest.parentId = ctrl.parentId; + await ctrl.loadAssociations(); + ctrl.loadData(); }; - ctrl.mixDatabaseData = null; - ctrl.isHide = true; - ctrl.hideContact = true; - ctrl.columns = []; - ctrl.members = []; - ctrl.errors = []; - ctrl.messages = { - items: [], + ctrl.loadAssociations = async () => { + var getAssociations = await service.getList(ctrl.associationRequest); + ctrl.associations = getAssociations.data.items; }; - ctrl.message = { connection: {}, content: "" }; - ctrl.request = { - uid: "", - specificulture: "", - action: "", - objectType: null, - data: {}, - room: "", - isMyself: true, - isSave: false, + ctrl.loadData = async () => { + var maxPriority = 0; + if (ctrl.associations.length > 0) { + maxPriority = + ctrl.associations[ctrl.associations.length - 1].priority || 0; + } + angular.forEach(ctrl.data, function (e, i) { + let nav = ctrl.associations.filter((m) => m.childId == e.id)[0]; + if (nav) { + if (nav.priority == undefined) { + nav.priority = maxPriority + 1; + maxPriority++; + } + e.isActived = true; + e.priority = nav.priority || 0; + } else { + e.isActived = false; + e.priority = maxPriority + 1; + maxPriority++; + } + e.isActived = nav != null; + }); + ctrl.data = $rootScope.sortArray(ctrl.data, "priority"); }; - ctrl.init = function () { - ctrl.mixDatabaseId = ctrl.mixDatabaseId || 0; - ctrl.request.specificulture = service.lang; - ctrl.request.room = ctrl.mixDatabaseName; - ctrl.request.isSave = ctrl.isSave == "true" || false; - ctrl.startConnection("serviceHub", ctrl.checkLoginStatus); + ctrl.select = async (obj) => { + if (obj.isActived) { + ctrl.selectItem(obj); + } else { + ctrl.removeItem(obj); + } + if (ctrl.callback) { + ctrl.callback({ associations: ctrl.associations }); + await ctrl.loadAssociations(); + } }; - ctrl.loadData = async function () { - /* - If input is data id => load ctrl.mixDatabaseData from service and handle it independently - Else modify input ctrl.mixDatabaseData - */ - $rootScope.isBusy = true; - var getDefault = await service.initData(ctrl.mixDatabaseName); - if (getDefault.success) { - ctrl.defaultData = getDefault.data; - ctrl.defaultData.data.user_name = ctrl.user.connection.name; - ctrl.defaultData.data.user_id = ctrl.user.connection.id; - ctrl.defaultData.data.user_avatar = ctrl.user.connection.avatar; - ctrl.defaultData.data.data_type = 9; - ctrl.mixDatabaseData = angular.copy(ctrl.defaultData); - $rootScope.isBusy = false; + ctrl.removeItem = async (obj) => { + var nav = ctrl.associations.filter((m) => m.childId == obj.id)[0]; + $rootScope.removeObjectByKey(ctrl.associations, "childId", obj.id); + if (nav && nav.id) { + await service.delete([nav.id]); + $rootScope.showMessage("saved", "success"); } - var getFields = await columnService.initData(ctrl.mixDatabaseName); - if (getFields.success) { - ctrl.columns = getFields.data; + }; + ctrl.selectItem = async (obj) => { + var nav = { + parentId: ctrl.parentId, + childId: obj.id, + priority: obj.priority, + }; + if (ctrl.parentId) { + var result = await service.save(nav); + nav.id = result.data.id; + $rootScope.showMessage("saved", "success"); + } + ctrl.associations.push(nav); + if (ctrl.callback) { + ctrl.callback({ selected: nav }); } }; - ctrl.submit = async function () { - if (ctrl.validate()) { - ctrl.request.action = "send_group_message"; - ctrl.request.uid = ctrl.user.connection.id; - ctrl.request.data = ctrl.mixDatabaseData.data; - ctrl.request.connection = ctrl.user.connection; - ctrl.connection.invoke("HandleRequest", JSON.stringify(ctrl.request)); - ctrl.mixDatabaseData = angular.copy(ctrl.defaultData); + ctrl.getTitle = (item) => { + return item[ctrl.titleField]; + }; + ctrl.updateOrders = async function (index) { + if (index > ctrl.dragStartIndex) { + ctrl.data.splice(ctrl.dragStartIndex, 1); + } else { + ctrl.data.splice(ctrl.dragStartIndex + 1, 1); } + angular.forEach(ctrl.data, function (e, i) { + e.priority = ctrl.minPriority + i; + }); + ctrl.saveOrder(); }; - ctrl.validate = function () { - var isValid = true; - ctrl.errors = []; - angular.forEach(ctrl.columns, function (column) { - if (column.regex) { - var regex = RegExp(column.regex, "g"); - isValid = regex.test(ctrl.mixDatabaseData.data[column.name]); - if (!isValid) { - ctrl.errors.push(`${column.name} is not match Regex`); - } - } - if (isValid && column.isEncrypt) { - ctrl.mixDatabaseData.data[column.name] = $rootScope.encrypt( - ctrl.mixDatabaseData.data[column.name] - ); + ctrl.saveOrder = async () => { + angular.forEach(ctrl.data, function (e, i) { + let nav = ctrl.associations.filter((m) => m.childId == e.id)[0]; + if (nav) { + nav.priority = ctrl.data[i].priority; } }); - return isValid; - }; - ctrl.receiveMessage = function (msg) { - switch (msg.responseKey) { - case "NewMember": - ctrl.newMember(msg.data); - // $('.widget-conversation').scrollTop = $('.widget-conversation')[0].scrollHeight; - break; - case "NewMessage": - ctrl.newMessage(msg.data); - break; - case "ConnectSuccess": - ctrl.user.loggedIn = true; - ctrl.initListMember(msg.data); - $scope.$apply(); - break; - case "PreviousMessages": - ctrl.messages = msg.data; - $scope.$apply(); - break; - case "MemberOffline": - ctrl.removeMember(msg.data); - break; - case "Error": - console.error(msg.data); - break; + if (ctrl.parentId) { + var result = await service.saveMany(ctrl.associations); + if (result.success) { + $rootScope.showMessage("saved", "success"); + } } }; - ctrl.newMessage = function (msg) { - ctrl.messages.items.push(msg); - $scope.$apply(); + ctrl.dragStart = function (index) { + ctrl.dragStartIndex = index; + ctrl.minPriority = ctrl.data[0].priority; }; - ctrl.newMember = function (member) { - var m = $rootScope.findObjectByKey(ctrl.members, "id", member.id); - if (!m) { - ctrl.members.push(member); - } - $scope.$apply(); + ctrl.goToDetails = async function (nav) { + $location.url(ctrl.detailUrl + nav[ctrl.key]); }; - ctrl.join = async function () { - ctrl.request.action = "join_group"; - ctrl.request.uid = ctrl.user.connection.id; - ctrl.request.data = ctrl.user.connection; - ctrl.message.connection = ctrl.user.connection; - ctrl.connection.invoke("HandleRequest", JSON.stringify(ctrl.request)); - await ctrl.loadData(); - $scope.$apply(); + }, + ], +}); + +modules.component("portalThemeSettings", { + templateUrl: + "/mix-app/views/app-portal/components/portal-theme-settings/view.html", + bindings: { + showLink: "=", + }, + controller: [ + "$rootScope", + "$scope", + "AppSettingsServices", + function ($rootScope, $scope, appSettingsServices) { + var ctrl = this; + this.$onInit = function () { + ctrl.portalThemeSettings = + $rootScope.globalSettings.portalThemeSettings; }; - ctrl.initListMember = function (data) { - data.forEach((member) => { - var index = ctrl.members.findIndex((x) => x.id === member.id); - if (index < 0) { - ctrl.members.splice(0, 0, member); + ctrl.applyThemeSettings = function () { + $rootScope.globalSettings.portalThemeSettings = + ctrl.portalThemeSettings; + }; + ctrl.saveThemeSettings = async function () { + var resp = await appSettingsServices.saveAppSettings( + "PortalThemeSettings", + ctrl.portalThemeSettings + ); + if (resp && resp.success) { + $rootScope.showMessage("success", "success"); + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); } - }); + $scope.$apply(); + } + }; + }, + ], +}); - $scope.$apply(); +modules.component("propertiesValue", { + templateUrl: + "/mix-app/views/app-portal/components/properties-value/view.html", + bindings: { + title: "=", + columns: "=", + properties: "=", + }, + controller: [ + "$rootScope", + "$scope", + function ($rootScope, $scope) { + var ctrl = this; + ctrl.defaultAttr = { + title: "", + name: "", + default: null, + options: [], + priority: 0, + dataType: 7, + isGroupBy: false, + isSelect: false, + isDisplay: true, + width: 3, }; + ctrl.selectedProp = null; + ctrl.mixConfigurations = $rootScope.globalSettings; - ctrl.checkLoginStatus = async function () { - var response = await userServices.getMyProfile(); - ctrl.user.connection.name = response.data.username; - ctrl.user.connection.id = response.data.id; - ctrl.user.connection.connectionId = ctrl.connection.connectionId; - ctrl.user.connection.avatar = response.data.avatar; - ctrl.user.loggedIn = true; - ctrl.join(); + ctrl.$doCheck = function () { + if ( + angular.toJson(ctrl.columns) != angular.toJson(ctrl.trackedColumns) + ) { + ctrl.trackedColumns = angular.copy(ctrl.columns); + ctrl.trackedProperties = angular.copy(ctrl.properties); + ctrl.loadEditors(); + } + }.bind(ctrl); + + ctrl.loadEditors = function () { + ctrl.properties = []; + for (let i = 0; i < ctrl.columns.length; i++) { + var col = ctrl.columns[i]; + var oldObj = + $rootScope.findObjectByKey( + ctrl.trackedProperties, + "name", + col.systemName + ) || {}; + + ctrl.properties.push({ + title: col.displayName, + name: col.systemName, + dataType: col.dataType, + value: oldObj.value || col.defaultValue, + options: col.options, + }); + } + }; + + ctrl.addAttr = function () { + if (ctrl.columns) { + var t = angular.copy(ctrl.defaultAttr); + ctrl.columns.push(t); + } }; }, ], @@ -16214,54 +16044,222 @@ modules.component("templateEditor", { // } // } }; - ctrl.loadTemplates = async function () { - ctrl.request.folderType = ctrl.folderType; - ctrl.request.themeId = ctrl.theme.id; - ctrl.request.pageSize = 1000; - let getTemplates = await service.getList(ctrl.request); - ctrl.templates = getTemplates.data.items; - ctrl.templates.splice(0, 0, { id: null, fileName: "" }); - if (!ctrl.templateId && ctrl.templates.length > 1) { - if (ctrl.defaultTemplate) { - ctrl.template = ctrl.templates.find( - (m) => m.fileName == ctrl.defaultTemplate - ); - ctrl.templateId = ctrl.template.id; - ctrl.selectedTemplate = ctrl.template; + ctrl.loadTemplates = async function () { + ctrl.request.folderType = ctrl.folderType; + ctrl.request.themeId = ctrl.theme.id; + ctrl.request.pageSize = 1000; + let getTemplates = await service.getList(ctrl.request); + ctrl.templates = getTemplates.data.items; + ctrl.templates.splice(0, 0, { id: null, fileName: "" }); + if (!ctrl.templateId && ctrl.templates.length > 1) { + if (ctrl.defaultTemplate) { + ctrl.template = ctrl.templates.find( + (m) => m.fileName == ctrl.defaultTemplate + ); + ctrl.templateId = ctrl.template.id; + ctrl.selectedTemplate = ctrl.template; + } + if (!ctrl.template) { + ctrl.template = ctrl.templates[1]; + ctrl.templateId = ctrl.templates[1].id; + ctrl.selectedTemplate = ctrl.template; + } + } + $scope.$apply(); + }; + ctrl.loadThemes = async () => { + let getThemes = await themeService.getList(ctrl.themeRequest); + ctrl.themes = getThemes.data.items; + ctrl.theme = !ctrl.templateId + ? ctrl.themes[0] + : ctrl.themes.filter((m) => m.id == ctrl.template.mixThemeId)[0]; + }; + ctrl.loadTemplate = async () => { + if (ctrl.templateId) { + var resp = await service.getSingle([ctrl.templateId], { + folderType: $scope.folderType, + }); + if (resp && resp.success) { + ctrl.selectedTemplate = resp.data; + ctrl.template = resp.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + if (resp) { + $rootScope.showErrors(resp.errors); + } + $rootScope.isBusy = false; + $scope.$apply(); + } + } + }; + }, + ], +}); + +modules.component("serviceHubPortal", { + templateUrl: + "/mix-app/views/app-portal/components/service-hub-portal/view.html", + bindings: { + mixDatabaseName: "=", + isSave: "=?", + }, + controller: [ + "$rootScope", + "$scope", + "RestMixDatabaseColumnPortalService", + "RestMixDatabaseDataClientService", + "UserServices", + function ($rootScope, $scope, columnService, service, userServices) { + var ctrl = this; + BaseHub.call(this, ctrl); + ctrl.mixConfigurations = $rootScope.globalSettings; + ctrl.user = { + loggedIn: false, + connection: {}, + }; + ctrl.mixDatabaseData = null; + ctrl.isHide = true; + ctrl.hideContact = true; + ctrl.columns = []; + ctrl.members = []; + ctrl.errors = []; + ctrl.messages = { + items: [], + }; + ctrl.message = { connection: {}, content: "" }; + ctrl.request = { + uid: "", + specificulture: "", + action: "", + objectType: null, + data: {}, + room: "", + isMyself: true, + isSave: false, + }; + ctrl.init = function () { + ctrl.mixDatabaseId = ctrl.mixDatabaseId || 0; + ctrl.request.specificulture = service.lang; + ctrl.request.room = ctrl.mixDatabaseName; + ctrl.request.isSave = ctrl.isSave == "true" || false; + ctrl.startConnection("serviceHub", ctrl.checkLoginStatus); + }; + ctrl.loadData = async function () { + /* + If input is data id => load ctrl.mixDatabaseData from service and handle it independently + Else modify input ctrl.mixDatabaseData + */ + $rootScope.isBusy = true; + var getDefault = await service.initData(ctrl.mixDatabaseName); + if (getDefault.success) { + ctrl.defaultData = getDefault.data; + ctrl.defaultData.data.user_name = ctrl.user.connection.name; + ctrl.defaultData.data.user_id = ctrl.user.connection.id; + ctrl.defaultData.data.user_avatar = ctrl.user.connection.avatar; + ctrl.defaultData.data.data_type = 9; + ctrl.mixDatabaseData = angular.copy(ctrl.defaultData); + $rootScope.isBusy = false; + } + var getFields = await columnService.initData(ctrl.mixDatabaseName); + if (getFields.success) { + ctrl.columns = getFields.data; + } + }; + ctrl.submit = async function () { + if (ctrl.validate()) { + ctrl.request.action = "send_group_message"; + ctrl.request.uid = ctrl.user.connection.id; + ctrl.request.data = ctrl.mixDatabaseData.data; + ctrl.request.connection = ctrl.user.connection; + ctrl.connection.invoke("HandleRequest", JSON.stringify(ctrl.request)); + ctrl.mixDatabaseData = angular.copy(ctrl.defaultData); + } + }; + ctrl.validate = function () { + var isValid = true; + ctrl.errors = []; + angular.forEach(ctrl.columns, function (column) { + if (column.regex) { + var regex = RegExp(column.regex, "g"); + isValid = regex.test(ctrl.mixDatabaseData.data[column.name]); + if (!isValid) { + ctrl.errors.push(`${column.name} is not match Regex`); + } } - if (!ctrl.template) { - ctrl.template = ctrl.templates[1]; - ctrl.templateId = ctrl.templates[1].id; - ctrl.selectedTemplate = ctrl.template; + if (isValid && column.isEncrypt) { + ctrl.mixDatabaseData.data[column.name] = $rootScope.encrypt( + ctrl.mixDatabaseData.data[column.name] + ); } + }); + return isValid; + }; + ctrl.receiveMessage = function (msg) { + switch (msg.responseKey) { + case "NewMember": + ctrl.newMember(msg.data); + // $('.widget-conversation').scrollTop = $('.widget-conversation')[0].scrollHeight; + break; + case "NewMessage": + ctrl.newMessage(msg.data); + break; + case "ConnectSuccess": + ctrl.user.loggedIn = true; + ctrl.initListMember(msg.data); + $scope.$apply(); + break; + case "PreviousMessages": + ctrl.messages = msg.data; + $scope.$apply(); + break; + case "MemberOffline": + ctrl.removeMember(msg.data); + break; + case "Error": + console.error(msg.data); + break; } + }; + ctrl.newMessage = function (msg) { + ctrl.messages.items.push(msg); $scope.$apply(); }; - ctrl.loadThemes = async () => { - let getThemes = await themeService.getList(ctrl.themeRequest); - ctrl.themes = getThemes.data.items; - ctrl.theme = !ctrl.templateId - ? ctrl.themes[0] - : ctrl.themes.filter((m) => m.id == ctrl.template.mixThemeId)[0]; + ctrl.newMember = function (member) { + var m = $rootScope.findObjectByKey(ctrl.members, "id", member.id); + if (!m) { + ctrl.members.push(member); + } + $scope.$apply(); }; - ctrl.loadTemplate = async () => { - if (ctrl.templateId) { - var resp = await service.getSingle([ctrl.templateId], { - folderType: $scope.folderType, - }); - if (resp && resp.success) { - ctrl.selectedTemplate = resp.data; - ctrl.template = resp.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - if (resp) { - $rootScope.showErrors(resp.errors); - } - $rootScope.isBusy = false; - $scope.$apply(); + ctrl.join = async function () { + ctrl.request.action = "join_group"; + ctrl.request.uid = ctrl.user.connection.id; + ctrl.request.data = ctrl.user.connection; + ctrl.message.connection = ctrl.user.connection; + ctrl.connection.invoke("HandleRequest", JSON.stringify(ctrl.request)); + await ctrl.loadData(); + $scope.$apply(); + }; + ctrl.initListMember = function (data) { + data.forEach((member) => { + var index = ctrl.members.findIndex((x) => x.id === member.id); + if (index < 0) { + ctrl.members.splice(0, 0, member); } - } + }); + + $scope.$apply(); + }; + + ctrl.checkLoginStatus = async function () { + var response = await userServices.getMyProfile(); + ctrl.user.connection.name = response.data.username; + ctrl.user.connection.id = response.data.id; + ctrl.user.connection.connectionId = ctrl.connection.connectionId; + ctrl.user.connection.avatar = response.data.avatar; + ctrl.user.loggedIn = true; + ctrl.join(); }; }, ], @@ -16283,6 +16281,67 @@ modules.component("toastHelper", { ], }); +modules.component("urlAlias", { + templateUrl: "/mix-app/views/app-portal/components/url-alias/url-alias.html", + controller: [ + "$rootScope", + "$scope", + "UrlAliasService", + function ($rootScope, $scope, service) { + var ctrl = this; + ctrl.$onInit = function () { + ctrl.updateUrl(); + }; + ctrl.updateUrl = function () { + ctrl.url = + $rootScope.globalSettings.domain + + "/" + + $rootScope.mixConfigurations.lang + + "/" + + ctrl.urlAlias.alias; + }; + ctrl.remove = function () { + if (ctrl.urlAlias.id > 0) { + $rootScope.showConfirm( + ctrl, + "removeConfirmed", + [ctrl.urlAlias.id], + null, + "Remove", + "Deleted data will not able to recover, are you sure you want to delete this item?" + ); + } else { + if (ctrl.removeCallback) { + ctrl.removeCallback({ index: ctrl.index }); + } + } + }; + + ctrl.removeConfirmed = async function (id) { + $rootScope.isBusy = true; + var result = await service.delete(id); + if (result.success) { + if (ctrl.removeCallback) { + ctrl.removeCallback({ index: ctrl.index }); + } + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showMessage("failed"); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + }, + ], + bindings: { + urlAlias: "=", + index: "=", + callback: "&", + removeCallback: "&", + }, +}); + app.factory("ConnectionManager", [ function () { var serviceFactory = {}; @@ -17135,67 +17194,6 @@ app.factory("ViewModel", [ }, ]); -modules.component("urlAlias", { - templateUrl: "/mix-app/views/app-portal/components/url-alias/url-alias.html", - controller: [ - "$rootScope", - "$scope", - "UrlAliasService", - function ($rootScope, $scope, service) { - var ctrl = this; - ctrl.$onInit = function () { - ctrl.updateUrl(); - }; - ctrl.updateUrl = function () { - ctrl.url = - $rootScope.globalSettings.domain + - "/" + - $rootScope.mixConfigurations.lang + - "/" + - ctrl.urlAlias.alias; - }; - ctrl.remove = function () { - if (ctrl.urlAlias.id > 0) { - $rootScope.showConfirm( - ctrl, - "removeConfirmed", - [ctrl.urlAlias.id], - null, - "Remove", - "Deleted data will not able to recover, are you sure you want to delete this item?" - ); - } else { - if (ctrl.removeCallback) { - ctrl.removeCallback({ index: ctrl.index }); - } - } - }; - - ctrl.removeConfirmed = async function (id) { - $rootScope.isBusy = true; - var result = await service.delete(id); - if (result.success) { - if (ctrl.removeCallback) { - ctrl.removeCallback({ index: ctrl.index }); - } - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showMessage("failed"); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - }, - ], - bindings: { - urlAlias: "=", - index: "=", - callback: "&", - removeCallback: "&", - }, -}); - !(function (t) { var e = {}; function i(n) { diff --git a/src/applications/Mixcore/wwwroot/mix-app/js/app-shared.min.js b/src/applications/Mixcore/wwwroot/mix-app/js/app-shared.min.js index 9daf20096..f1adc749d 100644 --- a/src/applications/Mixcore/wwwroot/mix-app/js/app-shared.min.js +++ b/src/applications/Mixcore/wwwroot/mix-app/js/app-shared.min.js @@ -2968,6 +2968,157 @@ appShared.factory("TranslatorService", [ }, ]); +"use strict"; +appShared.factory("MixDbService", [ + "BaseRestService", + function (baseService) { + var serviceFactory = angular.copy(baseService); + serviceFactory.init("mix-db"); + var _initDbName = function (name) { + serviceFactory.init(`mix-db/${name}`); + }; + var _filter = async function (request) { + var url = `${this.prefixUrl}/filter`; + var req = { + serviceBase: this.serviceBase, + method: "POST", + url: url, + data: request, + }; + return await this.getRestApiResult(req); + }; + var _export = async function (request) { + var url = `${this.prefixUrl}/export`; + var req = { + serviceBase: this.serviceBase, + method: "POST", + url: url, + data: request, + }; + return await this.getRestApiResult(req); + }; + var _import = async function (file) { + var url = `${this.prefixUrl}/import`; + var frm = new FormData(); + frm.append("file", file); + return await this.ajaxSubmitForm(frm, url); + }; + var _getSingleByParent = async function (parentType, parentId) { + var url = `${this.prefixUrl}/get-by-parent/${parentType}/${parentId}`; + var req = { + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); + }; + serviceFactory.initDbName = _initDbName; + serviceFactory.filter = _filter; + serviceFactory.export = _export; + serviceFactory.import = _import; + serviceFactory.getSingleByParent = _getSingleByParent; + return serviceFactory; + }, +]); + +"use strict"; +appShared.factory("RestMixDatabasePortalService", [ + "BaseRestService", + function (baseService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("mix-database"); + var _migrate = async function (data) { + var url = `${this.prefixUrl}/migrate/${data.systemName}`; + var req = { + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); + }; + var _backup = async function (data) { + var url = `${this.prefixUrl}/backup/${data.systemName}`; + var req = { + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); + }; + var _restore = async function (data) { + var url = `${this.prefixUrl}/restore/${data.systemName}`; + var req = { + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); + }; + var _updateSchema = async function (data) { + var url = `${this.prefixUrl}/update/${data.systemName}`; + var req = { + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); + }; + var _getByName = async function (name) { + var url = `${this.prefixUrl}/get-by-name/${name}`; + var req = { + method: "GET", + url: url, + }; + return await this.getRestApiResult(req); + }; + serviceFactory.migrate = _migrate; + serviceFactory.backup = _backup; + serviceFactory.restore = _restore; + serviceFactory.updateSchema = _updateSchema; + serviceFactory.getByName = _getByName; + return serviceFactory; + }, +]); + +"use strict"; +appShared.factory("RestMixAssociationPortalService", [ + "BaseRestService", + function (baseService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("mix-db-association"); + + serviceFactory.getAssociation = async ( + parentDbName, + childDbName, + parentId, + childId + ) => { + var url = `${serviceFactory.prefixUrl}/${parentDbName}/${childDbName}/${ + parentId || guidParentId + }/${childId}`; + var req = { + serviceBase: serviceFactory.serviceBase, + apiVersion: serviceFactory.apiVersion, + method: "GET", + url: url, + }; + return await serviceFactory.getRestApiResult(req); + }; + serviceFactory.deleteAssociation = async ( + parentDbName, + childDbName, + parentId, + guidParentId, + childId + ) => { + var url = `${serviceFactory.prefixUrl}/${parentDbName}/${childDbName}/${parentId}/${childId}`; + var req = { + serviceBase: serviceFactory.serviceBase, + apiVersion: serviceFactory.apiVersion, + method: "DELETE", + url: url, + }; + return await serviceFactory.getRestApiResult(req); + }; + return serviceFactory; + }, +]); + "use strict"; appShared.factory("RestMixDatabaseColumnPortalService", [ "BaseRestService", @@ -2989,6 +3140,16 @@ appShared.factory("RestMixDatabaseColumnPortalService", [ }, ]); +"use strict"; +appShared.factory("RestMixDatabaseDataValuePortalService", [ + "BaseRestService", + function (baseService) { + var serviceFactory = Object.create(baseService); + serviceFactory.init("mix-database-data-value"); + return serviceFactory; + }, +]); + "use strict"; appShared.factory("RestMixDatabaseDataClientService", [ "BaseRestService", @@ -3122,162 +3283,11 @@ appShared.factory("RestMixDatabaseDataPortalService", [ ]); "use strict"; -appShared.factory("RestMixAssociationPortalService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-db-association"); - - serviceFactory.getAssociation = async ( - parentDbName, - childDbName, - parentId, - childId - ) => { - var url = `${serviceFactory.prefixUrl}/${parentDbName}/${childDbName}/${ - parentId || guidParentId - }/${childId}`; - var req = { - serviceBase: serviceFactory.serviceBase, - apiVersion: serviceFactory.apiVersion, - method: "GET", - url: url, - }; - return await serviceFactory.getRestApiResult(req); - }; - serviceFactory.deleteAssociation = async ( - parentDbName, - childDbName, - parentId, - guidParentId, - childId - ) => { - var url = `${serviceFactory.prefixUrl}/${parentDbName}/${childDbName}/${parentId}/${childId}`; - var req = { - serviceBase: serviceFactory.serviceBase, - apiVersion: serviceFactory.apiVersion, - method: "DELETE", - url: url, - }; - return await serviceFactory.getRestApiResult(req); - }; - return serviceFactory; - }, -]); - -"use strict"; -appShared.factory("MixDbService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = angular.copy(baseService); - serviceFactory.init("mix-db"); - var _initDbName = function (name) { - serviceFactory.init(`mix-db/${name}`); - }; - var _filter = async function (request) { - var url = `${this.prefixUrl}/filter`; - var req = { - serviceBase: this.serviceBase, - method: "POST", - url: url, - data: request, - }; - return await this.getRestApiResult(req); - }; - var _export = async function (request) { - var url = `${this.prefixUrl}/export`; - var req = { - serviceBase: this.serviceBase, - method: "POST", - url: url, - data: request, - }; - return await this.getRestApiResult(req); - }; - var _import = async function (file) { - var url = `${this.prefixUrl}/import`; - var frm = new FormData(); - frm.append("file", file); - return await this.ajaxSubmitForm(frm, url); - }; - var _getSingleByParent = async function (parentType, parentId) { - var url = `${this.prefixUrl}/get-by-parent/${parentType}/${parentId}`; - var req = { - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); - }; - serviceFactory.initDbName = _initDbName; - serviceFactory.filter = _filter; - serviceFactory.export = _export; - serviceFactory.import = _import; - serviceFactory.getSingleByParent = _getSingleByParent; - return serviceFactory; - }, -]); - -"use strict"; -appShared.factory("RestMixDatabasePortalService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-database"); - var _migrate = async function (data) { - var url = `${this.prefixUrl}/migrate/${data.systemName}`; - var req = { - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); - }; - var _backup = async function (data) { - var url = `${this.prefixUrl}/backup/${data.systemName}`; - var req = { - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); - }; - var _restore = async function (data) { - var url = `${this.prefixUrl}/restore/${data.systemName}`; - var req = { - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); - }; - var _updateSchema = async function (data) { - var url = `${this.prefixUrl}/update/${data.systemName}`; - var req = { - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); - }; - var _getByName = async function (name) { - var url = `${this.prefixUrl}/get-by-name/${name}`; - var req = { - method: "GET", - url: url, - }; - return await this.getRestApiResult(req); - }; - serviceFactory.migrate = _migrate; - serviceFactory.backup = _backup; - serviceFactory.restore = _restore; - serviceFactory.updateSchema = _updateSchema; - serviceFactory.getByName = _getByName; - return serviceFactory; - }, -]); - -"use strict"; -appShared.factory("RestMixDatabaseDataValuePortalService", [ +appShared.factory("RestMixRelationshipPortalService", [ "BaseRestService", function (baseService) { var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-database-data-value"); + serviceFactory.init("mix-database-relationship"); return serviceFactory; }, ]); @@ -3301,16 +3311,6 @@ appShared.factory("RestMvcModuleDataService", [ }, ]); -"use strict"; -appShared.factory("RestMixRelationshipPortalService", [ - "BaseRestService", - function (baseService) { - var serviceFactory = Object.create(baseService); - serviceFactory.init("mix-database-relationship"); - return serviceFactory; - }, -]); - "use strict"; appShared.factory("RestPostService", [ "BaseRestService", @@ -4714,7 +4714,168 @@ appShared.controller("MvcPostController", [ } }; }, -]); +]); + +sharedComponents.component("addressEditor", { + templateUrl: "/mix-app/views/app-shared/components/address-editor/view.html", + bindings: { + province: "=", + provinceClass: "=?", + district: "=", + districtClass: "=?", + ward: "=", + wardClass: "=?", + }, + controller: "AddressEditorController", +}); + +sharedComponents.controller("AddressEditorController", [ + "$rootScope", + "$scope", + "ApiService", + function PortalTemplateController($rootScope, $scope, apiService) { + var ctrl = this; + ctrl.provinceEndpoint = "/rest/shared/json-data/provinces.json/true"; + ctrl.districtEndpoint = "/rest/shared/json-data/districts.json/true"; + ctrl.wardEndpoint = "/rest/shared/json-data/wards.json/true"; + ctrl.$onInit = async function () { + ctrl.provinceClass = + ctrl.provinceClass || "form-select form-control mb-3"; + ctrl.districtClass = + ctrl.districtClass || "form-select form-control mb-3"; + ctrl.wardClass = ctrl.wardClass || "form-select form-control mb-3"; + + ctrl.provinceOptions = await apiService.getApiResult({ + url: ctrl.provinceEndpoint, + }); + $scope.$apply(); + $rootScope.$watch( + () => { + return ctrl.province; + }, + async function (newVal, oldVal) { + if (newVal != oldVal || !ctrl.district) { + if (!ctrl.allDistrictOptions) { + ctrl.allDistrictOptions = await apiService.getApiResult({ + url: ctrl.districtEndpoint, + }); + ctrl.districtOptions = ctrl.allDistrictOptions.filter( + (m) => m["province"] == ctrl.province + ); + $scope.$apply(); + } else { + ctrl.districtOptions = ctrl.allDistrictOptions.filter( + (m) => m["province"] == ctrl.province + ); + } + } + } + ); + $rootScope.$watch( + () => { + return ctrl.district; + }, + async function (newVal, oldVal) { + if (newVal != oldVal) { + if (!ctrl.allWardOptions) { + ctrl.allWardOptions = await apiService.getApiResult({ + url: ctrl.wardEndpoint, + }); + ctrl.wardOptions = ctrl.allWardOptions.filter( + (m) => m["district"] == ctrl.district + ); + $scope.$apply(); + } else { + ctrl.wardOptions = ctrl.allWardOptions.filter( + (m) => m["district"] == ctrl.district + ); + } + } + } + ); + }; + }, +]); + +sharedComponents.component("apiFile", { + templateUrl: "/mix-app/views/app-shared/components/api-file/api-file.html", + controller: [ + "$rootScope", + "$scope", + "Upload", + function PortalTemplateController($rootScope, $scope, uploader) { + var ctrl = this; + ctrl.accept = ctrl.accept || "application/zip"; + ctrl.selectFile = function (files) { + if (files !== undefined && files !== null && files.length > 0) { + const file = files[0]; + ctrl.postedFile = file; + } + }; + + ctrl.uploadFile = function (file) { + // Create FormData object + var files = new FormData(); + var folder = ctrl.folder; + var title = ctrl.title; + var description = ctrl.description; + // Looping over all files and add it to FormData object + files.append(file.name, file); + + // Adding one more key to FormData object + files.append("fileFolder", folder); + files.append("title", title); + files.append("description", description); + $.ajax({ + url: "/" + $rootScope.mixConfigurations.lang + "/media/upload", //'/tts/UploadImage', + type: "POST", + contentType: false, // Not to set any content header + processData: false, // Not to process data + data: files, + success: function (result) { + ctrl.src = result.data.fullPath; + $scope.$apply(); + }, + error: function (err) { + return ""; + }, + }); + }; + ctrl.getBase64 = function (file) { + if (file !== null) { + $rootScope.isBusy = true; + var reader = new FileReader(); + reader.readAsDataURL(file); + reader.onload = function () { + var index = reader.result.indexOf(",") + 1; + var base64 = reader.result.substring(index); + ctrl.postedFile.fileName = file.name.substring( + 0, + file.name.lastIndexOf(".") + ); + ctrl.postedFile.extension = file.name.substring( + file.name.lastIndexOf(".") + ); + ctrl.postedFile.fileStream = reader.result; + $rootScope.isBusy = false; + $scope.$apply(); + }; + reader.onerror = function (error) {}; + } else { + return null; + } + }; + }, + ], + bindings: { + header: "=", + accept: "=", + title: "=", + postedFile: "=", + formName: "=", + isBase64: "=", + }, +}); sharedComponents.component("azureStorage", { templateUrl: "/mix-app/views/app-shared/components/azure-storage/view.html", @@ -4824,87 +4985,6 @@ sharedComponents.component("azureStorage", { ], }); -sharedComponents.component("addressEditor", { - templateUrl: "/mix-app/views/app-shared/components/address-editor/view.html", - bindings: { - province: "=", - provinceClass: "=?", - district: "=", - districtClass: "=?", - ward: "=", - wardClass: "=?", - }, - controller: "AddressEditorController", -}); - -sharedComponents.controller("AddressEditorController", [ - "$rootScope", - "$scope", - "ApiService", - function PortalTemplateController($rootScope, $scope, apiService) { - var ctrl = this; - ctrl.provinceEndpoint = "/rest/shared/json-data/provinces.json/true"; - ctrl.districtEndpoint = "/rest/shared/json-data/districts.json/true"; - ctrl.wardEndpoint = "/rest/shared/json-data/wards.json/true"; - ctrl.$onInit = async function () { - ctrl.provinceClass = - ctrl.provinceClass || "form-select form-control mb-3"; - ctrl.districtClass = - ctrl.districtClass || "form-select form-control mb-3"; - ctrl.wardClass = ctrl.wardClass || "form-select form-control mb-3"; - - ctrl.provinceOptions = await apiService.getApiResult({ - url: ctrl.provinceEndpoint, - }); - $scope.$apply(); - $rootScope.$watch( - () => { - return ctrl.province; - }, - async function (newVal, oldVal) { - if (newVal != oldVal || !ctrl.district) { - if (!ctrl.allDistrictOptions) { - ctrl.allDistrictOptions = await apiService.getApiResult({ - url: ctrl.districtEndpoint, - }); - ctrl.districtOptions = ctrl.allDistrictOptions.filter( - (m) => m["province"] == ctrl.province - ); - $scope.$apply(); - } else { - ctrl.districtOptions = ctrl.allDistrictOptions.filter( - (m) => m["province"] == ctrl.province - ); - } - } - } - ); - $rootScope.$watch( - () => { - return ctrl.district; - }, - async function (newVal, oldVal) { - if (newVal != oldVal) { - if (!ctrl.allWardOptions) { - ctrl.allWardOptions = await apiService.getApiResult({ - url: ctrl.wardEndpoint, - }); - ctrl.wardOptions = ctrl.allWardOptions.filter( - (m) => m["district"] == ctrl.district - ); - $scope.$apply(); - } else { - ctrl.wardOptions = ctrl.allWardOptions.filter( - (m) => m["district"] == ctrl.district - ); - } - } - } - ); - }; - }, -]); - sharedComponents.component("barCode", { templateUrl: "/mix-app/views/app-shared/components/bar-code/view.html", bindings: { @@ -4981,86 +5061,6 @@ sharedComponents.component("barCode", { ], }); -sharedComponents.component("apiFile", { - templateUrl: "/mix-app/views/app-shared/components/api-file/api-file.html", - controller: [ - "$rootScope", - "$scope", - "Upload", - function PortalTemplateController($rootScope, $scope, uploader) { - var ctrl = this; - ctrl.accept = ctrl.accept || "application/zip"; - ctrl.selectFile = function (files) { - if (files !== undefined && files !== null && files.length > 0) { - const file = files[0]; - ctrl.postedFile = file; - } - }; - - ctrl.uploadFile = function (file) { - // Create FormData object - var files = new FormData(); - var folder = ctrl.folder; - var title = ctrl.title; - var description = ctrl.description; - // Looping over all files and add it to FormData object - files.append(file.name, file); - - // Adding one more key to FormData object - files.append("fileFolder", folder); - files.append("title", title); - files.append("description", description); - $.ajax({ - url: "/" + $rootScope.mixConfigurations.lang + "/media/upload", //'/tts/UploadImage', - type: "POST", - contentType: false, // Not to set any content header - processData: false, // Not to process data - data: files, - success: function (result) { - ctrl.src = result.data.fullPath; - $scope.$apply(); - }, - error: function (err) { - return ""; - }, - }); - }; - ctrl.getBase64 = function (file) { - if (file !== null) { - $rootScope.isBusy = true; - var reader = new FileReader(); - reader.readAsDataURL(file); - reader.onload = function () { - var index = reader.result.indexOf(",") + 1; - var base64 = reader.result.substring(index); - ctrl.postedFile.fileName = file.name.substring( - 0, - file.name.lastIndexOf(".") - ); - ctrl.postedFile.extension = file.name.substring( - file.name.lastIndexOf(".") - ); - ctrl.postedFile.fileStream = reader.result; - $rootScope.isBusy = false; - $scope.$apply(); - }; - reader.onerror = function (error) {}; - } else { - return null; - } - }; - }, - ], - bindings: { - header: "=", - accept: "=", - title: "=", - postedFile: "=", - formName: "=", - isBase64: "=", - }, -}); - sharedComponents.component("breadcrumbs", { templateUrl: "/mix-app/views/app-shared/components/breadcrumbs/breadcrumbs.html", @@ -5111,6 +5111,21 @@ sharedComponents.component("cultures", { }, }); +sharedComponents.component("swDataPreview", { + templateUrl: + "/mix-app/views/app-shared/components/data-preview/data-preview.html", + controller: [ + "$rootScope", + function ($rootScope) { + var ctrl = this; + }, + ], + bindings: { + type: "=", + value: "=", + }, +}); + //sharedComponents.controller('ImageController', ); sharedComponents.component("customFile", { templateUrl: @@ -5241,21 +5256,6 @@ sharedComponents.component("customFile", { ], }); -sharedComponents.component("swDataPreview", { - templateUrl: - "/mix-app/views/app-shared/components/data-preview/data-preview.html", - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - }, - ], - bindings: { - type: "=", - value: "=", - }, -}); - sharedComponents.component("mixDataTypeEditor", { templateUrl: "/mix-app/views/app-shared/components/data-type-editor/view.html", @@ -5886,13 +5886,6 @@ appShared.component("mediaNavs", { }, }); -sharedComponents.component("message", { - templateUrl: "/mix-app/views/app-shared/components/message/message.html", - bindings: { - message: "=", - }, -}); - "use strict"; appShared.controller("MediaController", [ "$scope", @@ -6194,13 +6187,10 @@ sharedComponents.component("medias", { bindings: {}, }); -sharedComponents.component("messengerPrivate", { - templateUrl: - "/mix-app/views/app-shared/components/messenger-private/index.html", - controller: "MessengerController", +sharedComponents.component("message", { + templateUrl: "/mix-app/views/app-shared/components/message/message.html", bindings: { message: "=", - connectionId: "=", }, }); @@ -6376,6 +6366,16 @@ sharedComponents.component("messenger", { }, }); +sharedComponents.component("messengerPrivate", { + templateUrl: + "/mix-app/views/app-shared/components/messenger-private/index.html", + controller: "MessengerController", + bindings: { + message: "=", + connectionId: "=", + }, +}); + sharedComponents.component("mixColumnEditor", { templateUrl: "/mix-app/views/app-shared/components/mix-column-editor/view.html", @@ -7040,39 +7040,15 @@ appShared.controller("MixDatabaseDataClientController", [ var response = await service.saveList($scope.others); if (response.success) { $scope.getList(); - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - }, -]); - -sharedComponents.component("mixDatabaseDataValuePreview", { - templateUrl: - "/mix-app/views/app-shared/components/mix-database-data-value-preview/view.html", - controller: [ - "$rootScope", - function ($rootScope) { - var ctrl = this; - ctrl.$onInit = function () { - if (ctrl.data.column && ctrl.data.column.isEncrypt) { - var encryptedData = { - key: ctrl.data.encryptKey, - data: ctrl.data.encryptValue, - }; - ctrl.data.stringValue = $rootScope.decrypt(encryptedData); - } - }; - }, - ], - bindings: { - data: "=", - width: "=", + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; }, -}); +]); sharedComponents.component("mixDatabaseFormWeb", { templateUrl: @@ -7203,6 +7179,30 @@ sharedComponents.component("mixDatabaseFormWeb", { ], }); +sharedComponents.component("mixDatabaseDataValuePreview", { + templateUrl: + "/mix-app/views/app-shared/components/mix-database-data-value-preview/view.html", + controller: [ + "$rootScope", + function ($rootScope) { + var ctrl = this; + ctrl.$onInit = function () { + if (ctrl.data.column && ctrl.data.column.isEncrypt) { + var encryptedData = { + key: ctrl.data.encryptKey, + data: ctrl.data.encryptValue, + }; + ctrl.data.stringValue = $rootScope.decrypt(encryptedData); + } + }; + }, + ], + bindings: { + data: "=", + width: "=", + }, +}); + sharedComponents.component("mixDateEditor", { templateUrl: "/mix-app/views/app-shared/components/mix-date-editor/view.html", bindings: { @@ -8391,48 +8391,6 @@ sharedComponents.component("moduleFormEditor", { ], }); -sharedComponents.component("modulePreview", { - templateUrl: "/mix-app/views/app-shared/components/module-preview/view.html", - controller: [ - "$scope", - "$rootScope", - "ModuleDataRestService", - function ($scope, $rootScope, moduleDataService) { - var ctrl = this; - $rootScope.isBusy = false; - ctrl.previousContentId = undefined; - - this.$onInit = () => { - ctrl.previousContentId = angular.copy(ctrl.contentId); - }; - - this.$doCheck = () => { - if (ctrl.contentId !== ctrl.previousContentId) { - ctrl.loadModuleData(); - ctrl.previousContentId = ctrl.contentId; - } - }; - - ctrl.loadModuleData = async function () { - $rootScope.isBusy = true; - var response = await moduleDataService.getSingle([ctrl.contentId]); - if (response.success) { - ctrl.data = response.data; - $rootScope.isBusy = false; - $scope.$apply(); - } else { - $rootScope.showErrors(response.errors); - $rootScope.isBusy = false; - $scope.$apply(); - } - }; - }, - ], - bindings: { - contentId: "=", - }, -}); - sharedComponents.component("onePay", { templateUrl: "/mix-app/views/app-shared/components/one-pay/view.html", bindings: { @@ -8511,6 +8469,48 @@ sharedComponents.controller("OnePayShoppingCartController", [ }, ]); +sharedComponents.component("modulePreview", { + templateUrl: "/mix-app/views/app-shared/components/module-preview/view.html", + controller: [ + "$scope", + "$rootScope", + "ModuleDataRestService", + function ($scope, $rootScope, moduleDataService) { + var ctrl = this; + $rootScope.isBusy = false; + ctrl.previousContentId = undefined; + + this.$onInit = () => { + ctrl.previousContentId = angular.copy(ctrl.contentId); + }; + + this.$doCheck = () => { + if (ctrl.contentId !== ctrl.previousContentId) { + ctrl.loadModuleData(); + ctrl.previousContentId = ctrl.contentId; + } + }; + + ctrl.loadModuleData = async function () { + $rootScope.isBusy = true; + var response = await moduleDataService.getSingle([ctrl.contentId]); + if (response.success) { + ctrl.data = response.data; + $rootScope.isBusy = false; + $scope.$apply(); + } else { + $rootScope.showErrors(response.errors); + $rootScope.isBusy = false; + $scope.$apply(); + } + }; + }, + ], + bindings: { + contentId: "=", + }, +}); + sharedComponents.component("mixPaging", { templateUrl: "/mix-app/views/app-shared/components/paging/paging.html", controller: [ @@ -9358,20 +9358,6 @@ sharedComponents.component("snowy", { bindings: {}, }); -sharedComponents.component("statuses", { - templateUrl: "/mix-app/views/app-shared/components/statuses/statuses.html", - controller: [ - "$rootScope", - "ngAppSettings", - function ($rootScope, ngAppSettings) { - this.contentStatuses = ngAppSettings.contentStatuses; - }, - ], - bindings: { - status: "=", - }, -}); - sharedComponents.component("starRating", { templateUrl: "/mix-app/views/app-shared/components/star-rating/star-rating.html", @@ -9416,49 +9402,18 @@ appShared.controller("StarRatingController", [ }, ]); -"use trick"; -sharedComponents.directive("pane", function () { - return { - require: "^tabs", - restrict: "E", - transclude: true, - scope: { header: "@", id: "@", icon: "@" }, - link: function (scope, element, attrs, tabsController) { - tabsController.addPane(scope); - }, - template: - '
' + - "
", - replace: true, - }; -}); - -sharedComponents.directive("tabs", function () { - return { - restrict: "E", - transclude: true, - scope: { - selectCallback: "&", - }, - controller: function ($scope, $element) { - var panes = ($scope.panes = []); - - $scope.select = function (pane) { - angular.forEach(panes, function (pane) { - pane.selected = false; - }); - pane.selected = true; - this.selectCallback({ pane: pane }); - }; - - this.addPane = function (pane) { - if (panes.length === 0) $scope.select(pane); - panes.push(pane); - }; +sharedComponents.component("statuses", { + templateUrl: "/mix-app/views/app-shared/components/statuses/statuses.html", + controller: [ + "$rootScope", + "ngAppSettings", + function ($rootScope, ngAppSettings) { + this.contentStatuses = ngAppSettings.contentStatuses; }, - templateUrl: "/mix-app/views/app-shared/components/tabs/tabs.html", - replace: true, - }; + ], + bindings: { + status: "=", + }, }); sharedComponents.component("mixStore", { @@ -9521,8 +9476,7 @@ sharedComponents.component("mixStore", { await ctrl.getThemes(ctrl.themeRequest); $scope.$apply(); }; - ctrl.receiveMessage = function (resp) { - let msg = JSON.parse(resp); + ctrl.receiveMessage = function (msg) { switch (msg.action) { case "Downloading": var index = ctrl.data.items.findIndex( @@ -9645,6 +9599,51 @@ sharedComponents.component("mixStore", { ], }); +"use trick"; +sharedComponents.directive("pane", function () { + return { + require: "^tabs", + restrict: "E", + transclude: true, + scope: { header: "@", id: "@", icon: "@" }, + link: function (scope, element, attrs, tabsController) { + tabsController.addPane(scope); + }, + template: + '
' + + "
", + replace: true, + }; +}); + +sharedComponents.directive("tabs", function () { + return { + restrict: "E", + transclude: true, + scope: { + selectCallback: "&", + }, + controller: function ($scope, $element) { + var panes = ($scope.panes = []); + + $scope.select = function (pane) { + angular.forEach(panes, function (pane) { + pane.selected = false; + }); + pane.selected = true; + this.selectCallback({ pane: pane }); + }; + + this.addPane = function (pane) { + if (panes.length === 0) $scope.select(pane); + panes.push(pane); + }; + }, + templateUrl: "/mix-app/views/app-shared/components/tabs/tabs.html", + replace: true, + }; +}); + "use trick"; sharedComponents.directive("paneH", function () { return { @@ -9691,19 +9690,6 @@ sharedComponents.directive("tabsH", function () { }; }); -sharedComponents.component("tags", { - templateUrl: "/mix-app/views/app-shared/components/tags/tags.html", - controller: [ - "$scope", - function ($scope) { - var ctrl = this; - }, - ], - bindings: { - input: "=", - }, -}); - "use trick"; sharedComponents.directive("paneV", function () { return { @@ -9749,6 +9735,19 @@ sharedComponents.directive("tabsV", function () { }; }); +sharedComponents.component("tags", { + templateUrl: "/mix-app/views/app-shared/components/tags/tags.html", + controller: [ + "$scope", + function ($scope) { + var ctrl = this; + }, + ], + bindings: { + input: "=", + }, +}); + sharedComponents.component("tagsView", { templateUrl: "/mix-app/views/app-shared/components/tags-view/view.html", controller: [ @@ -15655,9 +15654,9 @@ angular.module("bw.paging", []).directive("paging", function () { ]); })(); -var t,e;t=self,e=()=>(()=>{var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),t.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"t",{value:!0})};var e,s={};t.r(s),t.d(s,{AbortError:()=>r,DefaultHttpClient:()=>H,HttpClient:()=>d,HttpError:()=>i,HttpResponse:()=>u,HttpTransportType:()=>W,HubConnection:()=>N,HubConnectionBuilder:()=>Y,HubConnectionState:()=>A,JsonHubProtocol:()=>K,LogLevel:()=>e,MessageType:()=>R,NullLogger:()=>p,Subject:()=>U,TimeoutError:()=>n,TransferFormat:()=>O,VERSION:()=>f});class i extends Error{constructor(t,e){const s=new.target.prototype;super(`${t}: Status code '${e}'`),this.statusCode=e,this.__proto__=s}}class n extends Error{constructor(t="A timeout occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class r extends Error{constructor(t="An abort occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class o extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="UnsupportedTransportError",this.__proto__=s}}class h extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="DisabledTransportError",this.__proto__=s}}class c extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="FailedToStartTransportError",this.__proto__=s}}class a extends Error{constructor(t){const e=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=e}}class l extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.innerErrors=e,this.__proto__=s}}class u{constructor(t,e,s){this.statusCode=t,this.statusText=e,this.content=s}}class d{get(t,e){return this.send({...e,method:"GET",url:t})}post(t,e){return this.send({...e,method:"POST",url:t})}delete(t,e){return this.send({...e,method:"DELETE",url:t})}getCookieString(t){return""}}!function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"}(e||(e={}));class p{constructor(){}log(t,e){}}p.instance=new p;const f="7.0.5";class w{static isRequired(t,e){if(null==t)throw new Error(`The '${e}' argument is required.`)}static isNotEmpty(t,e){if(!t||t.match(/^\s*$/))throw new Error(`The '${e}' argument should not be empty.`)}static isIn(t,e,s){if(!(t in e))throw new Error(`Unknown ${s} value: ${t}.`)}}class g{static get isBrowser(){return"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isReactNative(){return"object"==typeof window&&void 0===window.document}static get isNode(){return!this.isBrowser&&!this.isWebWorker&&!this.isReactNative}}function m(t,e){let s="";return y(t)?(s=`Binary data of length ${t.byteLength}`,e&&(s+=`. Content: '${function(t){const e=new Uint8Array(t);let s="";return e.forEach((t=>{s+=`0x${t<16?"0":""}${t.toString(16)} `})),s.substr(0,s.length-1)}(t)}'`)):"string"==typeof t&&(s=`String data of length ${t.length}`,e&&(s+=`. Content: '${t}'`)),s}function y(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}async function b(t,s,i,n,r,o){const h={},[c,a]=E();h[c]=a,t.log(e.Trace,`(${s} transport) sending data. ${m(r,o.logMessageContent)}.`);const l=y(r)?"arraybuffer":"text",u=await i.post(n,{content:r,headers:{...h,...o.headers},responseType:l,timeout:o.timeout,withCredentials:o.withCredentials});t.log(e.Trace,`(${s} transport) request complete. Response status: ${u.statusCode}.`)}class v{constructor(t,e){this.i=t,this.h=e}dispose(){const t=this.i.observers.indexOf(this.h);t>-1&&this.i.observers.splice(t,1),0===this.i.observers.length&&this.i.cancelCallback&&this.i.cancelCallback().catch((t=>{}))}}class ${constructor(t){this.l=t,this.out=console}log(t,s){if(t>=this.l){const i=`[${(new Date).toISOString()}] ${e[t]}: ${s}`;switch(t){case e.Critical:case e.Error:this.out.error(i);break;case e.Warning:this.out.warn(i);break;case e.Information:this.out.info(i);break;default:this.out.log(i)}}}}function E(){let t="X-SignalR-User-Agent";return g.isNode&&(t="User-Agent"),[t,C(f,S(),g.isNode?"NodeJS":"Browser",k())]}function C(t,e,s,i){let n="Microsoft SignalR/";const r=t.split(".");return n+=`${r[0]}.${r[1]}`,n+=` (${t}; `,n+=e&&""!==e?`${e}; `:"Unknown OS; ",n+=`${s}`,n+=i?`; ${i}`:"; Unknown Runtime Version",n+=")",n}function S(){if(!g.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function k(){if(g.isNode)return process.versions.node}function P(t){return t.stack?t.stack:t.message?t.message:`${t}`}class T extends d{constructor(e){if(super(),this.u=e,"undefined"==typeof fetch){const t=require;this.p=new(t("tough-cookie").CookieJar),this.m=t("node-fetch"),this.m=t("fetch-cookie")(this.m,this.p)}else this.m=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t.g)return t.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const t=require;this.v=t("abort-controller")}else this.v=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new r;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const s=new this.v;let o;t.abortSignal&&(t.abortSignal.onabort=()=>{s.abort(),o=new r});let h,c=null;if(t.timeout){const i=t.timeout;c=setTimeout((()=>{s.abort(),this.u.log(e.Warning,"Timeout from HTTP request."),o=new n}),i)}""===t.content&&(t.content=void 0),t.content&&(t.headers=t.headers||{},y(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");try{h=await this.m(t.url,{body:t.content,cache:"no-cache",credentials:!0===t.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:s.signal})}catch(t){if(o)throw o;throw this.u.log(e.Warning,`Error from HTTP request. ${t}.`),t}finally{c&&clearTimeout(c),t.abortSignal&&(t.abortSignal.onabort=null)}if(!h.ok){const t=await I(h,"text");throw new i(t||h.statusText,h.status)}const a=I(h,t.responseType),l=await a;return new u(h.status,h.statusText,l)}getCookieString(t){let e="";return g.isNode&&this.p&&this.p.getCookies(t,((t,s)=>e=s.join("; "))),e}}function I(t,e){let s;switch(e){case"arraybuffer":s=t.arrayBuffer();break;case"text":default:s=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`)}return s}class _ extends d{constructor(t){super(),this.u=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?new Promise(((s,o)=>{const h=new XMLHttpRequest;h.open(t.method,t.url,!0),h.withCredentials=void 0===t.withCredentials||t.withCredentials,h.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===t.content&&(t.content=void 0),t.content&&(y(t.content)?h.setRequestHeader("Content-Type","application/octet-stream"):h.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const c=t.headers;c&&Object.keys(c).forEach((t=>{h.setRequestHeader(t,c[t])})),t.responseType&&(h.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{h.abort(),o(new r)}),t.timeout&&(h.timeout=t.timeout),h.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),h.status>=200&&h.status<300?s(new u(h.status,h.statusText,h.response||h.responseText)):o(new i(h.response||h.responseText||h.statusText,h.status))},h.onerror=()=>{this.u.log(e.Warning,`Error from HTTP request. ${h.status}: ${h.statusText}.`),o(new i(h.statusText,h.status))},h.ontimeout=()=>{this.u.log(e.Warning,"Timeout from HTTP request."),o(new n)},h.send(t.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class H extends d{constructor(t){if(super(),"undefined"!=typeof fetch||g.isNode)this.$=new T(t);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this.$=new _(t)}}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?this.$.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this.$.getCookieString(t)}}class D{static write(t){return`${t}${D.RecordSeparator}`}static parse(t){if(t[t.length-1]!==D.RecordSeparator)throw new Error("Message is incomplete.");const e=t.split(D.RecordSeparator);return e.pop(),e}}D.RecordSeparatorCode=30,D.RecordSeparator=String.fromCharCode(D.RecordSeparatorCode);class x{writeHandshakeRequest(t){return D.write(JSON.stringify(t))}parseHandshakeResponse(t){let e,s;if(y(t)){const i=new Uint8Array(t),n=i.indexOf(D.RecordSeparatorCode);if(-1===n)throw new Error("Message is incomplete.");const r=n+1;e=String.fromCharCode.apply(null,Array.prototype.slice.call(i.slice(0,r))),s=i.byteLength>r?i.slice(r).buffer:null}else{const i=t,n=i.indexOf(D.RecordSeparator);if(-1===n)throw new Error("Message is incomplete.");const r=n+1;e=i.substring(0,r),s=i.length>r?i.substring(r):null}const i=D.parse(e),n=JSON.parse(i[0]);if(n.type)throw new Error("Expected a handshake response from the server.");return[s,n]}}var R,A;!function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close"}(R||(R={}));class U{constructor(){this.observers=[]}next(t){for(const e of this.observers)e.next(t)}error(t){for(const e of this.observers)e.error&&e.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new v(this,t)}}!function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"}(A||(A={}));class N{constructor(t,s,i,n){this.C=0,this.S=()=>{this.u.log(e.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},w.isRequired(t,"connection"),w.isRequired(s,"logger"),w.isRequired(i,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this.u=s,this.k=i,this.connection=t,this.P=n,this.T=new x,this.connection.onreceive=t=>this.I(t),this.connection.onclose=t=>this._(t),this.H={},this.D={},this.R=[],this.A=[],this.U=[],this.N=0,this.L=!1,this.M=A.Disconnected,this.j=!1,this.q=this.k.writeMessage({type:R.Ping})}static create(t,e,s,i){return new N(t,e,s,i)}get state(){return this.M}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this.M!==A.Disconnected&&this.M!==A.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this.W=this.O(),this.W}async O(){if(this.M!==A.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this.M=A.Connecting,this.u.log(e.Debug,"Starting HubConnection.");try{await this.F(),g.isBrowser&&window.document.addEventListener("freeze",this.S),this.M=A.Connected,this.j=!0,this.u.log(e.Debug,"HubConnection connected successfully.")}catch(t){return this.M=A.Disconnected,this.u.log(e.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async F(){this.B=void 0,this.L=!1;const t=new Promise(((t,e)=>{this.X=t,this.J=e}));await this.connection.start(this.k.transferFormat);try{const s={protocol:this.k.name,version:this.k.version};if(this.u.log(e.Debug,"Sending handshake request."),await this.V(this.T.writeHandshakeRequest(s)),this.u.log(e.Information,`Using HubProtocol '${this.k.name}'.`),this.G(),this.K(),this.Y(),await t,this.B)throw this.B;this.connection.features.inherentKeepAlive||await this.V(this.q)}catch(t){throw this.u.log(e.Debug,`Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`),this.G(),this.Z(),await this.connection.stop(t),t}}async stop(){const t=this.W;this.tt=this.et(),await this.tt;try{await t}catch(t){}}et(t){return this.M===A.Disconnected?(this.u.log(e.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve()):this.M===A.Disconnecting?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.tt):(this.M=A.Disconnecting,this.u.log(e.Debug,"Stopping HubConnection."),this.st?(this.u.log(e.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this.st),this.st=void 0,this.it(),Promise.resolve()):(this.G(),this.Z(),this.B=t||new r("The connection was stopped before the hub handshake could complete."),this.connection.stop(t)))}stream(t,...e){const[s,i]=this.nt(e),n=this.rt(t,e,i);let r;const o=new U;return o.cancelCallback=()=>{const t=this.ot(n.invocationId);return delete this.H[n.invocationId],r.then((()=>this.ht(t)))},this.H[n.invocationId]=(t,e)=>{e?o.error(e):t&&(t.type===R.Completion?t.error?o.error(new Error(t.error)):o.complete():o.next(t.item))},r=this.ht(n).catch((t=>{o.error(t),delete this.H[n.invocationId]})),this.ct(s,r),o}V(t){return this.Y(),this.connection.send(t)}ht(t){return this.V(this.k.writeMessage(t))}send(t,...e){const[s,i]=this.nt(e),n=this.ht(this.lt(t,e,!0,i));return this.ct(s,n),n}invoke(t,...e){const[s,i]=this.nt(e),n=this.lt(t,e,!1,i);return new Promise(((t,e)=>{this.H[n.invocationId]=(s,i)=>{i?e(i):s&&(s.type===R.Completion?s.error?e(new Error(s.error)):t(s.result):e(new Error(`Unexpected message type: ${s.type}`)))};const i=this.ht(n).catch((t=>{e(t),delete this.H[n.invocationId]}));this.ct(s,i)}))}on(t,e){t&&e&&(t=t.toLowerCase(),this.D[t]||(this.D[t]=[]),-1===this.D[t].indexOf(e)&&this.D[t].push(e))}off(t,e){if(!t)return;t=t.toLowerCase();const s=this.D[t];if(s)if(e){const i=s.indexOf(e);-1!==i&&(s.splice(i,1),0===s.length&&delete this.D[t])}else delete this.D[t]}onclose(t){t&&this.R.push(t)}onreconnecting(t){t&&this.A.push(t)}onreconnected(t){t&&this.U.push(t)}I(t){if(this.G(),this.L||(t=this.ut(t),this.L=!0),t){const s=this.k.parseMessages(t,this.u);for(const t of s)switch(t.type){case R.Invocation:this.dt(t);break;case R.StreamItem:case R.Completion:{const s=this.H[t.invocationId];if(s){t.type===R.Completion&&delete this.H[t.invocationId];try{s(t)}catch(t){this.u.log(e.Error,`Stream callback threw error: ${P(t)}`)}}break}case R.Ping:break;case R.Close:{this.u.log(e.Information,"Close message received from server.");const s=t.error?new Error("Server returned an error on close: "+t.error):void 0;!0===t.allowReconnect?this.connection.stop(s):this.tt=this.et(s);break}default:this.u.log(e.Warning,`Invalid message type: ${t.type}.`)}}this.K()}ut(t){let s,i;try{[i,s]=this.T.parseHandshakeResponse(t)}catch(t){const s="Error parsing handshake response: "+t;this.u.log(e.Error,s);const i=new Error(s);throw this.J(i),i}if(s.error){const t="Server returned handshake error: "+s.error;this.u.log(e.Error,t);const i=new Error(t);throw this.J(i),i}return this.u.log(e.Debug,"Server handshake complete."),this.X(),i}Y(){this.connection.features.inherentKeepAlive||(this.C=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this.Z())}K(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this.ft=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this.wt))){let t=this.C-(new Date).getTime();t<0&&(t=0),this.wt=setTimeout((async()=>{if(this.M===A.Connected)try{await this.V(this.q)}catch{this.Z()}}),t)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async dt(t){const s=t.target.toLowerCase(),i=this.D[s];if(!i)return this.u.log(e.Warning,`No client method with the name '${s}' found.`),void(t.invocationId&&(this.u.log(e.Warning,`No result given for '${s}' method and invocation ID '${t.invocationId}'.`),await this.ht(this.gt(t.invocationId,"Client didn't provide a result.",null))));const n=i.slice(),r=!!t.invocationId;let o,h,c;for(const i of n)try{const n=o;o=await i.apply(this,t.arguments),r&&o&&n&&(this.u.log(e.Error,`Multiple results provided for '${s}'. Sending error to server.`),c=this.gt(t.invocationId,"Client provided multiple results.",null)),h=void 0}catch(t){h=t,this.u.log(e.Error,`A callback for the method '${s}' threw error '${t}'.`)}c?await this.ht(c):r?(h?c=this.gt(t.invocationId,`${h}`,null):void 0!==o?c=this.gt(t.invocationId,null,o):(this.u.log(e.Warning,`No result given for '${s}' method and invocation ID '${t.invocationId}'.`),c=this.gt(t.invocationId,"Client didn't provide a result.",null)),await this.ht(c)):o&&this.u.log(e.Error,`Result given for '${s}' method but server is not expecting a result.`)}_(t){this.u.log(e.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this.M}.`),this.B=this.B||t||new r("The underlying connection was closed before the hub handshake could complete."),this.X&&this.X(),this.yt(t||new Error("Invocation canceled due to the underlying connection being closed.")),this.G(),this.Z(),this.M===A.Disconnecting?this.it(t):this.M===A.Connected&&this.P?this.bt(t):this.M===A.Connected&&this.it(t)}it(t){if(this.j){this.M=A.Disconnected,this.j=!1,g.isBrowser&&window.document.removeEventListener("freeze",this.S);try{this.R.forEach((e=>e.apply(this,[t])))}catch(s){this.u.log(e.Error,`An onclose callback called with error '${t}' threw error '${s}'.`)}}}async bt(t){const s=Date.now();let i=0,n=void 0!==t?t:new Error("Attempting to reconnect due to a unknown error."),r=this.vt(i++,0,n);if(null===r)return this.u.log(e.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this.it(t);if(this.M=A.Reconnecting,t?this.u.log(e.Information,`Connection reconnecting because of error '${t}'.`):this.u.log(e.Information,"Connection reconnecting."),0!==this.A.length){try{this.A.forEach((e=>e.apply(this,[t])))}catch(s){this.u.log(e.Error,`An onreconnecting callback called with error '${t}' threw error '${s}'.`)}if(this.M!==A.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this.u.log(e.Information,`Reconnect attempt number ${i} will start in ${r} ms.`),await new Promise((t=>{this.st=setTimeout(t,r)})),this.st=void 0,this.M!==A.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this.F(),this.M=A.Connected,this.u.log(e.Information,"HubConnection reconnected successfully."),0!==this.U.length)try{this.U.forEach((t=>t.apply(this,[this.connection.connectionId])))}catch(t){this.u.log(e.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`)}return}catch(t){if(this.u.log(e.Information,`Reconnect attempt failed because of error '${t}'.`),this.M!==A.Reconnecting)return this.u.log(e.Debug,`Connection moved to the '${this.M}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this.M===A.Disconnecting&&this.it());n=t instanceof Error?t:new Error(t.toString()),r=this.vt(i++,Date.now()-s,n)}}this.u.log(e.Information,`Reconnect retries have been exhausted after ${Date.now()-s} ms and ${i} failed attempts. Connection disconnecting.`),this.it()}vt(t,s,i){try{return this.P.nextRetryDelayInMilliseconds({elapsedMilliseconds:s,previousRetryCount:t,retryReason:i})}catch(i){return this.u.log(e.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${s}) threw error '${i}'.`),null}}yt(t){const s=this.H;this.H={},Object.keys(s).forEach((i=>{const n=s[i];try{n(null,t)}catch(s){this.u.log(e.Error,`Stream 'error' callback called with '${t}' threw error: ${P(s)}`)}}))}Z(){this.wt&&(clearTimeout(this.wt),this.wt=void 0)}G(){this.ft&&clearTimeout(this.ft)}lt(t,e,s,i){if(s)return 0!==i.length?{arguments:e,streamIds:i,target:t,type:R.Invocation}:{arguments:e,target:t,type:R.Invocation};{const s=this.N;return this.N++,0!==i.length?{arguments:e,invocationId:s.toString(),streamIds:i,target:t,type:R.Invocation}:{arguments:e,invocationId:s.toString(),target:t,type:R.Invocation}}}ct(t,e){if(0!==t.length){e||(e=Promise.resolve());for(const s in t)t[s].subscribe({complete:()=>{e=e.then((()=>this.ht(this.gt(s))))},error:t=>{let i;i=t instanceof Error?t.message:t&&t.toString?t.toString():"Unknown error",e=e.then((()=>this.ht(this.gt(s,i))))},next:t=>{e=e.then((()=>this.ht(this.$t(s,t))))}})}}nt(t){const e=[],s=[];for(let i=0;i0)&&(e=!1,this.Pt=await this.kt()),this.Tt(t);const s=await this.St.send(t);return e&&401===s.statusCode&&this.kt?(this.Pt=await this.kt(),this.Tt(t),await this.St.send(t)):s}Tt(t){t.headers||(t.headers={}),this.Pt?t.headers[j.Authorization]=`Bearer ${this.Pt}`:this.kt&&t.headers[j.Authorization]&&delete t.headers[j.Authorization]}getCookieString(t){return this.St.getCookieString(t)}}var W,O;!function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"}(W||(W={})),function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"}(O||(O={}));class F{constructor(){this.It=!1,this.onabort=null}abort(){this.It||(this.It=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this.It}}class B{constructor(t,e,s){this.$=t,this.u=e,this._t=new F,this.Ht=s,this.Dt=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._t.aborted}async connect(t,s){if(w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.xt=t,this.u.log(e.Trace,"(LongPolling transport) Connecting."),s===O.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,r]=E(),o={[n]:r,...this.Ht.headers},h={abortSignal:this._t.signal,headers:o,timeout:1e5,withCredentials:this.Ht.withCredentials};s===O.Binary&&(h.responseType="arraybuffer");const c=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${c}.`);const a=await this.$.get(c,h);200!==a.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this.Rt=new i(a.statusText||"",a.statusCode),this.Dt=!1):this.Dt=!0,this.At=this.Ut(this.xt,h)}async Ut(t,s){try{for(;this.Dt;)try{const n=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this.$.get(n,s);204===r.statusCode?(this.u.log(e.Information,"(LongPolling transport) Poll terminated by server."),this.Dt=!1):200!==r.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this.Rt=new i(r.statusText||"",r.statusCode),this.Dt=!1):r.content?(this.u.log(e.Trace,`(LongPolling transport) data received. ${m(r.content,this.Ht.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(t){this.Dt?t instanceof n?this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this.Rt=t,this.Dt=!1):this.u.log(e.Trace,`(LongPolling transport) Poll errored after shutdown: ${t.message}`)}}finally{this.u.log(e.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this.Nt()}}async send(t){return this.Dt?b(this.u,"LongPolling",this.$,this.xt,t,this.Ht):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this.u.log(e.Trace,"(LongPolling transport) Stopping polling."),this.Dt=!1,this._t.abort();try{await this.At,this.u.log(e.Trace,`(LongPolling transport) sending DELETE request to ${this.xt}.`);const t={},[s,i]=E();t[s]=i;const n={headers:{...t,...this.Ht.headers},timeout:this.Ht.timeout,withCredentials:this.Ht.withCredentials};await this.$.delete(this.xt,n),this.u.log(e.Trace,"(LongPolling transport) DELETE request sent.")}finally{this.u.log(e.Trace,"(LongPolling transport) Stop finished."),this.Nt()}}Nt(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this.Rt&&(t+=" Error: "+this.Rt),this.u.log(e.Trace,t),this.onclose(this.Rt)}}}class X{constructor(t,e,s,i){this.$=t,this.Pt=e,this.u=s,this.Ht=i,this.onreceive=null,this.onclose=null}async connect(t,s){return w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.u.log(e.Trace,"(SSE transport) Connecting."),this.xt=t,this.Pt&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this.Pt)}`),new Promise(((i,n)=>{let r,o=!1;if(s===O.Text){if(g.isBrowser||g.isWebWorker)r=new this.Ht.EventSource(t,{withCredentials:this.Ht.withCredentials});else{const e=this.$.getCookieString(t),s={};s.Cookie=e;const[i,n]=E();s[i]=n,r=new this.Ht.EventSource(t,{withCredentials:this.Ht.withCredentials,headers:{...s,...this.Ht.headers}})}try{r.onmessage=t=>{if(this.onreceive)try{this.u.log(e.Trace,`(SSE transport) data received. ${m(t.data,this.Ht.logMessageContent)}.`),this.onreceive(t.data)}catch(t){return void this.Lt(t)}},r.onerror=t=>{o?this.Lt():n(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this.u.log(e.Information,`SSE connected to ${this.xt}`),this.Mt=r,o=!0,i()}}catch(t){return void n(t)}}else n(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(t){return this.Mt?b(this.u,"SSE",this.$,this.xt,t,this.Ht):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this.Lt(),Promise.resolve()}Lt(t){this.Mt&&(this.Mt.close(),this.Mt=void 0,this.onclose&&this.onclose(t))}}class J{constructor(t,e,s,i,n,r){this.u=s,this.kt=e,this.jt=i,this.qt=n,this.$=t,this.onreceive=null,this.onclose=null,this.Wt=r}async connect(t,s){let i;return w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.u.log(e.Trace,"(WebSockets transport) Connecting."),this.kt&&(i=await this.kt()),new Promise(((n,r)=>{let o;t=t.replace(/^http/,"ws");const h=this.$.getCookieString(t);let c=!1;if(g.isNode||g.isReactNative){const e={},[s,n]=E();e[s]=n,i&&(e[j.Authorization]=`Bearer ${i}`),h&&(e[j.Cookie]=h),o=new this.qt(t,void 0,{headers:{...e,...this.Wt}})}else i&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(i)}`);o||(o=new this.qt(t)),s===O.Binary&&(o.binaryType="arraybuffer"),o.onopen=s=>{this.u.log(e.Information,`WebSocket connected to ${t}.`),this.Ot=o,c=!0,n()},o.onerror=t=>{let s=null;s="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"There was an error with the transport",this.u.log(e.Information,`(WebSockets transport) ${s}.`)},o.onmessage=t=>{if(this.u.log(e.Trace,`(WebSockets transport) data received. ${m(t.data,this.jt)}.`),this.onreceive)try{this.onreceive(t.data)}catch(t){return void this.Lt(t)}},o.onclose=t=>{if(c)this.Lt(t);else{let e=null;e="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(e))}}}))}send(t){return this.Ot&&this.Ot.readyState===this.qt.OPEN?(this.u.log(e.Trace,`(WebSockets transport) sending data. ${m(t,this.jt)}.`),this.Ot.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this.Ot&&this.Lt(void 0),Promise.resolve()}Lt(t){this.Ot&&(this.Ot.onclose=()=>{},this.Ot.onmessage=()=>{},this.Ot.onerror=()=>{},this.Ot.close(),this.Ot=void 0),this.u.log(e.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this.Ft(t)||!1!==t.wasClean&&1e3===t.code?t instanceof Error?this.onclose(t):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)))}Ft(t){return t&&"boolean"==typeof t.wasClean&&"number"==typeof t.code}}class z{constructor(t,s={}){var i;if(this.Bt=()=>{},this.features={},this.Xt=1,w.isRequired(t,"url"),this.u=void 0===(i=s.logger)?new $(e.Information):null===i?p.instance:void 0!==i.log?i:new $(i),this.baseUrl=this.Jt(t),(s=s||{}).logMessageContent=void 0!==s.logMessageContent&&s.logMessageContent,"boolean"!=typeof s.withCredentials&&void 0!==s.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");s.withCredentials=void 0===s.withCredentials||s.withCredentials,s.timeout=void 0===s.timeout?1e5:s.timeout;let n=null,r=null;if(g.isNode){const t=require;n=t("ws"),r=t("eventsource")}g.isNode||"undefined"==typeof WebSocket||s.WebSocket?g.isNode&&!s.WebSocket&&n&&(s.WebSocket=n):s.WebSocket=WebSocket,g.isNode||"undefined"==typeof EventSource||s.EventSource?g.isNode&&!s.EventSource&&void 0!==r&&(s.EventSource=r):s.EventSource=EventSource,this.$=new q(s.httpClient||new H(this.u),s.accessTokenFactory),this.M="Disconnected",this.j=!1,this.Ht=s,this.onreceive=null,this.onclose=null}async start(t){if(t=t||O.Binary,w.isIn(t,O,"transferFormat"),this.u.log(e.Debug,`Starting connection with transfer format '${O[t]}'.`),"Disconnected"!==this.M)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this.M="Connecting",this.zt=this.F(t),await this.zt,"Disconnecting"===this.M){const t="Failed to start the HttpConnection before stop() was called.";return this.u.log(e.Error,t),await this.tt,Promise.reject(new r(t))}if("Connected"!==this.M){const t="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this.u.log(e.Error,t),Promise.reject(new r(t))}this.j=!0}send(t){return"Connected"!==this.M?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this.Vt||(this.Vt=new V(this.transport)),this.Vt.send(t))}async stop(t){return"Disconnected"===this.M?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this.M?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.tt):(this.M="Disconnecting",this.tt=new Promise((t=>{this.Bt=t})),await this.et(t),void await this.tt)}async et(t){this.Gt=t;try{await this.zt}catch(t){}if(this.transport){try{await this.transport.stop()}catch(t){this.u.log(e.Error,`HttpConnection.transport.stop() threw error '${t}'.`),this.Kt()}this.transport=void 0}else this.u.log(e.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async F(t){let s=this.baseUrl;this.kt=this.Ht.accessTokenFactory,this.$.kt=this.kt;try{if(this.Ht.skipNegotiation){if(this.Ht.transport!==W.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this.Qt(W.WebSockets),await this.Yt(s,t)}else{let e=null,i=0;do{if(e=await this.Zt(s),"Disconnecting"===this.M||"Disconnected"===this.M)throw new r("The connection was stopped during negotiation.");if(e.error)throw new Error(e.error);if(e.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(e.url&&(s=e.url),e.accessToken){const t=e.accessToken;this.kt=()=>t,this.$.Pt=t,this.$.kt=void 0}i++}while(e.url&&i<100);if(100===i&&e.url)throw new Error("Negotiate redirection limit exceeded.");await this.te(s,this.Ht.transport,e,t)}this.transport instanceof B&&(this.features.inherentKeepAlive=!0),"Connecting"===this.M&&(this.u.log(e.Debug,"The HttpConnection connected successfully."),this.M="Connected")}catch(t){return this.u.log(e.Error,"Failed to start the connection: "+t),this.M="Disconnected",this.transport=void 0,this.Bt(),Promise.reject(t)}}async Zt(t){const s={},[n,r]=E();s[n]=r;const o=this.ee(t);this.u.log(e.Debug,`Sending negotiation request: ${o}.`);try{const t=await this.$.post(o,{content:"",headers:{...s,...this.Ht.headers},timeout:this.Ht.timeout,withCredentials:this.Ht.withCredentials});if(200!==t.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`));const e=JSON.parse(t.content);return(!e.negotiateVersion||e.negotiateVersion<1)&&(e.connectionToken=e.connectionId),e}catch(t){let s="Failed to complete negotiation with the server: "+t;return t instanceof i&&404===t.statusCode&&(s+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this.u.log(e.Error,s),Promise.reject(new a(s))}}se(t,e){return e?t+(-1===t.indexOf("?")?"?":"&")+`id=${e}`:t}async te(t,s,i,n){let o=this.se(t,i.connectionToken);if(this.ie(s))return this.u.log(e.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=s,await this.Yt(o,n),void(this.connectionId=i.connectionId);const h=[],a=i.availableTransports||[];let u=i;for(const i of a){const a=this.ne(i,s,n);if(a instanceof Error)h.push(`${i.transport} failed:`),h.push(a);else if(this.ie(a)){if(this.transport=a,!u){try{u=await this.Zt(t)}catch(t){return Promise.reject(t)}o=this.se(t,u.connectionToken)}try{return await this.Yt(o,n),void(this.connectionId=u.connectionId)}catch(t){if(this.u.log(e.Error,`Failed to start the transport '${i.transport}': ${t}`),u=void 0,h.push(new c(`${i.transport} failed: ${t}`,W[i.transport])),"Connecting"!==this.M){const t="Failed to select transport before stop() was called.";return this.u.log(e.Debug,t),Promise.reject(new r(t))}}}}return h.length>0?Promise.reject(new l(`Unable to connect to the server with any of the available transports. ${h.join(" ")}`,h)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}Qt(t){switch(t){case W.WebSockets:if(!this.Ht.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new J(this.$,this.kt,this.u,this.Ht.logMessageContent,this.Ht.WebSocket,this.Ht.headers||{});case W.ServerSentEvents:if(!this.Ht.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new X(this.$,this.$.Pt,this.u,this.Ht);case W.LongPolling:return new B(this.$,this.u,this.Ht);default:throw new Error(`Unknown transport: ${t}.`)}}Yt(t,e){return this.transport.onreceive=this.onreceive,this.transport.onclose=t=>this.Kt(t),this.transport.connect(t,e)}ne(t,s,i){const n=W[t.transport];if(null==n)return this.u.log(e.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(!function(t,e){return!t||0!=(e&t)}(s,n))return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it was disabled by the client.`),new h(`'${W[n]}' is disabled by the client.`,n);if(!(t.transferFormats.map((t=>O[t])).indexOf(i)>=0))return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it does not support the requested transfer format '${O[i]}'.`),new Error(`'${W[n]}' does not support ${O[i]}.`);if(n===W.WebSockets&&!this.Ht.WebSocket||n===W.ServerSentEvents&&!this.Ht.EventSource)return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it is not supported in your environment.'`),new o(`'${W[n]}' is not supported in your environment.`,n);this.u.log(e.Debug,`Selecting transport '${W[n]}'.`);try{return this.Qt(n)}catch(t){return t}}ie(t){return t&&"object"==typeof t&&"connect"in t}Kt(t){if(this.u.log(e.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this.M}.`),this.transport=void 0,t=this.Gt||t,this.Gt=void 0,"Disconnected"!==this.M){if("Connecting"===this.M)throw this.u.log(e.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this.M&&this.Bt(),t?this.u.log(e.Error,`Connection disconnected with error '${t}'.`):this.u.log(e.Information,"Connection disconnected."),this.Vt&&(this.Vt.stop().catch((t=>{this.u.log(e.Error,`TransportSendQueue.stop() threw error '${t}'.`)})),this.Vt=void 0),this.connectionId=void 0,this.M="Disconnected",this.j){this.j=!1;try{this.onclose&&this.onclose(t)}catch(s){this.u.log(e.Error,`HttpConnection.onclose(${t}) threw error '${s}'.`)}}}else this.u.log(e.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`)}Jt(t){if(0===t.lastIndexOf("https://",0)||0===t.lastIndexOf("http://",0))return t;if(!g.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const s=window.document.createElement("a");return s.href=t,this.u.log(e.Information,`Normalizing '${t}' to '${s.href}'.`),s.href}ee(t){const e=t.indexOf("?");let s=t.substring(0,-1===e?t.length:e);return"/"!==s[s.length-1]&&(s+="/"),s+="negotiate",s+=-1===e?"":t.substring(e),-1===s.indexOf("negotiateVersion")&&(s+=-1===e?"?":"&",s+="negotiateVersion="+this.Xt),s}}class V{constructor(t){this.re=t,this.oe=[],this.he=!0,this.ce=new G,this.ae=new G,this.le=this.ue()}send(t){return this.de(t),this.ae||(this.ae=new G),this.ae.promise}stop(){return this.he=!1,this.ce.resolve(),this.le}de(t){if(this.oe.length&&typeof this.oe[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this.oe} but was of type ${typeof t}`);this.oe.push(t),this.ce.resolve()}async ue(){for(;;){if(await this.ce.promise,!this.he){this.ae&&this.ae.reject("Connection stopped.");break}this.ce=new G;const t=this.ae;this.ae=void 0;const e="string"==typeof this.oe[0]?this.oe.join(""):V.pe(this.oe);this.oe.length=0;try{await this.re.send(e),t.resolve()}catch(e){t.reject(e)}}}static pe(t){const e=t.map((t=>t.byteLength)).reduce(((t,e)=>t+e)),s=new Uint8Array(e);let i=0;for(const e of t)s.set(new Uint8Array(e),i),i+=e.byteLength;return s.buffer}}class G{constructor(){this.promise=new Promise(((t,e)=>[this.fe,this.we]=[t,e]))}resolve(){this.fe()}reject(t){this.we(t)}}class K{constructor(){this.name="json",this.version=1,this.transferFormat=O.Text}parseMessages(t,s){if("string"!=typeof t)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];null===s&&(s=p.instance);const i=D.parse(t),n=[];for(const t of i){const i=JSON.parse(t);if("number"!=typeof i.type)throw new Error("Invalid payload.");switch(i.type){case R.Invocation:this.ge(i);break;case R.StreamItem:this.me(i);break;case R.Completion:this.ye(i);break;case R.Ping:case R.Close:break;default:s.log(e.Information,"Unknown message type '"+i.type+"' ignored.");continue}n.push(i)}return n}writeMessage(t){return D.write(JSON.stringify(t))}ge(t){this.be(t.target,"Invalid payload for Invocation message."),void 0!==t.invocationId&&this.be(t.invocationId,"Invalid payload for Invocation message.")}me(t){if(this.be(t.invocationId,"Invalid payload for StreamItem message."),void 0===t.item)throw new Error("Invalid payload for StreamItem message.")}ye(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this.be(t.error,"Invalid payload for Completion message."),this.be(t.invocationId,"Invalid payload for Completion message.")}be(t,e){if("string"!=typeof t||""===t)throw new Error(e)}}const Q={trace:e.Trace,debug:e.Debug,info:e.Information,information:e.Information,warn:e.Warning,warning:e.Warning,error:e.Error,critical:e.Critical,none:e.None};class Y{configureLogging(t){if(w.isRequired(t,"logging"),void 0!==t.log)this.logger=t;else if("string"==typeof t){const e=function(t){const e=Q[t.toLowerCase()];if(void 0!==e)return e;throw new Error(`Unknown log level: ${t}`)}(t);this.logger=new $(e)}else this.logger=new $(t);return this}withUrl(t,e){return w.isRequired(t,"url"),w.isNotEmpty(t,"url"),this.url=t,this.httpConnectionOptions="object"==typeof e?{...this.httpConnectionOptions,...e}:{...this.httpConnectionOptions,transport:e},this}withHubProtocol(t){return w.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new M(t):this.reconnectPolicy=t:this.reconnectPolicy=new M,this}build(){const t=this.httpConnectionOptions||{};if(void 0===t.logger&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const e=new z(this.url,t);return N.create(e,this.logger||p.instance,this.protocol||new K,this.reconnectPolicy)}}return Uint8Array.prototype.indexOf||Object.defineProperty(Uint8Array.prototype,"indexOf",{value:Array.prototype.indexOf,writable:!0}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:function(t,e){return new Uint8Array(Array.prototype.slice.call(this,t,e))},writable:!0}),Uint8Array.prototype.forEach||Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach,writable:!0}),s})(),"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.signalR=e():t.signalR=e(); +var t,e;t=self,e=()=>(()=>{var t={d:(e,s)=>{for(var i in s)t.o(s,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:s[i]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),t.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"t",{value:!0})};var e,s={};t.r(s),t.d(s,{AbortError:()=>r,DefaultHttpClient:()=>H,HttpClient:()=>d,HttpError:()=>i,HttpResponse:()=>u,HttpTransportType:()=>W,HubConnection:()=>N,HubConnectionBuilder:()=>Y,HubConnectionState:()=>A,JsonHubProtocol:()=>K,LogLevel:()=>e,MessageType:()=>R,NullLogger:()=>p,Subject:()=>U,TimeoutError:()=>n,TransferFormat:()=>O,VERSION:()=>f});class i extends Error{constructor(t,e){const s=new.target.prototype;super(`${t}: Status code '${e}'`),this.statusCode=e,this.__proto__=s}}class n extends Error{constructor(t="A timeout occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class r extends Error{constructor(t="An abort occurred."){const e=new.target.prototype;super(t),this.__proto__=e}}class o extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="UnsupportedTransportError",this.__proto__=s}}class h extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="DisabledTransportError",this.__proto__=s}}class c extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.transport=e,this.errorType="FailedToStartTransportError",this.__proto__=s}}class a extends Error{constructor(t){const e=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=e}}class l extends Error{constructor(t,e){const s=new.target.prototype;super(t),this.innerErrors=e,this.__proto__=s}}class u{constructor(t,e,s){this.statusCode=t,this.statusText=e,this.content=s}}class d{get(t,e){return this.send({...e,method:"GET",url:t})}post(t,e){return this.send({...e,method:"POST",url:t})}delete(t,e){return this.send({...e,method:"DELETE",url:t})}getCookieString(t){return""}}!function(t){t[t.Trace=0]="Trace",t[t.Debug=1]="Debug",t[t.Information=2]="Information",t[t.Warning=3]="Warning",t[t.Error=4]="Error",t[t.Critical=5]="Critical",t[t.None=6]="None"}(e||(e={}));class p{constructor(){}log(t,e){}}p.instance=new p;const f="7.0.11";class w{static isRequired(t,e){if(null==t)throw new Error(`The '${e}' argument is required.`)}static isNotEmpty(t,e){if(!t||t.match(/^\s*$/))throw new Error(`The '${e}' argument should not be empty.`)}static isIn(t,e,s){if(!(t in e))throw new Error(`Unknown ${s} value: ${t}.`)}}class g{static get isBrowser(){return"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return"object"==typeof self&&"importScripts"in self}static get isReactNative(){return"object"==typeof window&&void 0===window.document}static get isNode(){return!this.isBrowser&&!this.isWebWorker&&!this.isReactNative}}function m(t,e){let s="";return y(t)?(s=`Binary data of length ${t.byteLength}`,e&&(s+=`. Content: '${function(t){const e=new Uint8Array(t);let s="";return e.forEach((t=>{s+=`0x${t<16?"0":""}${t.toString(16)} `})),s.substr(0,s.length-1)}(t)}'`)):"string"==typeof t&&(s=`String data of length ${t.length}`,e&&(s+=`. Content: '${t}'`)),s}function y(t){return t&&"undefined"!=typeof ArrayBuffer&&(t instanceof ArrayBuffer||t.constructor&&"ArrayBuffer"===t.constructor.name)}async function b(t,s,i,n,r,o){const h={},[c,a]=E();h[c]=a,t.log(e.Trace,`(${s} transport) sending data. ${m(r,o.logMessageContent)}.`);const l=y(r)?"arraybuffer":"text",u=await i.post(n,{content:r,headers:{...h,...o.headers},responseType:l,timeout:o.timeout,withCredentials:o.withCredentials});t.log(e.Trace,`(${s} transport) request complete. Response status: ${u.statusCode}.`)}class v{constructor(t,e){this.i=t,this.h=e}dispose(){const t=this.i.observers.indexOf(this.h);t>-1&&this.i.observers.splice(t,1),0===this.i.observers.length&&this.i.cancelCallback&&this.i.cancelCallback().catch((t=>{}))}}class ${constructor(t){this.l=t,this.out=console}log(t,s){if(t>=this.l){const i=`[${(new Date).toISOString()}] ${e[t]}: ${s}`;switch(t){case e.Critical:case e.Error:this.out.error(i);break;case e.Warning:this.out.warn(i);break;case e.Information:this.out.info(i);break;default:this.out.log(i)}}}}function E(){let t="X-SignalR-User-Agent";return g.isNode&&(t="User-Agent"),[t,C(f,S(),g.isNode?"NodeJS":"Browser",k())]}function C(t,e,s,i){let n="Microsoft SignalR/";const r=t.split(".");return n+=`${r[0]}.${r[1]}`,n+=` (${t}; `,n+=e&&""!==e?`${e}; `:"Unknown OS; ",n+=`${s}`,n+=i?`; ${i}`:"; Unknown Runtime Version",n+=")",n}function S(){if(!g.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function k(){if(g.isNode)return process.versions.node}function P(t){return t.stack?t.stack:t.message?t.message:`${t}`}class T extends d{constructor(e){if(super(),this.u=e,"undefined"==typeof fetch){const t=require;this.p=new(t("tough-cookie").CookieJar),this.m=t("node-fetch"),this.m=t("fetch-cookie")(this.m,this.p)}else this.m=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t.g)return t.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const t=require;this.v=t("abort-controller")}else this.v=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new r;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");const s=new this.v;let o;t.abortSignal&&(t.abortSignal.onabort=()=>{s.abort(),o=new r});let h,c=null;if(t.timeout){const i=t.timeout;c=setTimeout((()=>{s.abort(),this.u.log(e.Warning,"Timeout from HTTP request."),o=new n}),i)}""===t.content&&(t.content=void 0),t.content&&(t.headers=t.headers||{},y(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");try{h=await this.m(t.url,{body:t.content,cache:"no-cache",credentials:!0===t.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:s.signal})}catch(t){if(o)throw o;throw this.u.log(e.Warning,`Error from HTTP request. ${t}.`),t}finally{c&&clearTimeout(c),t.abortSignal&&(t.abortSignal.onabort=null)}if(!h.ok){const t=await I(h,"text");throw new i(t||h.statusText,h.status)}const a=I(h,t.responseType),l=await a;return new u(h.status,h.statusText,l)}getCookieString(t){let e="";return g.isNode&&this.p&&this.p.getCookies(t,((t,s)=>e=s.join("; "))),e}}function I(t,e){let s;switch(e){case"arraybuffer":s=t.arrayBuffer();break;case"text":default:s=t.text();break;case"blob":case"document":case"json":throw new Error(`${e} is not supported.`)}return s}class _ extends d{constructor(t){super(),this.u=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?new Promise(((s,o)=>{const h=new XMLHttpRequest;h.open(t.method,t.url,!0),h.withCredentials=void 0===t.withCredentials||t.withCredentials,h.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===t.content&&(t.content=void 0),t.content&&(y(t.content)?h.setRequestHeader("Content-Type","application/octet-stream"):h.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const c=t.headers;c&&Object.keys(c).forEach((t=>{h.setRequestHeader(t,c[t])})),t.responseType&&(h.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{h.abort(),o(new r)}),t.timeout&&(h.timeout=t.timeout),h.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),h.status>=200&&h.status<300?s(new u(h.status,h.statusText,h.response||h.responseText)):o(new i(h.response||h.responseText||h.statusText,h.status))},h.onerror=()=>{this.u.log(e.Warning,`Error from HTTP request. ${h.status}: ${h.statusText}.`),o(new i(h.statusText,h.status))},h.ontimeout=()=>{this.u.log(e.Warning,"Timeout from HTTP request."),o(new n)},h.send(t.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class H extends d{constructor(t){if(super(),"undefined"!=typeof fetch||g.isNode)this.$=new T(t);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this.$=new _(t)}}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new r):t.method?t.url?this.$.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this.$.getCookieString(t)}}class D{static write(t){return`${t}${D.RecordSeparator}`}static parse(t){if(t[t.length-1]!==D.RecordSeparator)throw new Error("Message is incomplete.");const e=t.split(D.RecordSeparator);return e.pop(),e}}D.RecordSeparatorCode=30,D.RecordSeparator=String.fromCharCode(D.RecordSeparatorCode);class x{writeHandshakeRequest(t){return D.write(JSON.stringify(t))}parseHandshakeResponse(t){let e,s;if(y(t)){const i=new Uint8Array(t),n=i.indexOf(D.RecordSeparatorCode);if(-1===n)throw new Error("Message is incomplete.");const r=n+1;e=String.fromCharCode.apply(null,Array.prototype.slice.call(i.slice(0,r))),s=i.byteLength>r?i.slice(r).buffer:null}else{const i=t,n=i.indexOf(D.RecordSeparator);if(-1===n)throw new Error("Message is incomplete.");const r=n+1;e=i.substring(0,r),s=i.length>r?i.substring(r):null}const i=D.parse(e),n=JSON.parse(i[0]);if(n.type)throw new Error("Expected a handshake response from the server.");return[s,n]}}var R,A;!function(t){t[t.Invocation=1]="Invocation",t[t.StreamItem=2]="StreamItem",t[t.Completion=3]="Completion",t[t.StreamInvocation=4]="StreamInvocation",t[t.CancelInvocation=5]="CancelInvocation",t[t.Ping=6]="Ping",t[t.Close=7]="Close"}(R||(R={}));class U{constructor(){this.observers=[]}next(t){for(const e of this.observers)e.next(t)}error(t){for(const e of this.observers)e.error&&e.error(t)}complete(){for(const t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new v(this,t)}}!function(t){t.Disconnected="Disconnected",t.Connecting="Connecting",t.Connected="Connected",t.Disconnecting="Disconnecting",t.Reconnecting="Reconnecting"}(A||(A={}));class N{constructor(t,s,i,n){this.C=0,this.S=()=>{this.u.log(e.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},w.isRequired(t,"connection"),w.isRequired(s,"logger"),w.isRequired(i,"protocol"),this.serverTimeoutInMilliseconds=3e4,this.keepAliveIntervalInMilliseconds=15e3,this.u=s,this.k=i,this.connection=t,this.P=n,this.T=new x,this.connection.onreceive=t=>this.I(t),this.connection.onclose=t=>this._(t),this.H={},this.D={},this.R=[],this.A=[],this.U=[],this.N=0,this.L=!1,this.M=A.Disconnected,this.j=!1,this.q=this.k.writeMessage({type:R.Ping})}static create(t,e,s,i){return new N(t,e,s,i)}get state(){return this.M}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this.M!==A.Disconnected&&this.M!==A.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this.W=this.O(),this.W}async O(){if(this.M!==A.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this.M=A.Connecting,this.u.log(e.Debug,"Starting HubConnection.");try{await this.F(),g.isBrowser&&window.document.addEventListener("freeze",this.S),this.M=A.Connected,this.j=!0,this.u.log(e.Debug,"HubConnection connected successfully.")}catch(t){return this.M=A.Disconnected,this.u.log(e.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async F(){this.B=void 0,this.L=!1;const t=new Promise(((t,e)=>{this.X=t,this.J=e}));await this.connection.start(this.k.transferFormat);try{const s={protocol:this.k.name,version:this.k.version};if(this.u.log(e.Debug,"Sending handshake request."),await this.V(this.T.writeHandshakeRequest(s)),this.u.log(e.Information,`Using HubProtocol '${this.k.name}'.`),this.G(),this.K(),this.Y(),await t,this.B)throw this.B;this.connection.features.inherentKeepAlive||await this.V(this.q)}catch(t){throw this.u.log(e.Debug,`Hub handshake failed with error '${t}' during start(). Stopping HubConnection.`),this.G(),this.Z(),await this.connection.stop(t),t}}async stop(){const t=this.W;this.tt=this.et(),await this.tt;try{await t}catch(t){}}et(t){return this.M===A.Disconnected?(this.u.log(e.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve()):this.M===A.Disconnecting?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.tt):(this.M=A.Disconnecting,this.u.log(e.Debug,"Stopping HubConnection."),this.st?(this.u.log(e.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this.st),this.st=void 0,this.it(),Promise.resolve()):(this.G(),this.Z(),this.B=t||new r("The connection was stopped before the hub handshake could complete."),this.connection.stop(t)))}stream(t,...e){const[s,i]=this.nt(e),n=this.rt(t,e,i);let r;const o=new U;return o.cancelCallback=()=>{const t=this.ot(n.invocationId);return delete this.H[n.invocationId],r.then((()=>this.ht(t)))},this.H[n.invocationId]=(t,e)=>{e?o.error(e):t&&(t.type===R.Completion?t.error?o.error(new Error(t.error)):o.complete():o.next(t.item))},r=this.ht(n).catch((t=>{o.error(t),delete this.H[n.invocationId]})),this.ct(s,r),o}V(t){return this.Y(),this.connection.send(t)}ht(t){return this.V(this.k.writeMessage(t))}send(t,...e){const[s,i]=this.nt(e),n=this.ht(this.lt(t,e,!0,i));return this.ct(s,n),n}invoke(t,...e){const[s,i]=this.nt(e),n=this.lt(t,e,!1,i);return new Promise(((t,e)=>{this.H[n.invocationId]=(s,i)=>{i?e(i):s&&(s.type===R.Completion?s.error?e(new Error(s.error)):t(s.result):e(new Error(`Unexpected message type: ${s.type}`)))};const i=this.ht(n).catch((t=>{e(t),delete this.H[n.invocationId]}));this.ct(s,i)}))}on(t,e){t&&e&&(t=t.toLowerCase(),this.D[t]||(this.D[t]=[]),-1===this.D[t].indexOf(e)&&this.D[t].push(e))}off(t,e){if(!t)return;t=t.toLowerCase();const s=this.D[t];if(s)if(e){const i=s.indexOf(e);-1!==i&&(s.splice(i,1),0===s.length&&delete this.D[t])}else delete this.D[t]}onclose(t){t&&this.R.push(t)}onreconnecting(t){t&&this.A.push(t)}onreconnected(t){t&&this.U.push(t)}I(t){if(this.G(),this.L||(t=this.ut(t),this.L=!0),t){const s=this.k.parseMessages(t,this.u);for(const t of s)switch(t.type){case R.Invocation:this.dt(t);break;case R.StreamItem:case R.Completion:{const s=this.H[t.invocationId];if(s){t.type===R.Completion&&delete this.H[t.invocationId];try{s(t)}catch(t){this.u.log(e.Error,`Stream callback threw error: ${P(t)}`)}}break}case R.Ping:break;case R.Close:{this.u.log(e.Information,"Close message received from server.");const s=t.error?new Error("Server returned an error on close: "+t.error):void 0;!0===t.allowReconnect?this.connection.stop(s):this.tt=this.et(s);break}default:this.u.log(e.Warning,`Invalid message type: ${t.type}.`)}}this.K()}ut(t){let s,i;try{[i,s]=this.T.parseHandshakeResponse(t)}catch(t){const s="Error parsing handshake response: "+t;this.u.log(e.Error,s);const i=new Error(s);throw this.J(i),i}if(s.error){const t="Server returned handshake error: "+s.error;this.u.log(e.Error,t);const i=new Error(t);throw this.J(i),i}return this.u.log(e.Debug,"Server handshake complete."),this.X(),i}Y(){this.connection.features.inherentKeepAlive||(this.C=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this.Z())}K(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this.ft=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this.wt))){let t=this.C-(new Date).getTime();t<0&&(t=0),this.wt=setTimeout((async()=>{if(this.M===A.Connected)try{await this.V(this.q)}catch{this.Z()}}),t)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async dt(t){const s=t.target.toLowerCase(),i=this.D[s];if(!i)return this.u.log(e.Warning,`No client method with the name '${s}' found.`),void(t.invocationId&&(this.u.log(e.Warning,`No result given for '${s}' method and invocation ID '${t.invocationId}'.`),await this.ht(this.gt(t.invocationId,"Client didn't provide a result.",null))));const n=i.slice(),r=!!t.invocationId;let o,h,c;for(const i of n)try{const n=o;o=await i.apply(this,t.arguments),r&&o&&n&&(this.u.log(e.Error,`Multiple results provided for '${s}'. Sending error to server.`),c=this.gt(t.invocationId,"Client provided multiple results.",null)),h=void 0}catch(t){h=t,this.u.log(e.Error,`A callback for the method '${s}' threw error '${t}'.`)}c?await this.ht(c):r?(h?c=this.gt(t.invocationId,`${h}`,null):void 0!==o?c=this.gt(t.invocationId,null,o):(this.u.log(e.Warning,`No result given for '${s}' method and invocation ID '${t.invocationId}'.`),c=this.gt(t.invocationId,"Client didn't provide a result.",null)),await this.ht(c)):o&&this.u.log(e.Error,`Result given for '${s}' method but server is not expecting a result.`)}_(t){this.u.log(e.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this.M}.`),this.B=this.B||t||new r("The underlying connection was closed before the hub handshake could complete."),this.X&&this.X(),this.yt(t||new Error("Invocation canceled due to the underlying connection being closed.")),this.G(),this.Z(),this.M===A.Disconnecting?this.it(t):this.M===A.Connected&&this.P?this.bt(t):this.M===A.Connected&&this.it(t)}it(t){if(this.j){this.M=A.Disconnected,this.j=!1,g.isBrowser&&window.document.removeEventListener("freeze",this.S);try{this.R.forEach((e=>e.apply(this,[t])))}catch(s){this.u.log(e.Error,`An onclose callback called with error '${t}' threw error '${s}'.`)}}}async bt(t){const s=Date.now();let i=0,n=void 0!==t?t:new Error("Attempting to reconnect due to a unknown error."),r=this.vt(i++,0,n);if(null===r)return this.u.log(e.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this.it(t);if(this.M=A.Reconnecting,t?this.u.log(e.Information,`Connection reconnecting because of error '${t}'.`):this.u.log(e.Information,"Connection reconnecting."),0!==this.A.length){try{this.A.forEach((e=>e.apply(this,[t])))}catch(s){this.u.log(e.Error,`An onreconnecting callback called with error '${t}' threw error '${s}'.`)}if(this.M!==A.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this.u.log(e.Information,`Reconnect attempt number ${i} will start in ${r} ms.`),await new Promise((t=>{this.st=setTimeout(t,r)})),this.st=void 0,this.M!==A.Reconnecting)return void this.u.log(e.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this.F(),this.M=A.Connected,this.u.log(e.Information,"HubConnection reconnected successfully."),0!==this.U.length)try{this.U.forEach((t=>t.apply(this,[this.connection.connectionId])))}catch(t){this.u.log(e.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${t}'.`)}return}catch(t){if(this.u.log(e.Information,`Reconnect attempt failed because of error '${t}'.`),this.M!==A.Reconnecting)return this.u.log(e.Debug,`Connection moved to the '${this.M}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this.M===A.Disconnecting&&this.it());n=t instanceof Error?t:new Error(t.toString()),r=this.vt(i++,Date.now()-s,n)}}this.u.log(e.Information,`Reconnect retries have been exhausted after ${Date.now()-s} ms and ${i} failed attempts. Connection disconnecting.`),this.it()}vt(t,s,i){try{return this.P.nextRetryDelayInMilliseconds({elapsedMilliseconds:s,previousRetryCount:t,retryReason:i})}catch(i){return this.u.log(e.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${s}) threw error '${i}'.`),null}}yt(t){const s=this.H;this.H={},Object.keys(s).forEach((i=>{const n=s[i];try{n(null,t)}catch(s){this.u.log(e.Error,`Stream 'error' callback called with '${t}' threw error: ${P(s)}`)}}))}Z(){this.wt&&(clearTimeout(this.wt),this.wt=void 0)}G(){this.ft&&clearTimeout(this.ft)}lt(t,e,s,i){if(s)return 0!==i.length?{arguments:e,streamIds:i,target:t,type:R.Invocation}:{arguments:e,target:t,type:R.Invocation};{const s=this.N;return this.N++,0!==i.length?{arguments:e,invocationId:s.toString(),streamIds:i,target:t,type:R.Invocation}:{arguments:e,invocationId:s.toString(),target:t,type:R.Invocation}}}ct(t,e){if(0!==t.length){e||(e=Promise.resolve());for(const s in t)t[s].subscribe({complete:()=>{e=e.then((()=>this.ht(this.gt(s))))},error:t=>{let i;i=t instanceof Error?t.message:t&&t.toString?t.toString():"Unknown error",e=e.then((()=>this.ht(this.gt(s,i))))},next:t=>{e=e.then((()=>this.ht(this.$t(s,t))))}})}}nt(t){const e=[],s=[];for(let i=0;i0)&&(e=!1,this.Pt=await this.kt()),this.Tt(t);const s=await this.St.send(t);return e&&401===s.statusCode&&this.kt?(this.Pt=await this.kt(),this.Tt(t),await this.St.send(t)):s}Tt(t){t.headers||(t.headers={}),this.Pt?t.headers[j.Authorization]=`Bearer ${this.Pt}`:this.kt&&t.headers[j.Authorization]&&delete t.headers[j.Authorization]}getCookieString(t){return this.St.getCookieString(t)}}var W,O;!function(t){t[t.None=0]="None",t[t.WebSockets=1]="WebSockets",t[t.ServerSentEvents=2]="ServerSentEvents",t[t.LongPolling=4]="LongPolling"}(W||(W={})),function(t){t[t.Text=1]="Text",t[t.Binary=2]="Binary"}(O||(O={}));class F{constructor(){this.It=!1,this.onabort=null}abort(){this.It||(this.It=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this.It}}class B{constructor(t,e,s){this.$=t,this.u=e,this._t=new F,this.Ht=s,this.Dt=!1,this.onreceive=null,this.onclose=null}get pollAborted(){return this._t.aborted}async connect(t,s){if(w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.xt=t,this.u.log(e.Trace,"(LongPolling transport) Connecting."),s===O.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,r]=E(),o={[n]:r,...this.Ht.headers},h={abortSignal:this._t.signal,headers:o,timeout:1e5,withCredentials:this.Ht.withCredentials};s===O.Binary&&(h.responseType="arraybuffer");const c=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${c}.`);const a=await this.$.get(c,h);200!==a.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this.Rt=new i(a.statusText||"",a.statusCode),this.Dt=!1):this.Dt=!0,this.At=this.Ut(this.xt,h)}async Ut(t,s){try{for(;this.Dt;)try{const n=`${t}&_=${Date.now()}`;this.u.log(e.Trace,`(LongPolling transport) polling: ${n}.`);const r=await this.$.get(n,s);204===r.statusCode?(this.u.log(e.Information,"(LongPolling transport) Poll terminated by server."),this.Dt=!1):200!==r.statusCode?(this.u.log(e.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this.Rt=new i(r.statusText||"",r.statusCode),this.Dt=!1):r.content?(this.u.log(e.Trace,`(LongPolling transport) data received. ${m(r.content,this.Ht.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(t){this.Dt?t instanceof n?this.u.log(e.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this.Rt=t,this.Dt=!1):this.u.log(e.Trace,`(LongPolling transport) Poll errored after shutdown: ${t.message}`)}}finally{this.u.log(e.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this.Nt()}}async send(t){return this.Dt?b(this.u,"LongPolling",this.$,this.xt,t,this.Ht):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this.u.log(e.Trace,"(LongPolling transport) Stopping polling."),this.Dt=!1,this._t.abort();try{await this.At,this.u.log(e.Trace,`(LongPolling transport) sending DELETE request to ${this.xt}.`);const t={},[s,i]=E();t[s]=i;const n={headers:{...t,...this.Ht.headers},timeout:this.Ht.timeout,withCredentials:this.Ht.withCredentials};await this.$.delete(this.xt,n),this.u.log(e.Trace,"(LongPolling transport) DELETE request sent.")}finally{this.u.log(e.Trace,"(LongPolling transport) Stop finished."),this.Nt()}}Nt(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this.Rt&&(t+=" Error: "+this.Rt),this.u.log(e.Trace,t),this.onclose(this.Rt)}}}class X{constructor(t,e,s,i){this.$=t,this.Pt=e,this.u=s,this.Ht=i,this.onreceive=null,this.onclose=null}async connect(t,s){return w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.u.log(e.Trace,"(SSE transport) Connecting."),this.xt=t,this.Pt&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this.Pt)}`),new Promise(((i,n)=>{let r,o=!1;if(s===O.Text){if(g.isBrowser||g.isWebWorker)r=new this.Ht.EventSource(t,{withCredentials:this.Ht.withCredentials});else{const e=this.$.getCookieString(t),s={};s.Cookie=e;const[i,n]=E();s[i]=n,r=new this.Ht.EventSource(t,{withCredentials:this.Ht.withCredentials,headers:{...s,...this.Ht.headers}})}try{r.onmessage=t=>{if(this.onreceive)try{this.u.log(e.Trace,`(SSE transport) data received. ${m(t.data,this.Ht.logMessageContent)}.`),this.onreceive(t.data)}catch(t){return void this.Lt(t)}},r.onerror=t=>{o?this.Lt():n(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this.u.log(e.Information,`SSE connected to ${this.xt}`),this.Mt=r,o=!0,i()}}catch(t){return void n(t)}}else n(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(t){return this.Mt?b(this.u,"SSE",this.$,this.xt,t,this.Ht):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this.Lt(),Promise.resolve()}Lt(t){this.Mt&&(this.Mt.close(),this.Mt=void 0,this.onclose&&this.onclose(t))}}class J{constructor(t,e,s,i,n,r){this.u=s,this.kt=e,this.jt=i,this.qt=n,this.$=t,this.onreceive=null,this.onclose=null,this.Wt=r}async connect(t,s){let i;return w.isRequired(t,"url"),w.isRequired(s,"transferFormat"),w.isIn(s,O,"transferFormat"),this.u.log(e.Trace,"(WebSockets transport) Connecting."),this.kt&&(i=await this.kt()),new Promise(((n,r)=>{let o;t=t.replace(/^http/,"ws");const h=this.$.getCookieString(t);let c=!1;if(g.isNode||g.isReactNative){const e={},[s,n]=E();e[s]=n,i&&(e[j.Authorization]=`Bearer ${i}`),h&&(e[j.Cookie]=h),o=new this.qt(t,void 0,{headers:{...e,...this.Wt}})}else i&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(i)}`);o||(o=new this.qt(t)),s===O.Binary&&(o.binaryType="arraybuffer"),o.onopen=s=>{this.u.log(e.Information,`WebSocket connected to ${t}.`),this.Ot=o,c=!0,n()},o.onerror=t=>{let s=null;s="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"There was an error with the transport",this.u.log(e.Information,`(WebSockets transport) ${s}.`)},o.onmessage=t=>{if(this.u.log(e.Trace,`(WebSockets transport) data received. ${m(t.data,this.jt)}.`),this.onreceive)try{this.onreceive(t.data)}catch(t){return void this.Lt(t)}},o.onclose=t=>{if(c)this.Lt(t);else{let e=null;e="undefined"!=typeof ErrorEvent&&t instanceof ErrorEvent?t.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(e))}}}))}send(t){return this.Ot&&this.Ot.readyState===this.qt.OPEN?(this.u.log(e.Trace,`(WebSockets transport) sending data. ${m(t,this.jt)}.`),this.Ot.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this.Ot&&this.Lt(void 0),Promise.resolve()}Lt(t){this.Ot&&(this.Ot.onclose=()=>{},this.Ot.onmessage=()=>{},this.Ot.onerror=()=>{},this.Ot.close(),this.Ot=void 0),this.u.log(e.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this.Ft(t)||!1!==t.wasClean&&1e3===t.code?t instanceof Error?this.onclose(t):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)))}Ft(t){return t&&"boolean"==typeof t.wasClean&&"number"==typeof t.code}}class z{constructor(t,s={}){var i;if(this.Bt=()=>{},this.features={},this.Xt=1,w.isRequired(t,"url"),this.u=void 0===(i=s.logger)?new $(e.Information):null===i?p.instance:void 0!==i.log?i:new $(i),this.baseUrl=this.Jt(t),(s=s||{}).logMessageContent=void 0!==s.logMessageContent&&s.logMessageContent,"boolean"!=typeof s.withCredentials&&void 0!==s.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");s.withCredentials=void 0===s.withCredentials||s.withCredentials,s.timeout=void 0===s.timeout?1e5:s.timeout;let n=null,r=null;if(g.isNode){const t=require;n=t("ws"),r=t("eventsource")}g.isNode||"undefined"==typeof WebSocket||s.WebSocket?g.isNode&&!s.WebSocket&&n&&(s.WebSocket=n):s.WebSocket=WebSocket,g.isNode||"undefined"==typeof EventSource||s.EventSource?g.isNode&&!s.EventSource&&void 0!==r&&(s.EventSource=r):s.EventSource=EventSource,this.$=new q(s.httpClient||new H(this.u),s.accessTokenFactory),this.M="Disconnected",this.j=!1,this.Ht=s,this.onreceive=null,this.onclose=null}async start(t){if(t=t||O.Binary,w.isIn(t,O,"transferFormat"),this.u.log(e.Debug,`Starting connection with transfer format '${O[t]}'.`),"Disconnected"!==this.M)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this.M="Connecting",this.zt=this.F(t),await this.zt,"Disconnecting"===this.M){const t="Failed to start the HttpConnection before stop() was called.";return this.u.log(e.Error,t),await this.tt,Promise.reject(new r(t))}if("Connected"!==this.M){const t="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this.u.log(e.Error,t),Promise.reject(new r(t))}this.j=!0}send(t){return"Connected"!==this.M?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this.Vt||(this.Vt=new V(this.transport)),this.Vt.send(t))}async stop(t){return"Disconnected"===this.M?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this.M?(this.u.log(e.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this.tt):(this.M="Disconnecting",this.tt=new Promise((t=>{this.Bt=t})),await this.et(t),void await this.tt)}async et(t){this.Gt=t;try{await this.zt}catch(t){}if(this.transport){try{await this.transport.stop()}catch(t){this.u.log(e.Error,`HttpConnection.transport.stop() threw error '${t}'.`),this.Kt()}this.transport=void 0}else this.u.log(e.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async F(t){let s=this.baseUrl;this.kt=this.Ht.accessTokenFactory,this.$.kt=this.kt;try{if(this.Ht.skipNegotiation){if(this.Ht.transport!==W.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this.Qt(W.WebSockets),await this.Yt(s,t)}else{let e=null,i=0;do{if(e=await this.Zt(s),"Disconnecting"===this.M||"Disconnected"===this.M)throw new r("The connection was stopped during negotiation.");if(e.error)throw new Error(e.error);if(e.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(e.url&&(s=e.url),e.accessToken){const t=e.accessToken;this.kt=()=>t,this.$.Pt=t,this.$.kt=void 0}i++}while(e.url&&i<100);if(100===i&&e.url)throw new Error("Negotiate redirection limit exceeded.");await this.te(s,this.Ht.transport,e,t)}this.transport instanceof B&&(this.features.inherentKeepAlive=!0),"Connecting"===this.M&&(this.u.log(e.Debug,"The HttpConnection connected successfully."),this.M="Connected")}catch(t){return this.u.log(e.Error,"Failed to start the connection: "+t),this.M="Disconnected",this.transport=void 0,this.Bt(),Promise.reject(t)}}async Zt(t){const s={},[n,r]=E();s[n]=r;const o=this.ee(t);this.u.log(e.Debug,`Sending negotiation request: ${o}.`);try{const t=await this.$.post(o,{content:"",headers:{...s,...this.Ht.headers},timeout:this.Ht.timeout,withCredentials:this.Ht.withCredentials});if(200!==t.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${t.statusCode}'`));const e=JSON.parse(t.content);return(!e.negotiateVersion||e.negotiateVersion<1)&&(e.connectionToken=e.connectionId),e}catch(t){let s="Failed to complete negotiation with the server: "+t;return t instanceof i&&404===t.statusCode&&(s+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this.u.log(e.Error,s),Promise.reject(new a(s))}}se(t,e){return e?t+(-1===t.indexOf("?")?"?":"&")+`id=${e}`:t}async te(t,s,i,n){let o=this.se(t,i.connectionToken);if(this.ie(s))return this.u.log(e.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=s,await this.Yt(o,n),void(this.connectionId=i.connectionId);const h=[],a=i.availableTransports||[];let u=i;for(const i of a){const a=this.ne(i,s,n);if(a instanceof Error)h.push(`${i.transport} failed:`),h.push(a);else if(this.ie(a)){if(this.transport=a,!u){try{u=await this.Zt(t)}catch(t){return Promise.reject(t)}o=this.se(t,u.connectionToken)}try{return await this.Yt(o,n),void(this.connectionId=u.connectionId)}catch(t){if(this.u.log(e.Error,`Failed to start the transport '${i.transport}': ${t}`),u=void 0,h.push(new c(`${i.transport} failed: ${t}`,W[i.transport])),"Connecting"!==this.M){const t="Failed to select transport before stop() was called.";return this.u.log(e.Debug,t),Promise.reject(new r(t))}}}}return h.length>0?Promise.reject(new l(`Unable to connect to the server with any of the available transports. ${h.join(" ")}`,h)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}Qt(t){switch(t){case W.WebSockets:if(!this.Ht.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new J(this.$,this.kt,this.u,this.Ht.logMessageContent,this.Ht.WebSocket,this.Ht.headers||{});case W.ServerSentEvents:if(!this.Ht.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new X(this.$,this.$.Pt,this.u,this.Ht);case W.LongPolling:return new B(this.$,this.u,this.Ht);default:throw new Error(`Unknown transport: ${t}.`)}}Yt(t,e){return this.transport.onreceive=this.onreceive,this.transport.onclose=t=>this.Kt(t),this.transport.connect(t,e)}ne(t,s,i){const n=W[t.transport];if(null==n)return this.u.log(e.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(!function(t,e){return!t||0!=(e&t)}(s,n))return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it was disabled by the client.`),new h(`'${W[n]}' is disabled by the client.`,n);if(!(t.transferFormats.map((t=>O[t])).indexOf(i)>=0))return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it does not support the requested transfer format '${O[i]}'.`),new Error(`'${W[n]}' does not support ${O[i]}.`);if(n===W.WebSockets&&!this.Ht.WebSocket||n===W.ServerSentEvents&&!this.Ht.EventSource)return this.u.log(e.Debug,`Skipping transport '${W[n]}' because it is not supported in your environment.'`),new o(`'${W[n]}' is not supported in your environment.`,n);this.u.log(e.Debug,`Selecting transport '${W[n]}'.`);try{return this.Qt(n)}catch(t){return t}}ie(t){return t&&"object"==typeof t&&"connect"in t}Kt(t){if(this.u.log(e.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this.M}.`),this.transport=void 0,t=this.Gt||t,this.Gt=void 0,"Disconnected"!==this.M){if("Connecting"===this.M)throw this.u.log(e.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this.M&&this.Bt(),t?this.u.log(e.Error,`Connection disconnected with error '${t}'.`):this.u.log(e.Information,"Connection disconnected."),this.Vt&&(this.Vt.stop().catch((t=>{this.u.log(e.Error,`TransportSendQueue.stop() threw error '${t}'.`)})),this.Vt=void 0),this.connectionId=void 0,this.M="Disconnected",this.j){this.j=!1;try{this.onclose&&this.onclose(t)}catch(s){this.u.log(e.Error,`HttpConnection.onclose(${t}) threw error '${s}'.`)}}}else this.u.log(e.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`)}Jt(t){if(0===t.lastIndexOf("https://",0)||0===t.lastIndexOf("http://",0))return t;if(!g.isBrowser)throw new Error(`Cannot resolve '${t}'.`);const s=window.document.createElement("a");return s.href=t,this.u.log(e.Information,`Normalizing '${t}' to '${s.href}'.`),s.href}ee(t){const e=t.indexOf("?");let s=t.substring(0,-1===e?t.length:e);return"/"!==s[s.length-1]&&(s+="/"),s+="negotiate",s+=-1===e?"":t.substring(e),-1===s.indexOf("negotiateVersion")&&(s+=-1===e?"?":"&",s+="negotiateVersion="+this.Xt),s}}class V{constructor(t){this.re=t,this.oe=[],this.he=!0,this.ce=new G,this.ae=new G,this.le=this.ue()}send(t){return this.de(t),this.ae||(this.ae=new G),this.ae.promise}stop(){return this.he=!1,this.ce.resolve(),this.le}de(t){if(this.oe.length&&typeof this.oe[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this.oe} but was of type ${typeof t}`);this.oe.push(t),this.ce.resolve()}async ue(){for(;;){if(await this.ce.promise,!this.he){this.ae&&this.ae.reject("Connection stopped.");break}this.ce=new G;const t=this.ae;this.ae=void 0;const e="string"==typeof this.oe[0]?this.oe.join(""):V.pe(this.oe);this.oe.length=0;try{await this.re.send(e),t.resolve()}catch(e){t.reject(e)}}}static pe(t){const e=t.map((t=>t.byteLength)).reduce(((t,e)=>t+e)),s=new Uint8Array(e);let i=0;for(const e of t)s.set(new Uint8Array(e),i),i+=e.byteLength;return s.buffer}}class G{constructor(){this.promise=new Promise(((t,e)=>[this.fe,this.we]=[t,e]))}resolve(){this.fe()}reject(t){this.we(t)}}class K{constructor(){this.name="json",this.version=1,this.transferFormat=O.Text}parseMessages(t,s){if("string"!=typeof t)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];null===s&&(s=p.instance);const i=D.parse(t),n=[];for(const t of i){const i=JSON.parse(t);if("number"!=typeof i.type)throw new Error("Invalid payload.");switch(i.type){case R.Invocation:this.ge(i);break;case R.StreamItem:this.me(i);break;case R.Completion:this.ye(i);break;case R.Ping:case R.Close:break;default:s.log(e.Information,"Unknown message type '"+i.type+"' ignored.");continue}n.push(i)}return n}writeMessage(t){return D.write(JSON.stringify(t))}ge(t){this.be(t.target,"Invalid payload for Invocation message."),void 0!==t.invocationId&&this.be(t.invocationId,"Invalid payload for Invocation message.")}me(t){if(this.be(t.invocationId,"Invalid payload for StreamItem message."),void 0===t.item)throw new Error("Invalid payload for StreamItem message.")}ye(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this.be(t.error,"Invalid payload for Completion message."),this.be(t.invocationId,"Invalid payload for Completion message.")}be(t,e){if("string"!=typeof t||""===t)throw new Error(e)}}const Q={trace:e.Trace,debug:e.Debug,info:e.Information,information:e.Information,warn:e.Warning,warning:e.Warning,error:e.Error,critical:e.Critical,none:e.None};class Y{configureLogging(t){if(w.isRequired(t,"logging"),void 0!==t.log)this.logger=t;else if("string"==typeof t){const e=function(t){const e=Q[t.toLowerCase()];if(void 0!==e)return e;throw new Error(`Unknown log level: ${t}`)}(t);this.logger=new $(e)}else this.logger=new $(t);return this}withUrl(t,e){return w.isRequired(t,"url"),w.isNotEmpty(t,"url"),this.url=t,this.httpConnectionOptions="object"==typeof e?{...this.httpConnectionOptions,...e}:{...this.httpConnectionOptions,transport:e},this}withHubProtocol(t){return w.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new M(t):this.reconnectPolicy=t:this.reconnectPolicy=new M,this}build(){const t=this.httpConnectionOptions||{};if(void 0===t.logger&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const e=new z(this.url,t);return N.create(e,this.logger||p.instance,this.protocol||new K,this.reconnectPolicy)}}return Uint8Array.prototype.indexOf||Object.defineProperty(Uint8Array.prototype,"indexOf",{value:Array.prototype.indexOf,writable:!0}),Uint8Array.prototype.slice||Object.defineProperty(Uint8Array.prototype,"slice",{value:function(t,e){return new Uint8Array(Array.prototype.slice.call(this,t,e))},writable:!0}),Uint8Array.prototype.forEach||Object.defineProperty(Uint8Array.prototype,"forEach",{value:Array.prototype.forEach,writable:!0}),s})(),"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.signalR=e():t.signalR=e(); //# sourceMappingURL=signalr.min.js.map -var e,t;e=self,t=e=>(()=>{var t=[,t=>{t.exports=e}],r={};function i(e){var n=r[e];if(void 0!==n)return n.exports;var s=r[e]={exports:{}};return t[e](s,s.exports,i),s.exports}i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{i.r(n),i.d(n,{MessagePackHubProtocol:()=>R,VERSION:()=>O});var e=4294967295;function t(e,t,r){var i=Math.floor(r/4294967296),n=r;e.setUint32(t,i),e.setUint32(t+4,n)}function r(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var s=("undefined"==typeof process||"never"!==process.env.TEXT_ENCODING)&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function o(e){for(var t=e.length,r=0,i=0;i=55296&&n<=56319&&i65535&&(u-=65536,s.push(u>>>10&1023|55296),u=56320|1023&u),s.push(u)}else s.push(a);s.length>=4096&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(o+=String.fromCharCode.apply(String,s)),o}var f,p=s?new TextDecoder:null,l=s?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:e,d=function(e,t){this.type=e,this.data=t},y=(f=function(e,t){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},f(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}f(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),w=function(e){function t(r){var i=e.call(this,r)||this,n=Object.create(t.prototype);return Object.setPrototypeOf(i,n),Object.defineProperty(i,"name",{configurable:!0,enumerable:!1,value:t.name}),i}return y(t,e),t}(Error),g={type:-1,encode:function(e){var r,i,n,s;return e instanceof Date?function(e){var r,i=e.sec,n=e.nsec;if(i>=0&&n>=0&&i<=17179869183){if(0===n&&i<=4294967295){var s=new Uint8Array(4);return(r=new DataView(s.buffer)).setUint32(0,i),s}var o=i/4294967296,a=4294967295&i;return s=new Uint8Array(8),(r=new DataView(s.buffer)).setUint32(0,n<<2|3&o),r.setUint32(4,a),s}return s=new Uint8Array(12),(r=new DataView(s.buffer)).setUint32(0,n),t(r,4,i),s}((r=e.getTime(),i=Math.floor(r/1e3),n=1e6*(r-1e3*i),s=Math.floor(n/1e9),{sec:i+s,nsec:n-1e9*s})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var i=t.getUint32(0);return{sec:4294967296*(3&i)+t.getUint32(4),nsec:i>>>2};case 12:return{sec:r(t,4),nsec:t.getUint32(0)};default:throw new w("Unrecognized data size for timestamp (expected 4, 8, or 12): "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},v=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(g)}return e.prototype.register=function(e){var t=e.type,r=e.encode,i=e.decode;if(t>=0)this.encoders[t]=r,this.decoders[t]=i;else{var n=1+t;this.builtInEncoders[n]=r,this.builtInDecoders[n]=i}},e.prototype.tryToEncode=function(e,t){for(var r=0;rthis.maxDepth)throw new Error("Too deep objects in depth "+t);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>h){var t=o(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),c(e,this.bytes,this.pos),this.pos+=t}else t=o(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,r){for(var i=e.length,n=r,s=0;s>6&31|192;else{if(o>=55296&&o<=56319&&s>12&15|224,t[n++]=o>>6&63|128):(t[n++]=o>>18&7|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128)}t[n++]=63&o|128}else t[n++]=o}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var r=this.extensionCodec.tryToEncode(e,this.context);if(null!=r)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: "+Object.prototype.toString.apply(e));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: "+t);this.writeU8(198),this.writeU32(t)}var r=m(e);this.writeU8a(r)},e.prototype.encodeArray=function(e,t){var r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large array: "+r);this.writeU8(221),this.writeU32(r)}for(var i=0,n=e;i0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,r){e:for(var i=0,n=this.caches[r-1];i=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)},e.prototype.decode=function(e,t,r){var i=this.find(e,t,r);if(null!=i)return this.hit++,i;this.miss++;var n=u(e,t,r),s=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(s,n),n},e}(),x=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{h(i.next(e))}catch(e){s(e)}}function a(e){try{h(i.throw(e))}catch(e){s(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((i=i.apply(e,t||[])).next())}))},S=function(e,t){var r,i,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,i&&(n=2&s[0]?i.return:s[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,s[1])).done)return n;switch(i=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((n=(n=o.trys).length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]1||a(e,t)}))})}function a(e,t){try{(r=n[e](t)).value instanceof _?Promise.resolve(r.value.v).then(h,c):u(s[0][2],r)}catch(e){u(s[0][3],e)}var r}function h(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}},T=new DataView(new ArrayBuffer(0)),B=new Uint8Array(T.buffer),A=function(){try{T.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),L=new A("Insufficient data"),C=new I,k=function(){function t(t,r,i,n,s,o,a,h){void 0===t&&(t=v.defaultCodec),void 0===r&&(r=void 0),void 0===i&&(i=e),void 0===n&&(n=e),void 0===s&&(s=e),void 0===o&&(o=e),void 0===a&&(a=e),void 0===h&&(h=C),this.extensionCodec=t,this.context=r,this.maxStrLength=i,this.maxBinLength=n,this.maxArrayLength=s,this.maxMapLength=o,this.maxExtLength=a,this.keyDecoder=h,this.totalPos=0,this.pos=0,this.view=T,this.bytes=B,this.headByte=-1,this.stack=[]}return t.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},t.prototype.setBuffer=function(e){this.bytes=m(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=m(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},t.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),r=m(e),i=new Uint8Array(t.length+r.length);i.set(t),i.set(r,t.length),this.setBuffer(i)}else this.setBuffer(e)},t.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},t.prototype.createExtraByteError=function(e){var t=this.view,r=this.pos;return new RangeError("Extra "+(t.byteLength-r)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},t.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},t.prototype.decodeMulti=function(e){return S(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},t.prototype.decodeAsync=function(e){var t,r,i,n;return x(this,void 0,void 0,(function(){var s,o,a,h,c,u,f,p;return S(this,(function(l){switch(l.label){case 0:s=!1,l.label=1;case 1:l.trys.push([1,6,7,12]),t=E(e),l.label=2;case 2:return[4,t.next()];case 3:if((r=l.sent()).done)return[3,5];if(a=r.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{o=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof A))throw e}this.totalPos+=this.pos,l.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return h=l.sent(),i={error:h},[3,12];case 7:return l.trys.push([7,,10,11]),r&&!r.done&&(n=t.return)?[4,n.call(t)]:[3,9];case 8:l.sent(),l.label=9;case 9:return[3,11];case 10:if(i)throw i.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,o]}throw u=(c=this).headByte,f=c.pos,p=c.totalPos,new RangeError("Insufficient data in parsing "+U(u)+" at "+p+" ("+f+" in the current buffer)")}}))}))},t.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},t.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},t.prototype.decodeMultiAsync=function(e,t){return M(this,arguments,(function(){var r,i,n,s,o,a,h,c,u;return S(this,(function(f){switch(f.label){case 0:r=t,i=-1,f.label=1;case 1:f.trys.push([1,13,14,19]),n=E(e),f.label=2;case 2:return[4,_(n.next())];case 3:if((s=f.sent()).done)return[3,12];if(o=s.value,t&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(i=this.readArraySize(),r=!1,this.complete()),f.label=4;case 4:f.trys.push([4,9,,10]),f.label=5;case 5:return[4,_(this.doDecodeSync())];case 6:return[4,f.sent()];case 7:return f.sent(),0==--i?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=f.sent())instanceof A))throw a;return[3,10];case 10:this.totalPos+=this.pos,f.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return h=f.sent(),c={error:h},[3,19];case 14:return f.trys.push([14,,17,18]),s&&!s.done&&(u=n.return)?[4,_(u.call(n))]:[3,16];case 15:f.sent(),f.label=16;case 16:return[3,18];case 17:if(c)throw c.error;return[7];case 18:return[7];case 19:return[2]}}))}))},t.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(i=e-128)){this.pushMapState(i),this.complete();continue e}t={}}else if(e<160){if(0!=(i=e-144)){this.pushArrayState(i),this.complete();continue e}t=[]}else{var r=e-160;t=this.decodeUtf8String(r,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)r=this.lookU8(),t=this.decodeUtf8String(r,1);else if(218===e)r=this.lookU16(),t=this.decodeUtf8String(r,2);else if(219===e)r=this.lookU32(),t=this.decodeUtf8String(r,4);else if(220===e){if(0!==(i=this.readU16())){this.pushArrayState(i),this.complete();continue e}t=[]}else if(221===e){if(0!==(i=this.readU32())){this.pushArrayState(i),this.complete();continue e}t=[]}else if(222===e){if(0!==(i=this.readU16())){this.pushMapState(i),this.complete();continue e}t={}}else if(223===e){if(0!==(i=this.readU32())){this.pushMapState(i),this.complete();continue e}t={}}else if(196===e){var i=this.lookU8();t=this.decodeBinary(i,1)}else if(197===e)i=this.lookU16(),t=this.decodeBinary(i,2);else if(198===e)i=this.lookU32(),t=this.decodeBinary(i,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)i=this.lookU8(),t=this.decodeExtension(i,1);else if(200===e)i=this.lookU16(),t=this.decodeExtension(i,2);else{if(201!==e)throw new w("Unrecognized type byte: "+U(e));i=this.lookU32(),t=this.decodeExtension(i,4)}this.complete();for(var n=this.stack;n.length>0;){var s=n[n.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;n.pop(),t=s.array}else{if(1===s.type){if(o=void 0,"string"!=(o=typeof t)&&"number"!==o)throw new w("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new w("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}n.pop(),t=s.map}}return t}var o},t.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},t.prototype.complete=function(){this.headByte=-1},t.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new w("Unrecognized array type byte: "+U(e))}},t.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new w("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},t.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new w("Max length exceeded: array length ("+e+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:e,array:new Array(e),position:0})},t.prototype.decodeUtf8String=function(e,t){var r;if(e>this.maxStrLength)throw new w("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthl?function(e,t,r){var i=e.subarray(t,t+r);return p.decode(i)}(this.bytes,n,e):u(this.bytes,n,e),this.pos+=t+e,i},t.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},t.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new w("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw L;var r=this.pos+t,i=this.bytes.subarray(r,r+e);return this.pos+=t+e,i},t.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new w("Max length exceeded: ext length ("+e+") > maxExtLength ("+this.maxExtLength+")");var r=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,r,this.context)},t.prototype.lookU8=function(){return this.view.getUint8(this.pos)},t.prototype.lookU16=function(){return this.view.getUint16(this.pos)},t.prototype.lookU32=function(){return this.view.getUint32(this.pos)},t.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},t.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},t.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},t.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},t.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},t.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},t.prototype.readU64=function(){var e,t,r=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,r},t.prototype.readI64=function(){var e=r(this.view,this.pos);return this.pos+=8,e},t.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},t.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},t}(),z=i(1);class D{static write(e){let t=e.byteLength||e.length;const r=[];do{let e=127&t;t>>=7,t>0&&(e|=128),r.push(e)}while(t>0);t=e.byteLength||e.length;const i=new Uint8Array(r.length+t);return i.set(r,0),i.set(e,r.length),i.buffer}static parse(e){const t=[],r=new Uint8Array(e),i=[0,7,14,21,28];for(let n=0;n7)throw new Error("Messages bigger than 2GB are not supported.");if(!(r.byteLength>=n+o+a))throw new Error("Incomplete message.");t.push(r.slice?r.slice(n+o,n+o+a):r.subarray(n+o,n+o+a)),n=n+o+a}return t}}const P=new Uint8Array([145,z.MessageType.Ping]);class R{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=z.TransferFormat.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new b(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new k(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(r=e)||"undefined"==typeof ArrayBuffer||!(r instanceof ArrayBuffer||r.constructor&&"ArrayBuffer"===r.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var r;null===t&&(t=z.NullLogger.instance);const i=D.parse(e),n=[];for(const e of i){const r=this._parseMessage(e,t);r&&n.push(r)}return n}writeMessage(e){switch(e.type){case z.MessageType.Invocation:return this._writeInvocation(e);case z.MessageType.StreamInvocation:return this._writeStreamInvocation(e);case z.MessageType.StreamItem:return this._writeStreamItem(e);case z.MessageType.Completion:return this._writeCompletion(e);case z.MessageType.Ping:return D.write(P);case z.MessageType.CancelInvocation:return this._writeCancelInvocation(e);default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const r=this._decoder.decode(e);if(0===r.length||!(r instanceof Array))throw new Error("Invalid payload.");const i=r[0];switch(i){case z.MessageType.Invocation:return this._createInvocationMessage(this._readHeaders(r),r);case z.MessageType.StreamItem:return this._createStreamItemMessage(this._readHeaders(r),r);case z.MessageType.Completion:return this._createCompletionMessage(this._readHeaders(r),r);case z.MessageType.Ping:return this._createPingMessage(r);case z.MessageType.Close:return this._createCloseMessage(r);default:return t.log(z.LogLevel.Information,"Unknown message type '"+i+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:z.MessageType.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:z.MessageType.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const r=t[2];return r?{arguments:t[4],headers:e,invocationId:r,streamIds:[],target:t[3],type:z.MessageType.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:z.MessageType.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:z.MessageType.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const r=t[3];if(r!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let i,n;switch(r){case this._errorResult:i=t[4];break;case this._nonVoidResult:n=t[4]}return{error:i,headers:e,invocationId:t[2],result:n,type:z.MessageType.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([z.MessageType.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([z.MessageType.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),D.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([z.MessageType.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([z.MessageType.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),D.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([z.MessageType.StreamItem,e.headers||{},e.invocationId,e.item]);return D.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let r;switch(t){case this._errorResult:r=this._encoder.encode([z.MessageType.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:r=this._encoder.encode([z.MessageType.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:r=this._encoder.encode([z.MessageType.Completion,e.headers||{},e.invocationId,t,e.result])}return D.write(r.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([z.MessageType.CancelInvocation,e.headers||{},e.invocationId]);return D.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}const O="7.0.5"})(),n})(),"object"==typeof exports&&"object"==typeof module?module.exports=t(require("signalR")):"function"==typeof define&&define.amd?define(["signalR"],t):"object"==typeof exports?exports.msgpack=t(require("signalR")):(e.signalR=e.signalR||{},e.signalR.protocols=e.signalR.protocols||{},e.signalR.protocols.msgpack=t(e.signalR)); +var e,t;e=self,t=e=>(()=>{var t=[,t=>{t.exports=e}],r={};function i(e){var n=r[e];if(void 0!==n)return n.exports;var s=r[e]={exports:{}};return t[e](s,s.exports,i),s.exports}i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{i.r(n),i.d(n,{MessagePackHubProtocol:()=>R,VERSION:()=>O});var e=4294967295;function t(e,t,r){var i=Math.floor(r/4294967296),n=r;e.setUint32(t,i),e.setUint32(t+4,n)}function r(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var s=("undefined"==typeof process||"never"!==process.env.TEXT_ENCODING)&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function o(e){for(var t=e.length,r=0,i=0;i=55296&&n<=56319&&i65535&&(u-=65536,s.push(u>>>10&1023|55296),u=56320|1023&u),s.push(u)}else s.push(a);s.length>=4096&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(o+=String.fromCharCode.apply(String,s)),o}var f,p=s?new TextDecoder:null,l=s?"undefined"!=typeof process&&"force"!==process.env.TEXT_DECODER?200:0:e,d=function(e,t){this.type=e,this.data=t},y=(f=function(e,t){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},f(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}f(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),w=function(e){function t(r){var i=e.call(this,r)||this,n=Object.create(t.prototype);return Object.setPrototypeOf(i,n),Object.defineProperty(i,"name",{configurable:!0,enumerable:!1,value:t.name}),i}return y(t,e),t}(Error),g={type:-1,encode:function(e){var r,i,n,s;return e instanceof Date?function(e){var r,i=e.sec,n=e.nsec;if(i>=0&&n>=0&&i<=17179869183){if(0===n&&i<=4294967295){var s=new Uint8Array(4);return(r=new DataView(s.buffer)).setUint32(0,i),s}var o=i/4294967296,a=4294967295&i;return s=new Uint8Array(8),(r=new DataView(s.buffer)).setUint32(0,n<<2|3&o),r.setUint32(4,a),s}return s=new Uint8Array(12),(r=new DataView(s.buffer)).setUint32(0,n),t(r,4,i),s}((r=e.getTime(),i=Math.floor(r/1e3),n=1e6*(r-1e3*i),s=Math.floor(n/1e9),{sec:i+s,nsec:n-1e9*s})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var i=t.getUint32(0);return{sec:4294967296*(3&i)+t.getUint32(4),nsec:i>>>2};case 12:return{sec:r(t,4),nsec:t.getUint32(0)};default:throw new w("Unrecognized data size for timestamp (expected 4, 8, or 12): "+e.length)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},v=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(g)}return e.prototype.register=function(e){var t=e.type,r=e.encode,i=e.decode;if(t>=0)this.encoders[t]=r,this.decoders[t]=i;else{var n=1+t;this.builtInEncoders[n]=r,this.builtInDecoders[n]=i}},e.prototype.tryToEncode=function(e,t){for(var r=0;rthis.maxDepth)throw new Error("Too deep objects in depth "+t);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: "+e+" bytes in UTF-8");this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>h){var t=o(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),c(e,this.bytes,this.pos),this.pos+=t}else t=o(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,r){for(var i=e.length,n=r,s=0;s>6&31|192;else{if(o>=55296&&o<=56319&&s>12&15|224,t[n++]=o>>6&63|128):(t[n++]=o>>18&7|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128)}t[n++]=63&o|128}else t[n++]=o}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var r=this.extensionCodec.tryToEncode(e,this.context);if(null!=r)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: "+Object.prototype.toString.apply(e));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: "+t);this.writeU8(198),this.writeU32(t)}var r=m(e);this.writeU8a(r)},e.prototype.encodeArray=function(e,t){var r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large array: "+r);this.writeU8(221),this.writeU32(r)}for(var i=0,n=e;i0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,r){e:for(var i=0,n=this.caches[r-1];i=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)},e.prototype.decode=function(e,t,r){var i=this.find(e,t,r);if(null!=i)return this.hit++,i;this.miss++;var n=u(e,t,r),s=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(s,n),n},e}(),x=function(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{h(i.next(e))}catch(e){s(e)}}function a(e){try{h(i.throw(e))}catch(e){s(e)}}function h(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}h((i=i.apply(e,t||[])).next())}))},S=function(e,t){var r,i,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,i&&(n=2&s[0]?i.return:s[0]?i.throw||((n=i.return)&&n.call(i),0):i.next)&&!(n=n.call(i,s[1])).done)return n;switch(i=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((n=(n=o.trys).length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]1||a(e,t)}))})}function a(e,t){try{(r=n[e](t)).value instanceof _?Promise.resolve(r.value.v).then(h,c):u(s[0][2],r)}catch(e){u(s[0][3],e)}var r}function h(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}},T=new DataView(new ArrayBuffer(0)),B=new Uint8Array(T.buffer),A=function(){try{T.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),L=new A("Insufficient data"),C=new I,k=function(){function t(t,r,i,n,s,o,a,h){void 0===t&&(t=v.defaultCodec),void 0===r&&(r=void 0),void 0===i&&(i=e),void 0===n&&(n=e),void 0===s&&(s=e),void 0===o&&(o=e),void 0===a&&(a=e),void 0===h&&(h=C),this.extensionCodec=t,this.context=r,this.maxStrLength=i,this.maxBinLength=n,this.maxArrayLength=s,this.maxMapLength=o,this.maxExtLength=a,this.keyDecoder=h,this.totalPos=0,this.pos=0,this.view=T,this.bytes=B,this.headByte=-1,this.stack=[]}return t.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},t.prototype.setBuffer=function(e){this.bytes=m(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=m(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},t.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),r=m(e),i=new Uint8Array(t.length+r.length);i.set(t),i.set(r,t.length),this.setBuffer(i)}else this.setBuffer(e)},t.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},t.prototype.createExtraByteError=function(e){var t=this.view,r=this.pos;return new RangeError("Extra "+(t.byteLength-r)+" of "+t.byteLength+" byte(s) found at buffer["+e+"]")},t.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},t.prototype.decodeMulti=function(e){return S(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},t.prototype.decodeAsync=function(e){var t,r,i,n;return x(this,void 0,void 0,(function(){var s,o,a,h,c,u,f,p;return S(this,(function(l){switch(l.label){case 0:s=!1,l.label=1;case 1:l.trys.push([1,6,7,12]),t=E(e),l.label=2;case 2:return[4,t.next()];case 3:if((r=l.sent()).done)return[3,5];if(a=r.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{o=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof A))throw e}this.totalPos+=this.pos,l.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return h=l.sent(),i={error:h},[3,12];case 7:return l.trys.push([7,,10,11]),r&&!r.done&&(n=t.return)?[4,n.call(t)]:[3,9];case 8:l.sent(),l.label=9;case 9:return[3,11];case 10:if(i)throw i.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,o]}throw u=(c=this).headByte,f=c.pos,p=c.totalPos,new RangeError("Insufficient data in parsing "+U(u)+" at "+p+" ("+f+" in the current buffer)")}}))}))},t.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},t.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},t.prototype.decodeMultiAsync=function(e,t){return M(this,arguments,(function(){var r,i,n,s,o,a,h,c,u;return S(this,(function(f){switch(f.label){case 0:r=t,i=-1,f.label=1;case 1:f.trys.push([1,13,14,19]),n=E(e),f.label=2;case 2:return[4,_(n.next())];case 3:if((s=f.sent()).done)return[3,12];if(o=s.value,t&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(i=this.readArraySize(),r=!1,this.complete()),f.label=4;case 4:f.trys.push([4,9,,10]),f.label=5;case 5:return[4,_(this.doDecodeSync())];case 6:return[4,f.sent()];case 7:return f.sent(),0==--i?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=f.sent())instanceof A))throw a;return[3,10];case 10:this.totalPos+=this.pos,f.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return h=f.sent(),c={error:h},[3,19];case 14:return f.trys.push([14,,17,18]),s&&!s.done&&(u=n.return)?[4,_(u.call(n))]:[3,16];case 15:f.sent(),f.label=16;case 16:return[3,18];case 17:if(c)throw c.error;return[7];case 18:return[7];case 19:return[2]}}))}))},t.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(i=e-128)){this.pushMapState(i),this.complete();continue e}t={}}else if(e<160){if(0!=(i=e-144)){this.pushArrayState(i),this.complete();continue e}t=[]}else{var r=e-160;t=this.decodeUtf8String(r,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)r=this.lookU8(),t=this.decodeUtf8String(r,1);else if(218===e)r=this.lookU16(),t=this.decodeUtf8String(r,2);else if(219===e)r=this.lookU32(),t=this.decodeUtf8String(r,4);else if(220===e){if(0!==(i=this.readU16())){this.pushArrayState(i),this.complete();continue e}t=[]}else if(221===e){if(0!==(i=this.readU32())){this.pushArrayState(i),this.complete();continue e}t=[]}else if(222===e){if(0!==(i=this.readU16())){this.pushMapState(i),this.complete();continue e}t={}}else if(223===e){if(0!==(i=this.readU32())){this.pushMapState(i),this.complete();continue e}t={}}else if(196===e){var i=this.lookU8();t=this.decodeBinary(i,1)}else if(197===e)i=this.lookU16(),t=this.decodeBinary(i,2);else if(198===e)i=this.lookU32(),t=this.decodeBinary(i,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)i=this.lookU8(),t=this.decodeExtension(i,1);else if(200===e)i=this.lookU16(),t=this.decodeExtension(i,2);else{if(201!==e)throw new w("Unrecognized type byte: "+U(e));i=this.lookU32(),t=this.decodeExtension(i,4)}this.complete();for(var n=this.stack;n.length>0;){var s=n[n.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;n.pop(),t=s.array}else{if(1===s.type){if(o=void 0,"string"!=(o=typeof t)&&"number"!==o)throw new w("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new w("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}n.pop(),t=s.map}}return t}var o},t.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},t.prototype.complete=function(){this.headByte=-1},t.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new w("Unrecognized array type byte: "+U(e))}},t.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new w("Max length exceeded: map length ("+e+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},t.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new w("Max length exceeded: array length ("+e+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:e,array:new Array(e),position:0})},t.prototype.decodeUtf8String=function(e,t){var r;if(e>this.maxStrLength)throw new w("Max length exceeded: UTF-8 byte length ("+e+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLengthl?function(e,t,r){var i=e.subarray(t,t+r);return p.decode(i)}(this.bytes,n,e):u(this.bytes,n,e),this.pos+=t+e,i},t.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},t.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new w("Max length exceeded: bin length ("+e+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(e+t))throw L;var r=this.pos+t,i=this.bytes.subarray(r,r+e);return this.pos+=t+e,i},t.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new w("Max length exceeded: ext length ("+e+") > maxExtLength ("+this.maxExtLength+")");var r=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,r,this.context)},t.prototype.lookU8=function(){return this.view.getUint8(this.pos)},t.prototype.lookU16=function(){return this.view.getUint16(this.pos)},t.prototype.lookU32=function(){return this.view.getUint32(this.pos)},t.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},t.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},t.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},t.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},t.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},t.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},t.prototype.readU64=function(){var e,t,r=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,r},t.prototype.readI64=function(){var e=r(this.view,this.pos);return this.pos+=8,e},t.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},t.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},t}(),z=i(1);class D{static write(e){let t=e.byteLength||e.length;const r=[];do{let e=127&t;t>>=7,t>0&&(e|=128),r.push(e)}while(t>0);t=e.byteLength||e.length;const i=new Uint8Array(r.length+t);return i.set(r,0),i.set(e,r.length),i.buffer}static parse(e){const t=[],r=new Uint8Array(e),i=[0,7,14,21,28];for(let n=0;n7)throw new Error("Messages bigger than 2GB are not supported.");if(!(r.byteLength>=n+o+a))throw new Error("Incomplete message.");t.push(r.slice?r.slice(n+o,n+o+a):r.subarray(n+o,n+o+a)),n=n+o+a}return t}}const P=new Uint8Array([145,z.MessageType.Ping]);class R{constructor(e){this.name="messagepack",this.version=1,this.transferFormat=z.TransferFormat.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new b(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new k(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(r=e)||"undefined"==typeof ArrayBuffer||!(r instanceof ArrayBuffer||r.constructor&&"ArrayBuffer"===r.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var r;null===t&&(t=z.NullLogger.instance);const i=D.parse(e),n=[];for(const e of i){const r=this._parseMessage(e,t);r&&n.push(r)}return n}writeMessage(e){switch(e.type){case z.MessageType.Invocation:return this._writeInvocation(e);case z.MessageType.StreamInvocation:return this._writeStreamInvocation(e);case z.MessageType.StreamItem:return this._writeStreamItem(e);case z.MessageType.Completion:return this._writeCompletion(e);case z.MessageType.Ping:return D.write(P);case z.MessageType.CancelInvocation:return this._writeCancelInvocation(e);default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const r=this._decoder.decode(e);if(0===r.length||!(r instanceof Array))throw new Error("Invalid payload.");const i=r[0];switch(i){case z.MessageType.Invocation:return this._createInvocationMessage(this._readHeaders(r),r);case z.MessageType.StreamItem:return this._createStreamItemMessage(this._readHeaders(r),r);case z.MessageType.Completion:return this._createCompletionMessage(this._readHeaders(r),r);case z.MessageType.Ping:return this._createPingMessage(r);case z.MessageType.Close:return this._createCloseMessage(r);default:return t.log(z.LogLevel.Information,"Unknown message type '"+i+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:z.MessageType.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:z.MessageType.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const r=t[2];return r?{arguments:t[4],headers:e,invocationId:r,streamIds:[],target:t[3],type:z.MessageType.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:z.MessageType.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:z.MessageType.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const r=t[3];if(r!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let i,n;switch(r){case this._errorResult:i=t[4];break;case this._nonVoidResult:n=t[4]}return{error:i,headers:e,invocationId:t[2],result:n,type:z.MessageType.Completion}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([z.MessageType.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([z.MessageType.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),D.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([z.MessageType.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([z.MessageType.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),D.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([z.MessageType.StreamItem,e.headers||{},e.invocationId,e.item]);return D.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let r;switch(t){case this._errorResult:r=this._encoder.encode([z.MessageType.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:r=this._encoder.encode([z.MessageType.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:r=this._encoder.encode([z.MessageType.Completion,e.headers||{},e.invocationId,t,e.result])}return D.write(r.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([z.MessageType.CancelInvocation,e.headers||{},e.invocationId]);return D.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}const O="7.0.9"})(),n})(),"object"==typeof exports&&"object"==typeof module?module.exports=t(require("signalR")):"function"==typeof define&&define.amd?define(["signalR"],t):"object"==typeof exports?exports.msgpack=t(require("signalR")):(e.signalR=e.signalR||{},e.signalR.protocols=e.signalR.protocols||{},e.signalR.protocols.msgpack=t(e.signalR)); //# sourceMappingURL=signalr-protocol-msgpack.min.js.map /*! * html2canvas 1.0.0 diff --git a/src/modules/mix.portal/Domain/Services/MixApplicationService.cs b/src/modules/mix.portal/Domain/Services/MixApplicationService.cs index a35c43e45..a65c528d3 100644 --- a/src/modules/mix.portal/Domain/Services/MixApplicationService.cs +++ b/src/modules/mix.portal/Domain/Services/MixApplicationService.cs @@ -63,11 +63,14 @@ private async Task CreateTemplate(string name, string appF { var indexFile = MixFileHelper.GetFileByFullName($"{appFolder}/index.html"); Regex regex = new("((?<=src=\")|(?<=href=\"))(?!(http[^\\s]+))(.+?)(\\.+?)"); + Regex baseHrefRegex = new("(base href=\"(.+?)\")"); if (indexFile.Content != null && regex.IsMatch(indexFile.Content)) { - indexFile.Content = regex.Replace(indexFile.Content, $"/{appFolder}/$3$4") + indexFile.Content = regex.Replace(indexFile.Content, $"/{appFolder}/$3$4"); + indexFile.Content = baseHrefRegex.Replace(indexFile.Content, $"base href=\"/app/{baseRoute}\"") .Replace("[baseRoute]", $"/app/{baseRoute}") + .Replace("base href=\"/\"", $"/app/{baseRoute}") //.Replace("[baseHref]", appFolder) .Replace("options['baseRoute']", $"'/app/{baseRoute}'") .Replace("options['baseHref']", $"'{appFolder}'");