'use strict'; var statuses = {'new': 'Новая анкета', 'filled': 'Анкета заполнена, но не отправлена', 'proverka': 'На проверке'}; // var statuses_without_done = clone(statuses); // delete statuses_without_done['done']; // delete statuses_without_done['initial']; var roles_titles = {'administrator': 'Член жюри'}; var c_roles = {}; // var $_education_levels = {high: 'Высшее образование', spo: 'СПО', mid: 'Среднее образование'}; var c_access = ''; var c_login = ''; var c_sharp = ''; var c_id = 0; var CUR_YEAR = new Date().getFullYear(); // var $_roles = {}; if (Object.keys(c_roles).length == 0) c_roles = {}; // CL(c_roles); var MONTHS = [ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь' ]; function empty(val) { return !val || !val.length; } function prepareNumber(val) { // CL('prepareNumber'); if (isEmpty(val)) { // CL('empty'); return 0; } else { // CL('here'); return parseFloat(onlyDigits(val)); // parseFloat(val.replace(/,/g, '.').replace(/[A-Za-zа-яА-Я]/g, '')); } } // returns string function onlyDigits(val) { val = val.toString(); return val.replace(/[^0-9.,]*/g, '').replace(/[.,]+/g, '.').replace(/(\.\d{2})\d+/g, '$1'); } function isEmpty(val) { return val === null || val === undefined || (new String(val)).length == 0 || val === '-'; } function isEmptyObject(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object } function MysqlToDE($date) { var dateArr = $date.split('-'); return dateArr[2] + "." + dateArr[1] + "." + dateArr[0]; } // https://stackoverflow.com/questions/10015027/javascript-tofixed-not-rounding // returns string function toFixed(number, decimals) { var x = Math.pow(10, Number(decimals) + 1); return (Number(number) + (1 / x)).toFixed(decimals) } // returns string function roundToTwo(num) { return toFixed(+(Math.round(num + "e+2") + "e-2"), 2); } Array.prototype.in_array = function(p_val) { for(var i = 0, l = this.length; i < l; i++) { if(this[i] == p_val) { return true; } } return false; } if (!String.prototype.trim) { (function() { // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function() { return this.replace(rtrim, ''); }; })(); } function monthDiff(d1, d2) { var months; months = (d2.getFullYear() - d1.getFullYear()) * 12; months -= d1.getMonth(); months += d2.getMonth() + 1; return months <= 0 ? 0 : months; } function strip_tags(str){ return str .replace(/(<(br[^>]*)>)/ig, '\n') .replace(/(<([^>]+)>)/ig,''); } function replaceComma(value) { if (value) return value.replace(',', '.'); else return ''; // CL(value); } function findById(obj, id) { for (var key in obj) { if (parseInt(obj[key].id) == id) return obj[key]; // else CL(obj[key].id + " != " + id); } return null; } function findKeyByValue(obj, val) { for (var key in obj) { if (obj[key] == val) return key; } return null; } function findByColumn(arr, column, value) { for (var i = 0; i < arr.length; i++) { if (arr[i][column] == value) { return arr[i]; } } } function deleteByColumn(arr, column, value) { for (var i = 0; i < arr.length; i++) { if (arr[i][column] == value) { arr.splice(i, 1); // CL(i); return; } } } function clone(obj) { var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } function getExtension(filename) { var name_parts = filename.split('.'); return name_parts[name_parts.length - 1]; } function getRandom(min, max) { return Math.random() * (max - min) + min; } //**************************************** // https://amsul.ca/pickadate.js/ angular.module('app', ['ngRoute', 'ngDialog', 'angularSpinners', 'ngMask', 'angularFileUpload', 'ngSanitize', 'toastr', 'ngAnimate', 'angucomplete-alt', 'pickadate']) // .constant('system_start_year', 2023) // http://oncodesign.io/2014/02/19/safely-prevent-template-caching-in-angularjs/ .run(function($rootScope, $templateCache) { $rootScope.$on('$routeChangeStart', function(event, next, current) { if (typeof(current) !== 'undefined'){ $templateCache.remove(current.templateUrl); } }); }) .config(['$routeProvider', '$locationProvider', 'toastrConfig', /*'uiMask.ConfigProvider',*/ function ($routeProvider, $locationProvider, toastrConfig) { angular.extend(toastrConfig, { autoDismiss: false, containerId: 'toast-container', maxOpened: 0, newestOnTop: true, positionClass: 'toast-bottom-right', preventDuplicates: false, preventOpenDuplicates: true, target: 'html', // debug: true, // timeOut: 500000 }); $locationProvider.hashPrefix(''); $routeProvider .when('/', { templateUrl: 'index.tpl.html?' + getRandom(10000, 99999), controller: 'IndexCtrl', resolve: { anketa: function($http) { if (c_id) return $http({url: 'ajax/get/get_anketa.php', method: 'GET', params: {}}); else return {data: {}}; }, admin: function() { return false; }, redirect_anketa_id: function() { return null; } } }) .when('/admin', { templateUrl: 'index.tpl.html?' + getRandom(10000, 99999), controller: 'IndexCtrl', resolve: { anketa: function($http) { return {data: {}}; }, admin: function() { return true; }, redirect_anketa_id: function() { return null; } } }) // для того чтобы после авторизации сразу перейти к нужной анкете (чтобы из письма удобно переходить, когда авторизация уже слетела) .when('/admin/anketa/:id', { templateUrl: 'index.tpl.html?' + getRandom(10000, 99999), controller: 'IndexCtrl', resolve: { anketa: function($http) { return {data: {}}; }, admin: function() { return true; }, redirect_anketa_id: function($route) { return $route.current.params.id; } } }) // Для проверки .when('/proverka', { // конкретный статус используется для роли факультет templateUrl: 'registrants.tpl.php?status=proverka&' + getRandom(10000, 99999), controller: 'RegistrantsCtrl', resolve: { params: function() { return {status: 'proverka'}; } } }) // Проверенные .when('/done', { // конкретный статус используется для роли факультет templateUrl: 'registrants.tpl.php?status=done&' + getRandom(10000, 99999), controller: 'RegistrantsCtrl', resolve: { params: function() { return {status: 'done'}; } } }) // Заполняемые .when('/new', { templateUrl: 'registrants.tpl.php?status=new&' + getRandom(10000, 99999), controller: 'RegistrantsCtrl', resolve: { params: function() { return {status: 'new'}; } } }) .when('/anketa/:id', { templateUrl: 'index.tpl.html?' + getRandom(10000, 99999), controller: 'IndexCtrl', resolve: { anketa: function(LDialog, $route, $http) { return $http({url: 'ajax/get/get_anketa.php', method: 'GET', params: {id: $route.current.params.id}}); }, sprav: function($http) { return $http({url: 'ajax/get/sprav.php', method: 'GET', params: {}}); }, admin: function() { return true; }, // anketa_id: function($route) // { // return $route.current.params.id // }, redirect_anketa_id: function($route) { return null; } } }) .when('/users', { templateUrl: 'users.tpl.html?' + getRandom(10000, 99999), controller: 'UsersCtrl', resolve: { // Departments: function(LDialog, $route, $http) // { // return $http({url: 'ajax/get/departments.php', method: 'GET', params: {}}); // }, Users: function(LDialog, $route, $http) { return $http({url: 'ajax/get/users.php', method: 'GET', params: {}}); } } }) // Заполняемые .when('/reports', { templateUrl: 'reports.tpl.php?' + getRandom(10000, 99999), controller: 'ReportsCtrl' }) .when('/registration', { templateUrl: 'registration.tpl.html?' + getRandom(10000, 99999), controller: 'RegistrationCtrl', resolve: { forgot: function() { return false } } }) .when('/registration/forgot', { templateUrl: 'registration.tpl.html?' + getRandom(10000, 99999), controller: 'RegistrationCtrl', resolve: { forgot: function() { return true } } }) .otherwise( { template: 'Страница не найдена' }); }]) //Главный контроллер .controller ('AppCtrl', function($scope, $rootScope, ngDialog) { CL('AppCtrl') $rootScope.c_roles = c_roles; $rootScope.statuses = statuses; $rootScope.c_login = c_login; $rootScope.c_sharp = c_sharp; // if (c_access == 'full') window.location = '#/users'; // CL(c_roles); // $rootScope.statuses = statuses; // var cur_date = new Date(); // var cur_month = cur_date.getMonth(); // $scope.$on('$routeChangeSuccess', function() { // $scope.selected_year = $route.current.params.year; // }); $rootScope.min_date = new Date(CUR_YEAR - 90, 0, 1); $rootScope.max_date = new Date(CUR_YEAR - 0, 11, 31); // CL($scope.max_date); $rootScope.pickDateOptions = { monthsFull: MONTHS, monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdaysFull: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'], weekdaysShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пн', 'Сб'], showMonthsShort: undefined, showWeekdaysFull: undefined, firstDay: 1, selectYears: 90 - 16, today: 'Сегодня', clear: 'Очистить', close: 'Закрыть', format: 'dd.mm.yyyy', formatSubmit: 'dd.mm.yyyy', // 'yyyy-mm-dd', editable: true, onSet: function(context) { if (context['select']) { // var selectedDate = new Date(context['select']); // CL(selectedDate); // CheckTermDates(context); } } }; $rootScope.pickTimeOptions = { clear: '', format: 'HH:i', interval: 10, // editable: true }; $rootScope.ShowSoglasie = function() { $scope.show_pdn_dialog_close_button = true; ngDialog.open({ template: "pdn.tpl.html" + "?" + getRandom(10000, 99999), scope: $scope, plain: false, disableAnimation: true, className: 'ngdialog-theme-default history' }) return true; } }) // Анкета кандидата (интерфейс кандидата) // Также формы авторизации кандидата и администратора // redirect_anketa_id - для быстрого перехода (администратора) к анкете кандидата после авторизации .controller ('IndexCtrl', function($scope, $rootScope, anketa, FileUploader, toastr, $http, spinnerService, $interval, admin, ngDialog, $templateCache, redirect_anketa_id, LDialog) { // if (c_access == 'full') window.location = '#/'; CL('IndexCtrl'); // CL(c_id); $templateCache.put('confirm_delete', '

Вы уверены, что хотите удалить?

\
\ \ \
'); $rootScope.page = 'index'; $scope.c_login = c_login; $scope.c_id = c_id; $scope.anketa = anketa.data; $scope.auth = {}; $scope.statuses = statuses; $scope.admin = admin; // $scope.c_department_id = c_department_id; // $scope.$_1c_education_levels = $_1c_education_levels; $scope.c_roles = c_roles; // CL(c_roles); if (c_roles.administrator && !$scope.anketa.id) window.location = '/proverka'; // CL($scope.anketa.type); function InitAdds() { $scope.anketa.show_add_costs_equipment = false; $scope.anketa.show_add_costs_rental= false; $scope.anketa.show_add_costs_food = false; $scope.anketa.show_add_costs_promotion = false; $scope.anketa.show_add_costs_additional = false; $scope.add_costs_equipment = {}; $scope.add_costs_rental = {}; $scope.add_costs_food = {}; $scope.add_costs_promotion = {}; $scope.add_costs_additional = {}; } $scope.isEmptyObject = function(obj) { // CL('isEmptyObject'); return isEmptyObject(obj) } InitAdds(); // // if (!c_id && c_access == 'admin') window.location = "/#/registrants"; $scope.Auth = function() { $http({url: 'ajax/post/auth.php', method: 'POST', data: $scope.auth}) .then(function(result) { if (result.data.result == 'success') { if (redirect_anketa_id) { // CL(1); window.location = "/anketa/" + redirect_anketa_id; } else { // CL(3); window.location = "/" ; } } else { toastr.error("Вы ввели неправильный логин или пароль"); } }); } // Fix bug when can not reupload the same file FileUploader.FileSelect.prototype.isEmptyAfterSelection = function() { return true }; function prepareBirthDate() { var dateArr = []; if ($scope.anketa.birth_date) dateArr = $scope.anketa.birth_date.split('.'); if (dateArr.length) $scope.anketa.birth_date_obj = new Date(dateArr[2], dateArr[1] - 1, dateArr[0]); } prepareBirthDate(); // dateArr = []; // if ($scope.anketa.passport_kogda) dateArr = $scope.anketa.passport_kogda.split('.'); // if (dateArr.length) $scope.anketa.passport_kogda_obj = new Date(dateArr[2], dateArr[1] - 1, dateArr[0]); $scope.MayEditAnketa = function() { return c_roles.participant && ($scope.anketa.status == 'new' || $scope.anketa.status == 'filled'); } $scope.SaveAnketa = function(silent, status) { // валидация $scope.anketa.valid = true; if (!silent) { $scope.anketa.save_pressed = true; } // CL($scope.anketa.save_pressed); // CL($scope.anketa.save_pressed); // if (empty($scope.anketa.surname)) $scope.anketa.valid = false; // if (empty($scope.anketa.name)) $scope.anketa.valid = false; // if (!$scope.anketa.no_patronymic && empty($scope.anketa.patronymic)) $scope.anketa.valid = false; if (empty($scope.anketa.fio)) $scope.anketa.valid = false; if (empty($scope.anketa.birth_date)) $scope.anketa.valid = false; if (empty($scope.anketa.e_mail)) $scope.anketa.valid = false; if (empty($scope.anketa.phone)) $scope.anketa.valid = false; // if (empty($scope.anketa.vo)) $scope.anketa.valid = false; // -- если человек не найден в кадрах, то обязательная за // if (!$scope.anketa.login && empty($scope.anketa.files['vo'])) $scope.anketa.valid = false; // commented Rotkov // if (!$scope.anketa.login && empty($scope.anketa.files['trudovaya'])) $scope.anketa.valid = false; if (empty($scope.anketa.files['brochure'])) $scope.anketa.valid = false; if (empty($scope.anketa.files['map'])) $scope.anketa.valid = false; // if (empty($scope.anketa.passport_num)) $scope.anketa.valid = false; // if (empty($scope.anketa.passport_seria)) $scope.anketa.valid = false; // if (empty($scope.anketa.passport_kem)) $scope.anketa.valid = false; // if (empty($scope.anketa.passport_kogda)) $scope.anketa.valid = false; // if (empty($scope.anketa.passport_address)) $scope.anketa.valid = false; // if (empty($scope.anketa.passport_podrazdelenie)) $scope.anketa.valid = false; if (empty($scope.anketa.vuz)) $scope.anketa.valid = false; if (empty($scope.anketa.napravlenie)) $scope.anketa.valid = false; if (empty($scope.anketa.education_level)) $scope.anketa.valid = false; //if (empty($scope.anketa.files['passport'])) $scope.anketa.valid = false; if (empty($scope.anketa.forma_obuchenia)) $scope.anketa.valid = false; // файл обязательный, только если СНИЛС не взят из 1С //if ($scope.anketa.snils_1c == '0' && empty($scope.anketa.files['snils'])) $scope.anketa.valid = false; if (empty($scope.anketa.title)) $scope.anketa.valid = false; //if (empty($scope.anketa.files['inn'])) $scope.anketa.valid = false; if (empty($scope.anketa.targets)) $scope.anketa.valid = false; // CL($scope.anketa.valid); if (empty($scope.anketa.length)) $scope.anketa.valid = false; if (empty($scope.anketa.time)) $scope.anketa.valid = false; if (empty($scope.anketa.route)) $scope.anketa.valid = false; if (empty($scope.anketa.activites)) $scope.anketa.valid = false; if (empty($scope.anketa.travel_means)) $scope.anketa.valid = false; if (empty($scope.anketa.audience_requirements)) $scope.anketa.valid = false; if (empty($scope.anketa.group_size)) $scope.anketa.valid = false; if (empty($scope.anketa.safety_requirements)) $scope.anketa.valid = false; if (empty($scope.anketa.motivation_strategies)) $scope.anketa.valid = false; if (empty($scope.anketa.leisure)) $scope.anketa.valid = false; if (empty($scope.anketa.inventory)) $scope.anketa.valid = false; if (empty($scope.anketa.staff)) $scope.anketa.valid = false; if (!$scope.anketa.costs_equipment.length) $scope.anketa.valid = false; if (!$scope.anketa.costs_rental.length) $scope.anketa.valid = false; if (!$scope.anketa.costs_food.length) $scope.anketa.valid = false; if (!$scope.anketa.costs_promotion.length) $scope.anketa.valid = false; if (!$scope.anketa.costs_additional.length) $scope.anketa.valid = false; // CL($scope.anketa.costs_equipment.length); // CL($scope.anketa.valid); // if (empty($scope.anketa.safety_requirements)) $scope.anketa.valid = false; // меняем статус в зависимости от валидности формы // СОХРАНЯЕТ КАНДИДАТ САМ if ($scope.anketa.status == 'new' && $scope.anketa.valid) $scope.anketa.new_status = 'filled'; else if ($scope.anketa.status == 'filled' && !$scope.anketa.valid) $scope.anketa.new_status = 'new'; // а в других статусах менять анкету нельзя { // CL($scope.anketa); // return; $http({url: 'ajax/post/save_anketa.php', method: 'POST', data: $scope.anketa}) .then(function(result) { if (result.data.result == 'success') { $scope.anketa.history = result.data.history; if (!silent) // здесь только тосты { if ($scope.anketa.valid) { if (!status && $scope.anketa.new_status == 'filled') { // toastr.success("Анкета перешла в статус \"Заполнена\" и отправлена на рассмотрение"); LDialog.success("Анкета полностью заполнена и может быть отправлена на проверку", {'size': 'sm'}); } else if (!status) { toastr.success("Анкета сохранена"); } // также сменим статус if (status) { $scope.SetStatus(status); } } else { toastr.warning("Анкета сохранена, но не все обязательные поля заполнены"); } } if ($scope.anketa.new_status) { $scope.anketa.status = $scope.anketa.new_status; $scope.anketa.new_status = ''; } $http({url: 'ajax/get/get_anketa.php', method: 'GET', params: {}}) .then(function(result) { var save_pressed = $scope.anketa.save_pressed; $scope.anketa = result.data; $scope.anketa.save_pressed = save_pressed; prepareBirthDate(); }); InitAdds(); } // else if (result.data.result == 'snils_exists') // { // toastr.error("Пользователь с данным СНИЛС уже существует. Запрещено создавать двойные учетные записи."); // } else { toastr.error("Ошибка сохранения"); } }); } } $scope.NewPhoneSendCode = function() { // CL($scope.anketa.new_phone); // return; if ($scope.anketa.new_phone.length < 11) { toastr.error("Некорректный ввод номера телефона"); return; } spinnerService.show('spinner'); $http({url: 'ajax/post/new_phone_send_code.php', method: 'POST', data: {phone: $scope.anketa.new_phone}}) .then(function(result) { if (result.data.exists == true) { toastr.error("Пользователь с таким телефоном уже зарегистрирован"); } else if (result.data.result == 'success') { $scope.anketa.submode_phone = 'input_code'; // TMP // $scope.anketa.new_phone_code = result.data.code; $scope.start_timer(); } // else spinnerService.hide('spinner'); }); } $scope.code_time = 0; var timer; $scope.start_timer = function() { $scope.code_time = 30; timer = $interval(function() { $scope.code_time--; if ($scope.code_time == 0) // таймер окончен { $scope.stop_timer(); } }, 1000); }; $scope.stop_timer = function() { //$scope.where_sent_code.mobile = undefined; if (angular.isDefined(timer)) { $interval.cancel(timer); timer = undefined; } }; $scope.NewPhoneCancel = function() { $scope.anketa.submode_phone = ''; $scope.anketa.new_phone_code = ''; $scope.anketa.new_phone = ''; } $scope.NewPhoneCheckCode = function() { $http({url: 'ajax/post/new_phone_check_code.php', method: 'POST', data: {code: $scope.anketa.new_phone_code}}) .then(function(result) { if (result.data.result == 'success') { toastr.success("Номер телефона изменён"); $scope.anketa.phone = $scope.anketa.new_phone; $scope.NewPhoneCancel(); } else { toastr.error("Неверный код"); } }); } var uploaderInit = { scope: $scope, url: 'ajax/post/file_upload.php', autoUpload: true }; // Инициализировать загрузчики файлов для анкеты кандидата // function InitAnketaUploaders() { CL('InitAnketaUploaders'); angular.forEach($scope.uploaders, function(obj, type) { // var init = clone(uploaderInit); // CL('InitAnketaUploaders: ' + type); uploaderInit.formData = [{anketa_id: $scope.anketa.id, type: type}]; $scope.uploaders[type] = new FileUploader(uploaderInit); $scope.uploaders[type].onErrorItem = function(item, response, status, headers) { $scope.uploaders[type].errorHappened = true; toastr.error("Ошибка при загрузке файла"); } $scope.uploaders[type].onCompleteAll = function() { if (!$scope.uploaders[type].errorHappened) { toastr.success("Файлы загружены"); $scope.SaveAnketa(); } this.clearQueue(); } $scope.uploaders[type].onSuccessItem = function(item, response, status, headers) { if (response.result == 'success') { if (!$scope.anketa.files) $scope.anketa.files = {}; if (!$scope.anketa.files[type]) $scope.anketa.files[type] = []; $scope.anketa.files[type].push(response.created_file); } else $scope.uploaders[type].errorHappened = true; } }); } $scope.uploaders = {map: {}, brochure: {}}; InitAnketaUploaders(); $scope.DeleteFile = function(file) { // CL($scope.anketa.files); $http({url: 'ajax/post/delete_file.php', method: 'GET', params: {hash: file.file_hash}}) .then(function(response) { if (response.data.result == 'success') { deleteByColumn($scope.anketa.files[file.type], 'id', file.id); toastr.success('Файл удалён'); $scope.SaveAnketa(); } else { toastr.error('Ошибка удаления файла'); } }); } // IndexCtrl $scope.CanViewAnketaHistory = function() { return true; } // История по Кандидату // IndexCtrl $scope.ShowAnketaHistory = function() { ngDialog.open({ template: "history_anketa.tpl.html" + "?" + getRandom(10000, 99999), scope: $scope, plain: false, disableAnimation: true, className: 'ngdialog-theme-default history' }); } $scope.DeleteRow = function(row, rows) { row.to_delete = true; $scope.SaveAnketa(true); // var index; // index = rows.indexOf(row); // // CL(index); // if (index !== undefined) // { // rows.splice(index, 1); // } } $scope.AddRowToTable = function(rows, row) { CL(row); if (row.price != undefined) { row.cost = row.quantity * row.price; } rows.push(row); InitAdds(); $scope.SaveAnketa(true); } // Расходы на оплату труда $scope.CalcCostsLaborTotal = function() { // CL('CalcCostsLaborTotal'); return $scope.anketa.costs_labor_total = roundToTwo(prepareNumber($scope.anketa.costs_labor_instructors) + prepareNumber($scope.anketa.costs_labor_excursions) + prepareNumber($scope.anketa.costs_labor_rukovoditel) + prepareNumber($scope.anketa.costs_labor_others)); } // Отчисления на социальное страхование $scope.CalcCostsInsurance = function() { return $scope.anketa.costs_insurance = prepareNumber($scope.anketa.costs_labor_total * 0.302); } // Всего затрат $scope.CalcCostsTotal = function() { var sum = prepareNumber($scope.anketa.costs_labor_total) + prepareNumber($scope.anketa.costs_insurance); // CL(sum); angular.forEach($scope.anketa.costs_equipment, function(row) { sum += prepareNumber(row.cost) }) angular.forEach($scope.anketa.costs_rental, function(row) { sum += prepareNumber(row.cost) }) angular.forEach($scope.anketa.costs_food, function(row) { sum += prepareNumber(row.cost) }) angular.forEach($scope.anketa.costs_promotion, function(row) { sum += prepareNumber(row.cost) }) angular.forEach($scope.anketa.costs_additional, function(row) { sum += prepareNumber(row.cost) }) // CL(sum); return $scope.anketa.costs_total = sum; } // удалить лишние символы $scope.onlyDigits = function(what) { $scope.anketa[what] = onlyDigits($scope.anketa[what]) } $scope.onlyDigitsInObj = function(row, prop) { row[prop] = onlyDigits(row[prop]); } // IndexCtrl $scope.SetStatus = function(status) { CL('SetStatus IndexCtrl'); if ($scope.anketa.valid) $http({url: 'ajax/post/set_status.php', method: 'POST', data: {anketa_id: $scope.anketa.id, status: status, message: $scope.anketa.new_message}}) .then(function(result) { $scope.show_progress = false; if (result.data.new_status) { $scope.anketa.status = result.data.new_status; $scope.anketa.history = result.data.history; if ($scope.anketa.status == 'proverka') { toastr.success("Анкета отправлена на проверку"); } } else { toastr.error("Произошла ошибка при установке статуса"); } $scope.anketa.push_set_status = false; }); } // Член Жюри сохраняет баллы для регистранта $scope.SaveBalls = function() { $http({url: 'ajax/post/save_balls.php', method: 'POST', data: {anketa_id: $scope.anketa.id, balls: $scope.anketa.balls}}) .then(function(result) { if (result.data.result != 'fail') { toastr.success("Баллы сохранены") } else { toastr.error("Произошла ошибка"); } }); } // По Ctrl-S сохраним var isCtrl = false; document.onkeyup=function(e){ if(e.keyCode == 17) isCtrl=false; } document.onkeydown=function(e){ if(e.keyCode == 17) isCtrl=true; if(e.keyCode == 83 && isCtrl == true) { $scope.SaveAnketa(false); return false; } } /* $scope.min_date = new Date(CUR_YEAR - 90, 0, 1); $scope.max_date = new Date(CUR_YEAR - 16, 11, 31); // CL($scope.max_date); $scope.pickDateOptions = { monthsFull: MONTHS, monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdaysFull: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'], weekdaysShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пн', 'Сб'], showMonthsShort: undefined, showWeekdaysFull: undefined, firstDay: 1, selectYears: 90 - 16, today: 'Сегодня', clear: 'Очистить', close: 'Закрыть', format: 'dd.mm.yyyy', formatSubmit: 'yyyy-mm-dd', editable: true, onSet: function(context) { if (context['select']) { // var selectedDate = new Date(context['select']); // CL(selectedDate); // CheckTermDates(context); } } }; */ // InitTermDates(); }) .controller ('RegistrantsCtrl', function($scope, $rootScope, LDialog, params) // , FileUploader, toastr, $http) { CL('RegistrantsCtrl'); // CL(params); if (!c_roles) window.location = '/'; if (params) { // if (params.status == 'all') // { // $rootScope.page = 'all'; // } // else // { // } $rootScope.page = params.status; CL($rootScope.page); } else { $rootScope.page = 'participants'; } }) .controller ('RegistrationCtrl', function($scope, $rootScope, $interval, toastr, $http, ngDialog, $templateCache, $timeout, spinnerService, LDialog, forgot) { CL('RegistrationCtrl'); $scope.rand = getRandom(10000, 99999); // признак, что забыл пароль, не нужен отказ в случае, если пользователь (телефон) в базе есть $scope.forgot = forgot; if (c_login) window.location = '/'; $scope.roles_titles = roles_titles; // $templateCache.put('confirm_delete', '

Вы уверены, что хотите удалить?

\ //
\ // \ // \ //
'); $rootScope.page = 'registration'; $scope.c_roles = c_roles; // $scope.phone = ''; $scope.registration = {}; $scope.submode = 'input_email'; $scope.data = {newpassword1: '', newpassword2: ''}; $scope.ShowPDN = function() { // if ($scope.registration.e_mail.length < 11) // { // toastr.error("Некорректный ввод"); // return; // } $scope.submode = 'pdn'; } $scope.ShowInputCode = function() { // if ($scope.registration.e_mail.length < 11) // { // toastr.error("Некорректный ввод"); // return; // } $scope.SendCode(); // $scope.submode = 'input_code'; } $scope.AgreePDN = function() { $scope.submode = 'input_password'; } $scope.CancelPDN = function() { window.location = '/'; } $scope.SendCode = function() { spinnerService.show('spinner'); $http({url: 'ajax/post/send_code.php', method: 'POST', data: $scope.registration}) .then(function(result) { if (result.data.already_registered && !$scope.forgot) { LDialog.error("Вы уже зарегистрированы. Войдите в систему.", {'size': 'sm'}); } else if (result.data.result == 'success') { $scope.submode = 'input_code'; // $scope.ShowPDN(); // TMP // $scope.code = result.data.code; $scope.start_timer(); } // else spinnerService.hide('spinner'); }); } $scope.code_time = 0; var timer; $scope.start_timer = function() { $scope.code_time = 30; timer = $interval(function() { $scope.code_time--; if ($scope.code_time == 0) // таймер окончен { $scope.stop_timer(); } }, 1000); }; $scope.stop_timer = function() { //$scope.where_sent_code.mobile = undefined; if (angular.isDefined(timer)) { $interval.cancel(timer); timer = undefined; } }; $scope.CheckCode = function() { $http({url: 'ajax/post/check_code.php', method: 'POST', data: {code: $scope.data.code}}) .then(function(result) { if (result.data.result == 'success') { // $scope.submode = 'input_password'; $scope.ShowPDN(); $scope.data.person = result.data.person; } else if (result.data.result == 'snils_exists') { toastr.error("Пользователь с данным СНИЛС уже существует. Запрещено создавать двойные учетные записи."); } else { toastr.error("Неверный код"); } }); } $scope.CheckPasswordRussian = function() { // есть русские буквы var russian_letters = $scope.data.newpassword1.match(/[а-яА-Я]/) != null; if (russian_letters) { $scope.russian_letters = true; } else { $scope.russian_letters = false; } } $scope.SetPassword = function(confirm_fio) { $scope.data.confirm_fio = confirm_fio; spinnerService.show('spinner'); $http({url: 'ajax/post/set_password.php', method: 'POST', data: $scope.data}) .then( function (data) { if (data.data.result != 'fail') { // TMP comment $scope.show_success_message = true; // TODO REMAKE // setTimeout(function() {window.location = '/'}, 3000); } else { LDialog.error("Ошибка сервера", {'size': 'sm'}); } spinnerService.hide('spinner'); }) ; } $scope.CheckPasswordAndFIO = function() { // CL($scope.data.newpassword1); if ($scope.data.newpassword1.length < 6 || $scope.data.newpassword2.length < 6) $scope.show_short_message = true; else $scope.show_short_message = false; if ($scope.data.newpassword1 != $scope.data.newpassword2) $scope.show_repeat_message = true; else $scope.show_repeat_message = false; // есть латинские буквы или цифры или спецсимволы (хотя бы из двух групп) var complexity = 0; if ($scope.data.newpassword1.match(/\d/) != null) complexity++; if ($scope.data.newpassword1.match(/[a-zA-Z]/) != null) complexity++; if ($scope.data.newpassword1.match(/[\'\{\}\[\]~`!@#\$%\^&\*\(\)_\+=:;\|\\/\?\.,-]/) != null) complexity++; // знак - д.б. последним if (complexity <= 1) $scope.simple = true; else $scope.simple = false; // задаём пароль if (!$scope.show_repeat_message && !$scope.show_short_message && !$scope.simple) { /*code: $scope.code,*/ // var data = {password: $scope.data.newpassword1 }; // code м.б. не нужен //if ($scope.person != undefined) data.login = $scope.person.cn; // м.б. не нужен // if ($scope.person.unnmobile) data.mobile = $scope.person.unnmobile; // if ($scope.person.unnmail) data.mail = $scope.person.unnmail; // по телефону был найден сотрудник, спросим, его ли ФИО if ($scope.data.person && !$scope.forgot) { $scope.submode = 'confirm_fio'; } else { $scope.SetPassword(); } } }; $scope.registrationRedirectRoot = function() { window.location = '/' } }) // END RegistrationCtrl .controller ('UsersCtrl', function($scope, $rootScope, toastr, $http, Users, ngDialog, $templateCache, $timeout) { CL('UsersCtrl'); if (!c_roles) window.location = '/'; // CL($_roles); $scope.roles_titles = roles_titles; $templateCache.put('confirm_delete', '

Вы уверены, что хотите удалить?

\
\ \ \
'); $rootScope.page = 'users'; $scope.c_roles = c_roles; $scope.Users = Users.data; // $scope.Departments = Departments.data; $scope.params = {}; function InitNewUser() { $scope.add_user = {roles: ['administrator']}; // придумаем логин вида adm*, инкрементировав число // $scope.Users var maxNumber = -1; // Начальное значение максимального числа for (var i = 0; i < $scope.Users.length; i++) { var match = $scope.Users[i].login.match(/\d{2}/); // Ищем двузначное число в свойстве login if (match) { var number = parseInt(match[0], 10); // Преобразуем строку в число if (number > maxNumber) { maxNumber = number; // Обновляем максимальное число, если нашли большее } } } if (maxNumber < 0) maxNumber = 0; // Вычисляем следующее число var nextNumber = (maxNumber + 1).toString().padStart(2, '0'); $scope.add_user.login = 'adm' + nextNumber; } InitNewUser(); // $scope.AddUser = function() // { // if (!$scope.Users) // { // $scope.Users = []; // } // if (!findByColumn($scope.Users, 'login', $scope.add_user.login)) // { // $scope.Users.push($scope.add_user); // } // // $scope.onControllerChanged(); // $scope.$broadcast('angucomplete-alt:clearInput', 'add_user'); // SaveUsers(); // } // CL($_roles); // CL(Departments); $scope.CanEdit = function() { return c_roles.superadmin; } $scope.SaveUser = function(user) { // CL($scope.add_user); // CL(user); if (!user.roles) user.roles = []; // CL(user); // признак нового пользователя if (!user.roles.length) { // CL(findByColumn($scope.Users, 'login', user.login)); if (findByColumn($scope.Users, 'login', user.login)) { toastr.warning("Такой администратор уже есть"); return; } if (user.role) { user.roles = [user.role]; } } $http({url: 'ajax/post/save_user.php', method: 'POST', data: user}) .then(function(result) { if (result.data.result == 'success') { toastr.success("Пользователь сохранен"); if (!findByColumn($scope.Users, 'login', user.login)) { $scope.Users.push($scope.add_user); } // $scope.onControllerChanged(); $scope.$broadcast('angucomplete-alt:clearInput', 'fio'); InitNewUser(); $scope.params.show_add_user = false; } else { toastr.error("Ошибка добавления"); } }); } $scope.DeleteUser = function(user) { ngDialog.openConfirm({ template: 'confirm_delete', className: 'ngdialog-theme-default', disableAnimation: true }).then(function (value) { // да $http({url: 'ajax/get/delete_user.php', method: 'GET', params: {login: user.login}}) .then(function(result) { if (result.data.result == 'success') { toastr.success("Пользователь удалён"); deleteByColumn($scope.Users, 'login', user.login); } }); }, function() {} ); } $scope.onSotrudnikSelect = function(data) { CL('onSotrudnikSelect'); // CL(data); if (data) { // CL(data); $scope.add_user.login = data.originalObject.login; $scope.add_user.person_id = data.originalObject.person_id; $scope.add_user.fio = data.originalObject.fio; } // CL($scope.add_user); } $scope.onSotrudnikChanged= function(data) { // $scope.add_user.login = $scope.add_user.fio = ''; CL('onSotrudnikChanged'); } $scope.focusOutSotrudnik = function() { CL('focusOutSotrudnik'); if (!$scope.add_user.login) { $scope.$broadcast('angucomplete-alt:clearInput', 'add_user'); } } $scope.ShowUserRoles = function(user) { var roles_titles_arr = []; angular.forEach(user.roles, function(role) { roles_titles_arr.push(roles_titles[role]); }) return roles_titles_arr.join(', '); } $scope.UserAddRole = function(user) { // CL(user.add_role); if (!user.roles.includes(user.add_role)) user.roles.push(user.add_role); user.add_role = undefined; user.show_add_role = false; $scope.SaveUser(user); } $scope.DeleteRole = function(user, role) { var key = findKeyByValue(user.roles, role); // CL(key); user.roles.splice(key, 1); // CL(user); $scope.SaveUser(user); } $scope.SetRoleFilter = function(role) { $scope.params.role_filter = role; } $scope.UserHasRole = function(user, role) { return user.roles.includes(role); } $scope.ChangeUserPassword = function(user) { $http({url: 'ajax/post/user_change_password.php', method: 'POST', data: user}) .then(function(result) { if (result.data.result == 'success') { toastr.success("Пароль изменён"); user.new_password = ''; } else { toastr.error("Ошибка"); } }); } }) .controller ('ReportsCtrl', function($scope, $rootScope, $http) { $rootScope.page = 'reports'; }) // End ReportsCtrl .factory('LDialog', function(ngDialog) { return { success: function(message) { ngDialog.open({ template: "

" + message + "

", plain: true, // disableAnimation: true, className: 'ngdialog-theme-success' }); }, error: function(message) { ngDialog.open({ template: "

" + message + "

", plain: true, // disableAnimation: true, className: 'ngdialog-theme-error' }); } }; }) .filter("nl2br", function($filter) { return function(data) { // CL(data.replace(/\\n/g, '
')); if (!data) return data; return data.replace(/\n/g, '
').replace(/\\n/g, '
'); }; }) .filter("jsDate", function () { return function (x) { if (!x || !x.length) return ''; var dateTimeArr = x.split(' '); var dateArr = dateTimeArr[0].split('-'); // var date = new Date(dateArr[0], dateArr[1] - 1, dateArr[2]); // return dateArr[2] + "." + dateArr[1] + "." + dateArr[0] + (dateTimeArr[1] ? (" " + dateTimeArr[1]) : ''); // return new Date(parseInt(x.substr(6))); }; }) // TODO to fix .filter("jsDateShort", function () { return function (x) { var dateTimeArr = x.split(' '); var dateArr = dateTimeArr[0].split('-'); var date = new Date(dateArr[0], dateArr[1] - 1, dateArr[2]); var result; // CL(dateTimeArr); // CL(dateArr); if (dateArr[2] != '00') // && MONTHS_ROD[dateArr[1] - 1]) { result = dateArr[2] + " " + dateArr[1] + (dateTimeArr[1] ? dateTimeArr[1].substring(0, 4) : '');// + " " + dateArr[0] + " г. " + (dateTimeArr[1] ? dateTimeArr[1] : ''); } else result = 'не известно'; return result; // return new Date(parseInt(x.substr(6))); }; }) .directive('numberInput', function() { return { require: 'ngModel', link: function(scope, elem, attrs, ngModelCtrl) { ngModelCtrl.$parsers.push(function(viewValue) { var transformedValue = viewValue.replace(/[^0-9,.]/g, ''); var commaIndex = transformedValue.indexOf(','); if (commaIndex !== -1) { transformedValue = transformedValue.substr(0, commaIndex + 1) + transformedValue.substr(commaIndex + 1).replace(/,/g, ''); } transformedValue = transformedValue.replace(/\./g, ','); // Ограничение числа до запятой до 9 var parts = transformedValue.split(','); if (parts[0] > 9) { transformedValue = 9 + ',' + parts[1].substring(0, 3); } // Ограничение числа знаков после запятой до трех var parts = transformedValue.split(','); if (parts.length > 1) { transformedValue = parts[0] + ',' + parts[1].substring(0, 3); } ngModelCtrl.$setViewValue(transformedValue); ngModelCtrl.$render(); return transformedValue; }); ngModelCtrl.$formatters.push(function(modelValue) { if (!modelValue) return modelValue; return modelValue.toString().replace(/\./g, ','); }); } }; }) .directive('focus', function() { return function(scope, elem, attr) { elem[0].focus(); }; }) .filter('pad', function() { return function(num, size) { return ('0' + num).substr(-size); }; }) .filter('currency', function() { return function(input) { // CL(input); return parseFloat(input).toFixed(2) + ' руб.'; // Пример форматирования }; }) // 9082312132 -> +7(908)231-21-32 .filter('mobile_filter', function() { return function(mobile) { if (mobile.length == 10) { var p1 = mobile.substr(0, 3); var p2 = mobile.substr(3, 3); var p3 = mobile.substr(6, 2); var p4 = mobile.substr(8, 2); return '+7(' + p1 + ')' + p2 + '-' + p3 + '-' + p4; } else return mobile; }; }) .factory('LDialog', function(ngDialog, $templateCache) { return { success: function(message) { ngDialog.open({ template: "

" + message + "

", plain: true, disableAnimation: true, className: 'ngdialog-theme-success' }); }, error: function(message) { ngDialog.open({ template: "

" + message + "

", plain: true, disableAnimation: true, className: 'ngdialog-theme-error' }); }, confirm_contact_approve: function(message, agree_confirm_contact_approve_fn) { $templateCache.put('confirm_contact_approve', '

' + message + '

\
\ \ \
'); ngDialog.openConfirm({ template: 'confirm_contact_approve', className: 'ngdialog-theme-plain' }).then( agree_confirm_contact_approve_fn, // нет function(reason) { } ); } }; }) .filter('range', function() { return function(input, total) { total = parseInt(total); for (var i=1; i<=total; i++) { input.push(i); } return input; }; }) ;