first commit

This commit is contained in:
ryanwong
2022-04-12 08:57:07 -04:00
commit 1bab399b38
446 changed files with 109788 additions and 0 deletions
@@ -0,0 +1,36 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Actives Add View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require("../models");
let AuthService = require("../services/AuthService");
module.exports = function (entity, pageName = "", success, error, base_url = "") {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.get_page_name = () => pageName;
this.endpoint = "/admin/actives";
this.heading = "Add active";
this.action = "/admin/actives-add";
this.form_fields = { name: "", handle: "", description: "" };
return this;
};
@@ -0,0 +1,40 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Actives Delete View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, success, error) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
return this;
};
@@ -0,0 +1,30 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Actives V View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName = "", success, error, base_url = "") {
this.entity = entity;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.endpoint = "/admin/actives";
this.get_page_name = () => pageName;
this.heading = "Active details";
this.detail_fields = { id: "", name: "", description: "" };
return this;
};
@@ -0,0 +1,51 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Actives Edit View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require("../models");
module.exports = function (entity, pageName = "", success, error, base_url = "") {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.endpoint = "/admin/actives";
this.get_page_name = () => pageName;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.heading = "Edit active";
this.action = "/admin/actives-edit";
this.form_fields = { name: "", id: "", handle: "", description: "" };
return this;
};
@@ -0,0 +1,555 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Actives Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ["ID", "Name", "Description", "Action"];
this._readable_column = ["ID", "Name", "Description"];
this._entity = entity;
this._heading = "Actives";
this._base_url = baseUrl.endsWith("/") ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = "";
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ["id", "name", "description"];
this._readable_field_column = ["id", "name", "description"];
this._links = "";
this._sort_base_url = "";
this._order_by = "";
this._sort = "";
this._link_types = { start: "start", prev: "prev", next: "next" };
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = "";
this.full_tag_close = "";
this.attributes = "";
this.first_link = "";
this.last_link = "";
this.first_tag_open = "";
this.query_string_segment = "per_page";
this.first_tag_close = "";
this.prev_link = "";
this.prev_tag_open = "";
this.prev_tag_close = "";
this.next_link = "";
this.next_tag_open = "";
this.next_tag_close = "";
this.last_tag_open = "";
this.last_tag_close = "";
this.cur_tag_open = "";
this.cur_tag_close = "";
this.num_tag_open = "";
this.num_tag_close = "";
this.suffix = "";
this.prefix = "";
this.cur_page = 0;
this.get_page_name = () => pageName;
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === "string") {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return "";
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear();
};
this.datetime = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
};
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
// 2018-06-12T19:30
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map((i) => startPage + i);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
};
this.set_id = function (id) {
this._id = id;
};
this._id = null;
this.get_name = function () {
return this._name;
};
this.set_name = function (name) {
this._name = name;
};
this._name = null;
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["name"] = value["name"];
clean_list_entry["description"] = value["description"];
clean_list.push(clean_list_entry);
}
return {
page: this.get_page(),
num_page: this.get_num_page(),
num_item: this.get_total_rows(),
item: clean_list,
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["name"] = value["name"];
clean_list_entry["description"] = value["description"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function (v, index) {
if (v.length === 0) {
columns.splice(index, 1);
}
return v.length > 0;
});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(",") + "\n";
}
return csv;
};
return this;
};
+224
View File
@@ -0,0 +1,224 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Admin Authentication View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const { nanoid, customAlphabet } = require('nanoid');
const { Op } = require('sequelize');
const bcrypt = require('bcryptjs');
const db = require('../models');
const MailService = require('../services/MailService');
// const SmsService = require('../services/SmsService');
module.exports = function (entity, pageName = '', success, error) {
this.entity = entity;
this.success = success || null;
this.error = error || null;
this.email = '';
this.resetToken = '';
this.get_page_name = () => pageName;
this.login_fields = { email: '', password: '' };
this.register_fields = {
email: '',
first_name: '',
last_name: '',
password: '',
confirm_password: '',
};
this.forgot_fields = { email: '' };
this.reset_fields = { password: '', confirm_password: '' };
this.account_verification_fields = { verificationCode: '' };
this.form_fields = { 'first_name': '','last_name': '','credential.email': '','credential.password': '','status': '' }
this.google_auth_url = '/admin/google/initialize';
this.facebook_auth_url = '/admin/facebook/initialize';
this.account_exists = function (email, otherFields={}) {
return db.credential.getByFields({ email, status: 1, ...otherFields });
};
this.get_associated_user = function (id) {
return this.entity.getByPK(id);
};
this.compare_password = function (password, hashedPassword) {
return bcrypt.compare(password, hashedPassword);
};
this.generate_hash = function (password) {
return bcrypt.hash(password, bcrypt.genSaltSync(10));
};
this.create_credential = function ({ ...args }) {
return db.credential.insert({
...args,
});
};
this.create_user = function ({ ...args }) {
return this.entity.insert({
...args,
});
};
this.destroy_credential = function (id) {
return db.credential.realDelete(id);
};
this.destroy_user = function (id) {
return db.user.realDelete(id);
};
this.createResetPasswordEmailTemplateForViews = function (slug) {
return db.email.insert({
slug: slug,
subject: 'Forgot Password',
"tag": "email,reset_token,link",
html: `Hi {{{email}}},<br/>You have requested to reset your password. Please click the link below to reset it.<br/><a href=\"{{{link}}}/{{{reset_token}}}\">Link</a>. <br/>Thanks,<br/> Admin`,
}, {
returnAllFields:true
});
};
this.initializeMailService = function (email) {
MailService.initialize({
hostname: process.env.EMAIL_SMTP_SMTP_HOST,
port: process.env.EMAIL_SMTP_SMTP_PORT,
username: process.env.EMAIL_SMTP_SMTP_USER,
password: process.env.EMAIL_SMTP_SMTP_PASS,
from: process.env.MAIL_FROM,
to: email,
});
};
this.getForgotPasswordMailTemplate = async function (slug) {
try {
const template = await MailService.template(slug);
return template;
} catch (error) {
if (error === 'TEMPLATE_NOT_FOUND') {
const template = await this.createResetPasswordEmailTemplateForViews(
slug,
);
if (template) {
return template;
}
}
return null;
}
};
this.injectMailTemplate = function (template, payload) {
return MailService.inject(template, payload);
};
this.sendMail = function (template) {
return MailService.send(template);
};
this.generateRandomToken = function (size = 32) {
return nanoid(size);
};
this.saveTokenToDB = function (
token,
user_id,
issue_at = new Date(),
expire_at = Date.now() + 36000000,
) {
return db.token.insert({ token, user_id, issue_at, expire_at });
};
this.validateToken = async function (token) {
try {
const isValid = await db.token.findOne({
where: {
token,
expire_at: { [Op.gt]: new Date() },
},
});
return isValid;
} catch (error) {
return false;
}
};
this.getUserCredential = function (user_id) {
return db.credential.findOne({ where: { user_id } });
};
this.updatePassword = function (hashedPassword, credential_id) {
return db.credential.edit(
{
password: hashedPassword,
},
credential_id,
);
};
this.create2FATemplate = function () {
return db.sms.insert({
slug: 'verify',
tag: 'code',
content: 'Your verification code is {{{code}}}',
});
};
this.sendSMS = async function (to, userID, slug = 'verify') {
const code = customAlphabet('0123456789', 8)();
try {
const template = await SmsService.template(slug);
const finalTemplate = SmsService.inject(template, { code });
await this.saveTokenToDB(code, userID);
return SmsService.send(to, finalTemplate);
} catch (error) {
if (error === 'TEMPLATE_NOT_FOUND') {
const template = await this.create2FATemplate();
if (template) {
const finalTemplate = SmsService.inject(template, { code });
await this.saveTokenToDB(code, userID);
return SmsService.send(to, finalTemplate);
}
throw new Error(error);
}
throw new Error(error);
}
};
this.status_mapping = function () {
return db.user.status_mapping();
};
this.role_id_mapping = function () {
return db.user.role_id_mapping();
};
this.type_mapping = function () {
return db.user.type_mapping();
};
this.verify_mapping = function () {
return db.user.verify_mapping();
};
this.two_factor_authentication_mapping = function () {
return db.user.two_factor_authentication_mapping();
};
this.force_password_change_mapping = function () {
return db.user.force_password_change_mapping();
};
return this;
};
@@ -0,0 +1,47 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Answers Add View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require("../models");
let AuthService = require("../services/AuthService");
module.exports = function (entity, pageName = "", success, error, base_url = "") {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.get_page_name = () => pageName;
this.endpoint = "/admin/answers";
this.heading = "Add answer";
this.action = "/admin/answers-add";
this.form_fields = {
question_id: "",
answer: "",
order: "",
answer_value: "",
explaination: "",
image_id: "",
response_header: "",
response_body: "",
response_arguments: "",
black_list_actives: "",
};
return this;
};
@@ -0,0 +1,40 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Answers Delete View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, success, error) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
return this;
};
@@ -0,0 +1,33 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Answers V View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this.entity = entity
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/answers"
this.get_page_name = () => pageName
this.heading = "Answer details"
this.detail_fields = {"id":"","question_id":"","question.question":"","answer":"","answer_value":"","explaination":"","image_id":"","response_header":"","response_body":"","response_arguments":"","black_list_actives":""}
return this;
}
@@ -0,0 +1,63 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Answers Edit View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require("../models");
module.exports = function (entity, pageName = "", success, error, base_url = "") {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.endpoint = "/admin/answers";
this.get_page_name = () => pageName;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.heading = "Edit answer";
this.action = "/admin/answers-edit";
this.form_fields = {
question_id: "",
answer: "",
answer_value: "",
order: "",
explaination: "",
image_id: "",
response_header: "",
response_body: "",
response_arguments: "",
black_list_actives: "",
id: "",
};
return this;
};
@@ -0,0 +1,559 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Answers Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ["Quiz", "Question", "Answer", "Order", "Image", "BL Actives", "Action"];
this._readable_column = ["Quiz", "Question", "Answer", "Order", "Image", "BL Actives"];
this._entity = entity;
this._heading = "Answers";
this._base_url = baseUrl.endsWith("/") ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = "";
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ["question.quiz_id", "question.id", "answer", "order", "", "black_list_actives"];
this._readable_field_column = ["quiz", "question", "answer", "order", "", "black_list_actives"];
this._links = "";
this._sort_base_url = "";
this._order_by = "";
this._sort = "";
this._link_types = { start: "start", prev: "prev", next: "next" };
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = "";
this.full_tag_close = "";
this.attributes = "";
this.first_link = "";
this.last_link = "";
this.first_tag_open = "";
this.query_string_segment = "per_page";
this.first_tag_close = "";
this.prev_link = "";
this.prev_tag_open = "";
this.prev_tag_close = "";
this.next_link = "";
this.next_tag_open = "";
this.next_tag_close = "";
this.last_tag_open = "";
this.last_tag_close = "";
this.cur_tag_open = "";
this.cur_tag_close = "";
this.num_tag_open = "";
this.num_tag_close = "";
this.suffix = "";
this.prefix = "";
this.cur_page = 0;
this.get_page_name = () => pageName;
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === "string") {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return "";
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear();
};
this.datetime = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
};
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
// 2018-06-12T19:30
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map((i) => startPage + i);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
};
this.set_id = function (id) {
this._id = id;
};
this._id = null;
this.get_question_id = function () {
return this._question_id;
};
this.set_question_id = function (question_id) {
this._question_id = question_id;
};
this._question_id = null;
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["answer"] = value["answer"];
clean_list_entry["question"] = value["question"]["question"];
clean_list_entry["image_id"] = value["image_id"];
clean_list_entry["black_list_actives"] = value["black_list_actives"];
clean_list.push(clean_list_entry);
}
return {
page: this.get_page(),
num_page: this.get_num_page(),
num_item: this.get_total_rows(),
item: clean_list,
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["answer"] = value["answer"];
clean_list_entry["question"] = value["question"]["question"];
clean_list_entry["image_id"] = value["image_id"];
clean_list_entry["black_list_actives"] = value["black_list_actives"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function (v, index) {
if (v.length === 0) {
columns.splice(index, 1);
}
return v.length > 0;
});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(",") + "\n";
}
return csv;
};
return this;
};
+44
View File
@@ -0,0 +1,44 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* file_upload_local Image View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName='', success, error ) {
this.entity = entity
this.success = success || null
this.error = error || null
this.endpoint = "{{{route}}}"
this.get_page_name = () => pageName
this.create_resource = function(data) {
return this.entity.insert(data)
}
this.upload_resource = function (req, res) {
const filename = nanoid();
const upload = uploader.local_upload('/uploads', 'file').single('file')
upload(req, res, function (error) {
if (error) throw new Error(error);
});
return filename;
};
return this
}
+44
View File
@@ -0,0 +1,44 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* image_upload_local Image View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName='', success, error ) {
this.entity = entity
this.success = success || null
this.error = error || null
this.endpoint = "{{{route}}}"
this.get_page_name = () => pageName
this.create_resource = function(data) {
return this.entity.insert(data)
}
this.upload_resource = function (req, res) {
const filename = nanoid();
const upload = uploader.local_upload('/uploads', 'image').single('image')
upload(req, res, function (error) {
if (error) throw new Error(error);
});
return filename;
};
return this
}
+224
View File
@@ -0,0 +1,224 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Admin Authentication View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const { nanoid, customAlphabet } = require('nanoid');
const { Op } = require('sequelize');
const bcrypt = require('bcryptjs');
const db = require('../models');
const MailService = require('../services/MailService');
// const SmsService = require('../services/SmsService');
module.exports = function (entity, pageName = '', success, error) {
this.entity = entity;
this.success = success || null;
this.error = error || null;
this.email = '';
this.resetToken = '';
this.get_page_name = () => pageName;
this.login_fields = { email: '', password: '' };
this.register_fields = {
email: '',
first_name: '',
last_name: '',
password: '',
confirm_password: '',
};
this.forgot_fields = { email: '' };
this.reset_fields = { password: '', confirm_password: '' };
this.account_verification_fields = { verificationCode: '' };
this.form_fields = { 'first_name': '','last_name': '','credential.email': '','credential.password': '','status': '' }
this.google_auth_url = '/member/google/initialize';
this.facebook_auth_url = '/member/facebook/initialize';
this.account_exists = function (email, otherFields={}) {
return db.credential.getByFields({ email, status: 1, ...otherFields });
};
this.get_associated_user = function (id) {
return this.entity.getByPK(id);
};
this.compare_password = function (password, hashedPassword) {
return bcrypt.compare(password, hashedPassword);
};
this.generate_hash = function (password) {
return bcrypt.hash(password, bcrypt.genSaltSync(10));
};
this.create_credential = function ({ ...args }) {
return db.credential.insert({
...args,
});
};
this.create_user = function ({ ...args }) {
return this.entity.insert({
...args,
});
};
this.destroy_credential = function (id) {
return db.credential.realDelete(id);
};
this.destroy_user = function (id) {
return db.user.realDelete(id);
};
this.createResetPasswordEmailTemplateForViews = function (slug) {
return db.email.insert({
slug: slug,
subject: 'Forgot Password',
"tag": "email,reset_token,link",
html: `Hi {{{email}}},<br/>You have requested to reset your password. Please click the link below to reset it.<br/><a href=\"{{{link}}}/{{{reset_token}}}\">Link</a>. <br/>Thanks,<br/> Admin`,
}, {
returnAllFields:true
});
};
this.initializeMailService = function (email) {
MailService.initialize({
hostname: process.env.EMAIL_SMTP_SMTP_HOST,
port: process.env.EMAIL_SMTP_SMTP_PORT,
username: process.env.EMAIL_SMTP_SMTP_USER,
password: process.env.EMAIL_SMTP_SMTP_PASS,
from: process.env.MAIL_FROM,
to: email,
});
};
this.getForgotPasswordMailTemplate = async function (slug) {
try {
const template = await MailService.template(slug);
return template;
} catch (error) {
if (error === 'TEMPLATE_NOT_FOUND') {
const template = await this.createResetPasswordEmailTemplateForViews(
slug,
);
if (template) {
return template;
}
}
return null;
}
};
this.injectMailTemplate = function (template, payload) {
return MailService.inject(template, payload);
};
this.sendMail = function (template) {
return MailService.send(template);
};
this.generateRandomToken = function (size = 32) {
return nanoid(size);
};
this.saveTokenToDB = function (
token,
user_id,
issue_at = new Date(),
expire_at = Date.now() + 36000000,
) {
return db.token.insert({ token, user_id, issue_at, expire_at });
};
this.validateToken = async function (token) {
try {
const isValid = await db.token.findOne({
where: {
token,
expire_at: { [Op.gt]: new Date() },
},
});
return isValid;
} catch (error) {
return false;
}
};
this.getUserCredential = function (user_id) {
return db.credential.findOne({ where: { user_id } });
};
this.updatePassword = function (hashedPassword, credential_id) {
return db.credential.edit(
{
password: hashedPassword,
},
credential_id,
);
};
this.create2FATemplate = function () {
return db.sms.insert({
slug: 'verify',
tag: 'code',
content: 'Your verification code is {{{code}}}',
});
};
this.sendSMS = async function (to, userID, slug = 'verify') {
const code = customAlphabet('0123456789', 8)();
try {
const template = await SmsService.template(slug);
const finalTemplate = SmsService.inject(template, { code });
await this.saveTokenToDB(code, userID);
return SmsService.send(to, finalTemplate);
} catch (error) {
if (error === 'TEMPLATE_NOT_FOUND') {
const template = await this.create2FATemplate();
if (template) {
const finalTemplate = SmsService.inject(template, { code });
await this.saveTokenToDB(code, userID);
return SmsService.send(to, finalTemplate);
}
throw new Error(error);
}
throw new Error(error);
}
};
this.status_mapping = function () {
return db.user.status_mapping();
};
this.role_id_mapping = function () {
return db.user.role_id_mapping();
};
this.type_mapping = function () {
return db.user.type_mapping();
};
this.verify_mapping = function () {
return db.user.verify_mapping();
};
this.two_factor_authentication_mapping = function () {
return db.user.two_factor_authentication_mapping();
};
this.force_password_change_mapping = function () {
return db.user.force_password_change_mapping();
};
return this;
};
@@ -0,0 +1,589 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Orders Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ["ID", "Order shopify id", "Customer", "Financial status", "Fulfillment status", "Created at", "Printables"];
this._readable_column = ["ID", "Order shopify id", "Customer", "Financial status", "Fulfillment status", "Created at"];
this._entity = entity;
this._heading = "Orders";
this._base_url = baseUrl.endsWith("/") ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = "";
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ["id", "shopify_id", "customer", "financial_status", "fulfillment_status", "created_at", ""];
this._readable_field_column = ["id", "shopify_id", "customer", "financial_status", "fulfillment_status", "created_at"];
this._links = "";
this._sort_base_url = "";
this._order_by = "";
this._sort = "";
this._link_types = { start: "start", prev: "prev", next: "next" };
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = "";
this.full_tag_close = "";
this.attributes = "";
this.first_link = "";
this.last_link = "";
this.first_tag_open = "";
this.query_string_segment = "per_page";
this.first_tag_close = "";
this.prev_link = "";
this.prev_tag_open = "";
this.prev_tag_close = "";
this.next_link = "";
this.next_tag_open = "";
this.next_tag_close = "";
this.last_tag_open = "";
this.last_tag_close = "";
this.cur_tag_open = "";
this.cur_tag_close = "";
this.num_tag_open = "";
this.num_tag_close = "";
this.suffix = "";
this.prefix = "";
this.cur_page = 0;
this.get_page_name = () => pageName;
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === "string") {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return "";
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear();
};
this.datetime = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
};
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
// 2018-06-12T19:30
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map((i) => startPage + i);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
};
this.set_id = function (id) {
this._id = id;
};
this._id = null;
this.get_customer_shopify_id = function () {
return this._customer_shopify_id;
};
this.set_customer_shopify_id = function (customer_shopify_id) {
this._customer_shopify_id = customer_shopify_id;
};
this._customer_shopify_id = null;
this.get_shopify_id = function () {
return this._shopify_id;
};
this.set_shopify_id = function (shopify_id) {
this._shopify_id = shopify_id;
};
this._shopify_id = null;
this.get_financial_status = function () {
return this._financial_status;
};
this.set_financial_status = function (financial_status) {
this._financial_status = financial_status;
};
this._financial_status = null;
this.get_fulfillment_status = function () {
return this._fulfillment_status;
};
this.set_fulfillment_status = function (fulfillment_status) {
this._fulfillment_status = fulfillment_status;
};
this._fulfillment_status = null;
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["shopify_id"] = value["shopify_id"];
clean_list_entry["customer"] = value["customer"];
clean_list_entry["financial_status"] = value["financial_status"];
clean_list_entry["fulfillment_status"] = value["fulfillment_status"];
clean_list.push(clean_list_entry);
}
return {
page: this.get_page(),
num_page: this.get_num_page(),
num_item: this.get_total_rows(),
item: clean_list,
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["shopify_id"] = value["shopify_id"];
clean_list_entry["customer"] = value["customer"];
clean_list_entry["financial_status"] = value["financial_status"];
clean_list_entry["fulfillment_status"] = value["fulfillment_status"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function (v, index) {
if (v.length === 0) {
columns.splice(index, 1);
}
return v.length > 0;
});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(",") + "\n";
}
return csv;
};
return this;
};
@@ -0,0 +1,46 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Output_variables Add View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models')
let AuthService = require('../services/AuthService');
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.get_page_name = () => pageName;
this.endpoint = "/admin/output-variables"
this.heading = "Add output variable"
this.action = "/admin/output-variables-add"
this.form_fields = {"name":"","active_list":"","ranges_response":""}
return this;
}
@@ -0,0 +1,40 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Output_variables Delete View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, success, error) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
return this;
};
@@ -0,0 +1,33 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Output_variables V View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this.entity = entity
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/output-variables"
this.get_page_name = () => pageName
this.heading = "Output variable details"
this.detail_fields = {"id":"","name":"","active_list":"","ranges_response":""}
return this;
}
@@ -0,0 +1,58 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Output_variables Edit View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, pageName='', success, error, base_url = "") {
this._entity = entity
this.session = null
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/output-variables"
this.get_page_name = () => pageName
this.format_date_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
return `${year}-${month}-${day}`
}
this.format_date_local_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
const hrs = d.getHours() < 10 ? `0${d.getHours() }` : d.getHours() ;
const mins = d.getMinutes() < 10 ? `0${d.getMinutes() }` : d.getMinutes() ;
return `${year}-${month}-${day}T${hrs}:${mins}`
}
this.heading = "Edit output variable"
this.action = "/admin/output-variables-edit"
this.form_fields = {"name":"","active_list":"","ranges_response":"","id":""}
return this;
}
@@ -0,0 +1,557 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Output_variables Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ["ID", "Name", "Priority", "Actives list", "Ranges responses", "Action"];
this._readable_column = ["ID", "Name", "Priority", "Actives list", "Ranges responses"];
this._entity = entity;
this._heading = "Output variables";
this._base_url = baseUrl.endsWith("/") ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = "";
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ["id", "name", "priority", "active_list", "ranges_response"];
this._readable_field_column = ["id", "name", "priority", "active_list", "ranges_response"];
this._links = "";
this._sort_base_url = "";
this._order_by = "";
this._sort = "";
this._link_types = { start: "start", prev: "prev", next: "next" };
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = "";
this.full_tag_close = "";
this.attributes = "";
this.first_link = "";
this.last_link = "";
this.first_tag_open = "";
this.query_string_segment = "per_page";
this.first_tag_close = "";
this.prev_link = "";
this.prev_tag_open = "";
this.prev_tag_close = "";
this.next_link = "";
this.next_tag_open = "";
this.next_tag_close = "";
this.last_tag_open = "";
this.last_tag_close = "";
this.cur_tag_open = "";
this.cur_tag_close = "";
this.num_tag_open = "";
this.num_tag_close = "";
this.suffix = "";
this.prefix = "";
this.cur_page = 0;
this.get_page_name = () => pageName;
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === "string") {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return "";
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear();
};
this.datetime = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
};
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
// 2018-06-12T19:30
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map((i) => startPage + i);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
};
this.set_id = function (id) {
this._id = id;
};
this._id = null;
this.get_name = function () {
return this._name;
};
this.set_name = function (name) {
this._name = name;
};
this._name = null;
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["name"] = value["name"];
clean_list_entry["active_list"] = value["active_list"];
clean_list_entry["ranges_response"] = value["ranges_response"];
clean_list.push(clean_list_entry);
}
return {
page: this.get_page(),
num_page: this.get_num_page(),
num_item: this.get_total_rows(),
item: clean_list,
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["name"] = value["name"];
clean_list_entry["active_list"] = value["active_list"];
clean_list_entry["ranges_response"] = value["ranges_response"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function (v, index) {
if (v.length === 0) {
columns.splice(index, 1);
}
return v.length > 0;
});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(",") + "\n";
}
return csv;
};
return this;
};
@@ -0,0 +1,66 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Questions Add View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require("../models");
let AuthService = require("../services/AuthService");
module.exports = function (entity, pageName = "", success, error, base_url = "") {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.get_page_name = () => pageName;
this.endpoint = "/admin/questions";
this.heading = "Add question";
this.action = "/admin/questions-add";
this.form_fields = {
quiz_id: "",
question: "",
question_arguments: "",
order: "",
image_width: "",
image_height: "",
note: "",
note_type: "",
target: "",
response: "",
save_response_into: "",
depends_on: "",
slider_range: "",
output_variable_name: "",
weight: "",
extra_output_variable: "",
type: "",
};
this.type_mapping = function () {
return this._entity.type_mapping();
};
this.target_mapping = function () {
return this._entity.target_mapping();
};
this.note_type_mapping = function () {
return this._entity.note_type_mapping();
};
return this;
};
@@ -0,0 +1,40 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Questions Delete View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, success, error) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
return this;
};
@@ -0,0 +1,47 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Questions V View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName = "", success, error, base_url = "") {
this.entity = entity;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.endpoint = "/admin/questions";
this.get_page_name = () => pageName;
this.heading = "Question details";
this.detail_fields = {
id: "",
"quiz.name": "",
question: "",
question_arguments: "",
order: "",
note: "",
note_type: "",
target: "",
response: "",
save_response_into: "",
depends_on: "",
slider_range: "",
output_variable_name: "",
weight: "",
extra_output_variable: "",
type: "",
};
return this;
};
@@ -0,0 +1,82 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Questions Edit View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require("../models");
module.exports = function (entity, pageName = "", success, error, base_url = "") {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.endpoint = "/admin/questions";
this.get_page_name = () => pageName;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.heading = "Edit question";
this.action = "/admin/questions-edit";
this.form_fields = {
quiz_id: "",
question: "",
order: "",
question_arguments: "",
note: "",
image_width: "",
image_height: "",
note_type: "",
target: "",
response: "",
save_response_into: "",
depends_on: "",
slider_range: "",
output_variable_name: "",
weight: "",
extra_output_variable: "",
type: "",
id: "",
};
this.type_mapping = function () {
return this._entity.type_mapping();
};
this.target_mapping = function () {
return this._entity.target_mapping();
};
this.note_type_mapping = function () {
return this._entity.note_type_mapping();
};
return this;
};
@@ -0,0 +1,583 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Questions Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ["Quiz", "Question", "Order", "Type", "Output variable", "Action"];
this._readable_column = ["Quiz", "Question", "Order", "Type", "Output variable"];
this._entity = entity;
this._heading = "Questions";
this._base_url = baseUrl.endsWith("/") ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = "";
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ["quiz.id", "order", "id", "type", "", ""];
this._readable_field_column = ["quiz", "order", "id", "type"];
this._links = "";
this._sort_base_url = "";
this._order_by = "";
this._sort = "";
this._link_types = { start: "start", prev: "prev", next: "next" };
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = "";
this.full_tag_close = "";
this.attributes = "";
this.first_link = "";
this.last_link = "";
this.first_tag_open = "";
this.query_string_segment = "per_page";
this.first_tag_close = "";
this.prev_link = "";
this.prev_tag_open = "";
this.prev_tag_close = "";
this.next_link = "";
this.next_tag_open = "";
this.next_tag_close = "";
this.last_tag_open = "";
this.last_tag_close = "";
this.cur_tag_open = "";
this.cur_tag_close = "";
this.num_tag_open = "";
this.num_tag_close = "";
this.suffix = "";
this.prefix = "";
this.cur_page = 0;
this.get_page_name = () => pageName;
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === "string") {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return "";
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear();
};
this.datetime = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
};
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
// 2018-06-12T19:30
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map((i) => startPage + i);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
};
this.set_id = function (id) {
this._id = id;
};
this._id = null;
this.get_quiz_id = function () {
return this._quiz_id;
};
this.set_quiz_id = function (quiz_id) {
this._quiz_id = quiz_id;
};
this._quiz_id = null;
this.get_type = function () {
return this._type;
};
this.set_type = function (type) {
this._type = type;
};
this._type = null;
this.type_mapping = function () {
return this._entity.type_mapping();
};
this.target_mapping = function () {
return this._entity.target_mapping();
};
this.note_type_mapping = function () {
return this._entity.note_type_mapping();
};
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
list[key].type = this.type_mapping()[value.type];
list[key].target = this.target_mapping()[value.target];
list[key].note_type = this.note_type_mapping()[value.note_type];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["question"] = value["question"];
clean_list_entry["type"] = value["type"];
clean_list.push(clean_list_entry);
}
return {
page: this.get_page(),
num_page: this.get_num_page(),
num_item: this.get_total_rows(),
item: clean_list,
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
list[key].type = this.type_mapping()[value.type];
list[key].target = this.target_mapping()[value.target];
list[key].note_type = this.note_type_mapping()[value.note_type];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["question"] = value["question"];
clean_list_entry["type"] = value["type"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function (v, index) {
if (v.length === 0) {
columns.splice(index, 1);
}
return v.length > 0;
});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(",") + "\n";
}
return csv;
};
return this;
};
@@ -0,0 +1,46 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Quizzes Add View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models')
let AuthService = require('../services/AuthService');
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.get_page_name = () => pageName;
this.endpoint = "/admin/quizzes"
this.heading = "Add quiz"
this.action = "/admin/quizzes-add"
this.form_fields = {"name":"","description":""}
return this;
}
@@ -0,0 +1,40 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Quizzes Delete View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, success, error) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
return this;
};
@@ -0,0 +1,33 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Quizzes V View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this.entity = entity
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/quizzes"
this.get_page_name = () => pageName
this.heading = "Quiz details"
this.detail_fields = {"id":"","name":"","description":""}
return this;
}
@@ -0,0 +1,58 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Quizzes Edit View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, pageName='', success, error, base_url = "") {
this._entity = entity
this.session = null
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/quizzes"
this.get_page_name = () => pageName
this.format_date_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
return `${year}-${month}-${day}`
}
this.format_date_local_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
const hrs = d.getHours() < 10 ? `0${d.getHours() }` : d.getHours() ;
const mins = d.getMinutes() < 10 ? `0${d.getMinutes() }` : d.getMinutes() ;
return `${year}-${month}-${day}T${hrs}:${mins}`
}
this.heading = "Edit quiz"
this.action = "/admin/quizzes-edit"
this.form_fields = {"name":"","description":"","id":""}
return this;
}
@@ -0,0 +1,583 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Quizzes Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ['ID','Name','Description','Action'];
this._readable_column = ["ID","Name","Description"];
this._entity = entity;
this._heading = 'Quizzes';
this._base_url = baseUrl.endsWith('/') ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = '';
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ['id','name','description'];
this._readable_field_column = ["id","name","description"]
this._links = '';
this._sort_base_url = '';
this._order_by = '';
this._sort = '';
this._link_types = {'start': 'start', 'prev': 'prev', 'next': 'next'};
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = '';
this.full_tag_close = '';
this.attributes = '';
this.first_link = '';
this.last_link = '';
this.first_tag_open = '';
this.query_string_segment = 'per_page';
this.first_tag_close = '';
this.prev_link = '';
this.prev_tag_open = '';
this.prev_tag_close = '';
this.next_link = '';
this.next_tag_open = '';
this.next_tag_close = '';
this.last_tag_open = '';
this.last_tag_close = '';
this.cur_tag_open = '';
this.cur_tag_close = '';
this.num_tag_open = '';
this.num_tag_close = '';
this.suffix = '';
this.prefix = '';
this.cur_page = 0;
this.get_page_name = () => pageName
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === 'string') {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return '';
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return (
("0" + (d.getMonth() + 1)).slice(-2) +
" " +
("0" + d.getDate()).slice(-2) +
" " +
d.getFullYear()
);
};
this.datetime = function (d) {
return (
("0" + (d.getMonth() + 1)).slice(-2) +
" " +
("0" + d.getDate()).slice(-2) +
" " +
d.getFullYear() +
" " +
("0" + d.getHours()).slice(-2) +
":" +
("0" + d.getMinutes()).slice(-2)
);
};
this.format_date_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
return `${year}-${month}-${day}`
}
// 2018-06-12T19:30
this.format_date_local_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
const hrs = d.getHours() < 10 ? `0${d.getHours() }` : d.getHours() ;
const mins = d.getMinutes() < 10 ? `0${d.getMinutes() }` : d.getMinutes() ;
return `${year}-${month}-${day}T${hrs}:${mins}`
}
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map(
(i) => startPage + i
);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
}
this.set_id = function (id) {
this._id = id;
}
this._id = null;
this.get_name = function () {
return this._name;
}
this.set_name = function (name) {
this._name = name;
}
this._name = null;
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["name"] = value["name"];
clean_list_entry["description"] = value["description"];
clean_list.push(clean_list_entry);
}
return {
"page" : this.get_page(),
"num_page" : this.get_num_page(),
"num_item" : this.get_total_rows(),
"item" : clean_list
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["name"] = value["name"];
clean_list_entry["description"] = value["description"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function(v, index){
if (v.length === 0) {columns.splice(index, 1);
}
return v.length > 0;});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(',') + "\n";
}
return csv;
}
return this;
};
@@ -0,0 +1,46 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Result_profile Add View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models')
let AuthService = require('../services/AuthService');
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.get_page_name = () => pageName;
this.endpoint = "/admin/profile-sections"
this.heading = "Add result profile"
this.action = "/admin/profile-sections-add"
this.form_fields = {"section_title":"","output_variable_list":""}
return this;
}
@@ -0,0 +1,40 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Result_profile Delete View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, success, error) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
return this;
};
@@ -0,0 +1,33 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Result_profile V View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this.entity = entity
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/profile-sections"
this.get_page_name = () => pageName
this.heading = "Result profile details"
this.detail_fields = {"id":"","section_title":"","output_variable_list":""}
return this;
}
@@ -0,0 +1,58 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Result_profile Edit View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, pageName='', success, error, base_url = "") {
this._entity = entity
this.session = null
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/profile-sections"
this.get_page_name = () => pageName
this.format_date_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
return `${year}-${month}-${day}`
}
this.format_date_local_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
const hrs = d.getHours() < 10 ? `0${d.getHours() }` : d.getHours() ;
const mins = d.getMinutes() < 10 ? `0${d.getMinutes() }` : d.getMinutes() ;
return `${year}-${month}-${day}T${hrs}:${mins}`
}
this.heading = "Edit result profile"
this.action = "/admin/profile-sections-edit"
this.form_fields = {"section_title":"","output_variable_list":"","id":""}
return this;
}
@@ -0,0 +1,583 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Result_profile Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ['ID','Section title','Variables List','Action'];
this._readable_column = ["ID","Section title","Variables List"];
this._entity = entity;
this._heading = 'Result profile';
this._base_url = baseUrl.endsWith('/') ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = '';
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ['id','section_title','output_variable_list'];
this._readable_field_column = ["id","section_title","output_variable_list"]
this._links = '';
this._sort_base_url = '';
this._order_by = '';
this._sort = '';
this._link_types = {'start': 'start', 'prev': 'prev', 'next': 'next'};
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = '';
this.full_tag_close = '';
this.attributes = '';
this.first_link = '';
this.last_link = '';
this.first_tag_open = '';
this.query_string_segment = 'per_page';
this.first_tag_close = '';
this.prev_link = '';
this.prev_tag_open = '';
this.prev_tag_close = '';
this.next_link = '';
this.next_tag_open = '';
this.next_tag_close = '';
this.last_tag_open = '';
this.last_tag_close = '';
this.cur_tag_open = '';
this.cur_tag_close = '';
this.num_tag_open = '';
this.num_tag_close = '';
this.suffix = '';
this.prefix = '';
this.cur_page = 0;
this.get_page_name = () => pageName
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === 'string') {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return '';
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return (
("0" + (d.getMonth() + 1)).slice(-2) +
" " +
("0" + d.getDate()).slice(-2) +
" " +
d.getFullYear()
);
};
this.datetime = function (d) {
return (
("0" + (d.getMonth() + 1)).slice(-2) +
" " +
("0" + d.getDate()).slice(-2) +
" " +
d.getFullYear() +
" " +
("0" + d.getHours()).slice(-2) +
":" +
("0" + d.getMinutes()).slice(-2)
);
};
this.format_date_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
return `${year}-${month}-${day}`
}
// 2018-06-12T19:30
this.format_date_local_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
const hrs = d.getHours() < 10 ? `0${d.getHours() }` : d.getHours() ;
const mins = d.getMinutes() < 10 ? `0${d.getMinutes() }` : d.getMinutes() ;
return `${year}-${month}-${day}T${hrs}:${mins}`
}
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map(
(i) => startPage + i
);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
}
this.set_id = function (id) {
this._id = id;
}
this._id = null;
this.get_section_title = function () {
return this._section_title;
}
this.set_section_title = function (section_title) {
this._section_title = section_title;
}
this._section_title = null;
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["section_title"] = value["section_title"];
clean_list_entry["output_variable_list"] = value["output_variable_list"];
clean_list.push(clean_list_entry);
}
return {
"page" : this.get_page(),
"num_page" : this.get_num_page(),
"num_item" : this.get_total_rows(),
"item" : clean_list
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["section_title"] = value["section_title"];
clean_list_entry["output_variable_list"] = value["output_variable_list"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function(v, index){
if (v.length === 0) {columns.splice(index, 1);
}
return v.length > 0;});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(',') + "\n";
}
return csv;
}
return this;
};
+56
View File
@@ -0,0 +1,56 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Rules Add View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models')
let AuthService = require('../services/AuthService');
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.get_page_name = () => pageName;
this.endpoint = "/admin/rules"
this.heading = "Add rule"
this.action = "/admin/rules-add"
this.form_fields = {"output_variable_name":"","actives":"","operator":"","compare_value":"","min":"","max":"","action":""}
this.operator_mapping = function () {
return this._entity.operator_mapping();
}
this.action_mapping = function () {
return this._entity.action_mapping();
}
return this;
}
@@ -0,0 +1,40 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Rules Delete View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, success, error) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
return this;
};
@@ -0,0 +1,33 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Rules V View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this.entity = entity
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/rules"
this.get_page_name = () => pageName
this.heading = "Rule details"
this.detail_fields = {"id":"","output_variable_name":"","actives":"","operator":"","compare_value":"","min":"","max":"","action":""}
return this;
}
@@ -0,0 +1,68 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Rules Edit View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, pageName='', success, error, base_url = "") {
this._entity = entity
this.session = null
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/rules"
this.get_page_name = () => pageName
this.format_date_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
return `${year}-${month}-${day}`
}
this.format_date_local_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
const hrs = d.getHours() < 10 ? `0${d.getHours() }` : d.getHours() ;
const mins = d.getMinutes() < 10 ? `0${d.getMinutes() }` : d.getMinutes() ;
return `${year}-${month}-${day}T${hrs}:${mins}`
}
this.heading = "Edit rule"
this.action = "/admin/rules-edit"
this.form_fields = {"output_variable_name":"","actives":"","operator":"","compare_value":"","min":"","max":"","action":"","id":""}
this.operator_mapping = function () {
return this._entity.operator_mapping();
}
this.action_mapping = function () {
return this._entity.action_mapping();
}
return this;
}
@@ -0,0 +1,593 @@
"use strict";
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Rules Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ["ID", "Output variable", "Actives", "Condition operator", "Compare value", "Operation", "Action"];
this._readable_column = ["ID", "Output variable", "Actives", "Condition operator", "Compare value", "Operation"];
this._entity = entity;
this._heading = "Rules";
this._base_url = baseUrl.endsWith("/") ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = "";
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ["id", "output_variable_name", "actives", "operator", "compare_value", "action"];
this._readable_field_column = ["id", "output_variable_name", "actives", "operator", "compare_value", "action"];
this._links = "";
this._sort_base_url = "";
this._order_by = "";
this._sort = "";
this._link_types = { start: "start", prev: "prev", next: "next" };
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = "";
this.full_tag_close = "";
this.attributes = "";
this.first_link = "";
this.last_link = "";
this.first_tag_open = "";
this.query_string_segment = "per_page";
this.first_tag_close = "";
this.prev_link = "";
this.prev_tag_open = "";
this.prev_tag_close = "";
this.next_link = "";
this.next_tag_open = "";
this.next_tag_close = "";
this.last_tag_open = "";
this.last_tag_close = "";
this.cur_tag_open = "";
this.cur_tag_close = "";
this.num_tag_open = "";
this.num_tag_close = "";
this.suffix = "";
this.prefix = "";
this.cur_page = 0;
this.get_page_name = () => pageName;
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === "string") {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return "";
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear();
};
this.datetime = function (d) {
return ("0" + (d.getMonth() + 1)).slice(-2) + " " + ("0" + d.getDate()).slice(-2) + " " + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
};
this.format_date_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
return `${year}-${month}-${day}`;
};
// 2018-06-12T19:30
this.format_date_local_input = function (date) {
const d = new Date(date);
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
const hrs = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
const mins = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
return `${year}-${month}-${day}T${hrs}:${mins}`;
};
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map((i) => startPage + i);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
};
this.set_id = function (id) {
this._id = id;
};
this._id = null;
this.get_operator = function () {
return this._operator;
};
this.set_operator = function (operator) {
this._operator = operator;
};
this._operator = null;
this.get_action = function () {
return this._action;
};
this.set_action = function (action) {
this._action = action;
};
this._action = null;
this.get_output_variable_name = function () {
return this._output_variable_name;
};
this.set_output_variable_name = function (output_variable_name) {
this._output_variable_name = output_variable_name;
};
this._output_variable_name = null;
this.operator_mapping = function () {
return this._entity.operator_mapping();
};
this.action_mapping = function () {
return this._entity.action_mapping();
};
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
list[key].operator = this.operator_mapping()[value.operator];
list[key].action = this.action_mapping()[value.action];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["output_variable_name"] = value["output_variable_name"];
clean_list_entry["actives"] = value["actives"];
clean_list_entry["operator"] = value["operator"];
clean_list_entry["compare_value"] = value["compare_value"];
clean_list_entry["action"] = value["action"];
clean_list.push(clean_list_entry);
}
return {
page: this.get_page(),
num_page: this.get_num_page(),
num_item: this.get_total_rows(),
item: clean_list,
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
list[key].operator = this.operator_mapping()[value.operator];
list[key].action = this.action_mapping()[value.action];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["output_variable_name"] = value["output_variable_name"];
clean_list_entry["actives"] = value["actives"];
clean_list_entry["operator"] = value["operator"];
clean_list_entry["compare_value"] = value["compare_value"];
clean_list_entry["action"] = value["action"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function (v, index) {
if (v.length === 0) {
columns.splice(index, 1);
}
return v.length > 0;
});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(",") + "\n";
}
return csv;
};
return this;
};
+51
View File
@@ -0,0 +1,51 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Users Add View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models')
let AuthService = require('../services/AuthService');
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this._entity = entity;
this.session = null;
this.success = success || null;
this.error = error || null;
this._base_url = base_url;
this.get_page_name = () => pageName;
this.endpoint = "/admin/users"
this.heading = "Add user"
this.action = "/admin/users-add"
this.form_fields = {"email":"","password":"","first_name":"","last_name":"","image":"","role_id":"","phone":"","status":""}
this.status_mapping = function () {
return this._entity.status_mapping();
}
return this;
}
@@ -0,0 +1,33 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Users V View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName='', success, error, base_url = "" ) {
this.entity = entity
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/users"
this.get_page_name = () => pageName
this.heading = "User details"
this.detail_fields = {"id":"","credential.email":"","first_name":"","last_name":"","role_id":"","status":""}
return this;
}
@@ -0,0 +1,63 @@
'use strict'
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Users Edit View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
const db = require('../models');
module.exports = function (entity, pageName='', success, error, base_url = "") {
this._entity = entity
this.session = null
this.success = success || null
this.error = error || null
this._base_url = base_url
this.endpoint = "/admin/users"
this.get_page_name = () => pageName
this.format_date_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
return `${year}-${month}-${day}`
}
this.format_date_local_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
const hrs = d.getHours() < 10 ? `0${d.getHours() }` : d.getHours() ;
const mins = d.getMinutes() < 10 ? `0${d.getMinutes() }` : d.getMinutes() ;
return `${year}-${month}-${day}T${hrs}:${mins}`
}
this.heading = "Edit user"
this.action = "/admin/users-edit"
this.form_fields = {"credential.email":"","credential.password":"","first_name":"","last_name":"","role_id":"","image":"","phone":"","status":"","id":""}
this.status_mapping = function () {
return this._entity.status_mapping();
}
return this;
}
@@ -0,0 +1,612 @@
'use strict';
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2021*/
/**
* Users Paginate List View Model
*
* @copyright 2021 Manaknightdigital Inc.
* @link https://manaknightdigital.com
* @license Proprietary Software licensing
* @author Ryan Wong
*/
module.exports = function (entity, pageName, success, error, baseUrl) {
this.success = success ? success : "";
this.error = error ? error : "";
this._list = [];
this._column = ['ID','Image','Email','Name','Status','Action'];
this._readable_column = ["ID","Email","Status"];
this._entity = entity;
this._heading = 'Users';
this._base_url = baseUrl.endsWith('/') ? baseUrl.substring(0, -1) : baseUrl;
this._query = {};
this._total_rows = 0;
this._format_layout = '';
this._per_page = 10;
this._page;
this._num_links = 5;
this._field_column = ['id','image','credential.email','','status'];
this._readable_field_column = ["id","email","status"]
this._links = '';
this._sort_base_url = '';
this._order_by = '';
this._sort = '';
this._link_types = {'start': 'start', 'prev': 'prev', 'next': 'next'};
this._attributes = ' class="page-link"';
this.reuse_query_string = true;
this.page_query_string = true;
this.full_tag_open = '';
this.full_tag_close = '';
this.attributes = '';
this.first_link = '';
this.last_link = '';
this.first_tag_open = '';
this.query_string_segment = 'per_page';
this.first_tag_close = '';
this.prev_link = '';
this.prev_tag_open = '';
this.prev_tag_close = '';
this.next_link = '';
this.next_tag_open = '';
this.next_tag_close = '';
this.last_tag_open = '';
this.last_tag_close = '';
this.cur_tag_open = '';
this.cur_tag_close = '';
this.num_tag_open = '';
this.num_tag_close = '';
this.suffix = '';
this.prefix = '';
this.cur_page = 0;
this.get_page_name = () => pageName
this.get_heading = function () {
return pageName;
};
this.get_column = function () {
return this._column;
};
this.get_readable_column = function () {
return this._readable_column;
};
this.set_list = function (list) {
this._list = list;
};
this.set_query = function (query = {}) {
Object.keys(query).forEach((key) => {
if (this._field_column.includes(key)) {
console.log(this._query);
this._query[key] = query[key];
}
});
};
this.get_list = function () {
return this._list;
};
/**
* get_links function
*
* @return mixed
*/
this.get_links = function () {
this._links = this.createLinks();
return this._links;
};
/**
* set_total_rows function
*
* @param integer total_rows
* @return void
*/
this.set_total_rows = function (total_rows) {
this._total_rows = total_rows;
};
/**
* set_per_page function
*
* @param integer per_page
* @return void
*/
this.set_per_page = function (per_page) {
this._per_page = per_page;
};
/**
* format_layout function
*
* @param integer _format_layout
* @return void
*/
this.set_format_layout = function (_format_layout) {
this._format_layout = _format_layout;
};
/**
* set_order_by function
*
* @param string order_by
* @return void
*/
this.set_order_by = function (order_by) {
this._order_by = order_by;
};
/**
* set_sort function
*
* @param string sort
* @return void
*/
this.set_sort = function (sort) {
this._sort = sort;
};
/**
* set_sort_base_url function
*
* @param string sort_base_url
* @return void
*/
this.set_sort_base_url = function (sort_base_url) {
this._sort_base_url = sort_base_url;
};
/**
* get_total_rows function
*
* @return integer
*/
this.get_total_rows = function () {
return this._total_rows;
};
/**
* get_format_layout function
*
* @return integer
*/
this.get_format_layout = function () {
return this._format_layout;
};
/**
* get_per_page function
*
* @return integer
*/
this.get_per_page = function () {
return this._per_page;
};
/**
* get_page function
*
* @return integer
*/
this.get_page = function () {
return this._page;
};
/**
* num_links function
*
* @return integer
*/
this.get_num_links = function () {
return this._num_links;
};
/**
* set_order_by function
*
*/
this.get_order_by = function () {
return this._order_by;
};
/**
* get_field_column function
*
*/
this.get_field_column = function () {
return this._field_column;
};
this.get_readable_field_column = function () {
return this._readable_field_column;
};
/**
* set_sort function
*
*/
this.get_sort = function () {
return this._sort;
};
this.get_query = function () {
return this._query;
};
/**
* set_sort_base_url function
*
*/
this.get_sort_base_url = function () {
return this._sort_base_url;
};
/**
* set_page function
*
* @param integer page
* @return void
*/
this.set_page = function (page) {
this._page = page;
};
/**
* num_pages function
*
* @return integer
*/
this.get_num_page = function () {
let num = Math.ceil(this._total_rows / this._per_page);
return num > 0 ? parseInt(num) : 1;
};
this.image_or_file = function (file) {
const images = [".jpg", ".png", ".gif", ".jpeg", ".bmp"];
let is_image = false;
const exist = images.filter(function (value) {
return value.indexOf(file) > -1;
});
if (exist.length > 0) {
return `<div class='mkd-image-container'><img class='img-fluid' src='${file}' onerror=\"if (this.src != '/uploads/placeholder.jpg') this.src = '/uploads/placeholder.jpg';\"/></div>`;
}
return `<a href='${file}' target='__blank'>${file}</a>`;
};
this.timeago = function (date) {
const newDate = new Date(date);
const today = new Date();
const currentTime = today.getTime();
const timestamp = newDate.getTime();
const strTime = array("second", "minute", "hour", "day", "month", "year");
const duration = array(60, 60, 24, 30, 12, 10);
if (currentTime >= timestamp) {
diff = currentTime - timestamp;
for (let i = 0; diff >= duration[i] && i < duration.length - 1; i++) {
diff = diff / duration[i];
}
diff = Math.round(diff, 0);
return diff + " " + strTime[i] + "(s) ago ";
}
};
this.time_default_mapping = function () {
let results = [];
for (let i = 0; i < 24; i++) {
for (let j = 0; j < 60; j++) {
let hour = i < 10 ? "0" + i : i;
let min = j < 10 ? "0" + j : j;
results[i * 60 + j] = `${hour}:${min}`;
}
}
return results;
};
this.convertToString = function (input) {
if (input) {
if (typeof input === "string") {
return input;
}
return String(input);
}
return "";
};
// convert string to words
this.toWords = function (input) {
input = this.convertToString(input);
var regex = /[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g;
return input.match(regex);
};
// convert the input array to camel case
this.toCamelCase = function (inputArray) {
let result = "";
for (let i = 0, len = inputArray.length; i < len; i++) {
let currentStr = inputArray[i];
let tempStr = currentStr.toLowerCase();
if (i != 0) {
// convert first letter to upper case (the word is in lowercase)
tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
}
result += tempStr;
}
return result;
};
this.toCamelCaseString = function (input) {
let words = this.toWords(input);
return this.toCamelCase(words);
};
this.ucFirst = function (string) {
if (typeof string === 'string') {
return string.charAt(0).toUpperCase() + string.slice(1);
}
return '';
};
this.number_format = function (field, n) {
return field.toFixed(n);
};
this.date = function (d) {
return (
("0" + (d.getMonth() + 1)).slice(-2) +
" " +
("0" + d.getDate()).slice(-2) +
" " +
d.getFullYear()
);
};
this.datetime = function (d) {
return (
("0" + (d.getMonth() + 1)).slice(-2) +
" " +
("0" + d.getDate()).slice(-2) +
" " +
d.getFullYear() +
" " +
("0" + d.getHours()).slice(-2) +
":" +
("0" + d.getMinutes()).slice(-2)
);
};
this.format_date_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
return `${year}-${month}-${day}`
}
// 2018-06-12T19:30
this.format_date_local_input = function(date){
const d = new Date(date)
const year = d.getFullYear();
const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1 }` : d.getMonth() + 1 ;
const day = d.getDate() < 10 ? `0${d.getDate() }` : d.getDate() ;
const hrs = d.getHours() < 10 ? `0${d.getHours() }` : d.getHours() ;
const mins = d.getMinutes() < 10 ? `0${d.getMinutes() }` : d.getMinutes() ;
return `${year}-${month}-${day}T${hrs}:${mins}`
}
this.createLinks = function () {
let totalItems = this._total_rows;
let currentPage = this._page;
let pageSize = this._per_page;
let maxPages = 10;
// calculate total pages
let totalPages = Math.ceil(totalItems / pageSize);
// ensure current page isn't out of range
if (currentPage < 0) {
currentPage = 0;
} else if (currentPage > totalPages) {
currentPage = +totalPages;
}
let startPage = 0;
let endPage = 0;
if (totalPages <= maxPages) {
// total pages less than max so show all pages
startPage = 1;
endPage = totalPages;
} else {
// total pages more than max so calculate start and end pages
let maxPagesBeforeCurrentPage = Math.floor(maxPages / 2);
let maxPagesAfterCurrentPage = Math.ceil(maxPages / 2) - 1;
if (currentPage <= maxPagesBeforeCurrentPage) {
// current page near the start
startPage = 1;
endPage = maxPages;
} else if (currentPage + maxPagesAfterCurrentPage >= totalPages) {
// current page near the end
startPage = totalPages - maxPages + 1;
endPage = totalPages;
} else {
// current page somewhere in the middle
startPage = currentPage - maxPagesBeforeCurrentPage;
endPage = currentPage + maxPagesAfterCurrentPage;
}
}
// calculate start and end item indexes
let startIndex = (currentPage - 1) * pageSize;
let endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
// create an array of pages to ng-repeat in the pager control
let pages = Array.from(Array(endPage + 1 - startPage).keys()).map(
(i) => startPage + i
);
// return object with all pager properties required by the view
const payload = {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages,
};
let html = '<ul class="pagination justify-content-end">';
for (let i = 0; i < payload.pages.length && payload.pages.length > 1; i++) {
const element = +payload.pages[i];
if (element - 1 == payload.currentPage) {
html += `<li class="page-item active"><a href="#" class="page-link" >${element}<span class="sr-only">(current)</span></a></li>`;
} else {
html += `<li class="page-item"><a href="${this._base_url}/${
element - 1
}?order_by=${this.get_order_by()}&amp;direction=${this.get_sort()}&amp;per_page=${this.get_per_page()}" class="page-link" data-ci-pagination-page="${element}">${element}</a></li>`;
}
}
html += "</ul>";
return html;
};
this.get_id = function () {
return this._id;
}
this.set_id = function (id) {
this._id = id;
}
this._id = null;
this.get_credential_email = function () {
return this._credential_email;
}
this.set_credential_email = function (credential_email) {
this._credential_email = credential_email;
}
this._credential_email = null;
this.get_first_name = function () {
return this._first_name;
}
this.set_first_name = function (first_name) {
this._first_name = first_name;
}
this._first_name = null;
this.get_last_name = function () {
return this._last_name;
}
this.set_last_name = function (last_name) {
this._last_name = last_name;
}
this._last_name = null;
this.status_mapping = function () {
return this._entity.status_mapping();
}
this.to_json = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
list[key].status = this.status_mapping()[value.status];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["image"] = value["image"];
clean_list_entry["email"] = value["credential"]["email"];
clean_list_entry["status"] = value["status"];
clean_list.push(clean_list_entry);
}
return {
"page" : this.get_page(),
"num_page" : this.get_num_page(),
"num_item" : this.get_total_rows(),
"item" : clean_list
};
};
this.to_csv = function () {
let list = this.get_list();
let clean_list = [];
for (let key in list) {
let value = list[key];
list[key].status = this.status_mapping()[value.status];
let clean_list_entry = {};
clean_list_entry["id"] = value["id"];
clean_list_entry["image"] = value["image"];
clean_list_entry["email"] = value["credential"]["email"];
clean_list_entry["status"] = value["status"];
clean_list.push(clean_list_entry);
}
const columns = this.get_field_column();
const column_fields = this.get_readable_field_column();
const fields = column_fields.filter(function(v, index){
if (v.length === 0) {columns.splice(index, 1);
}
return v.length > 0;});
let csv = columns.join(",") + "\n";
for (let i = 0; i < clean_list.length; i++) {
let row = clean_list[i];
let row_csv = [];
for (const key in row) {
let column = row[key];
if (fields.includes(key)) {
row_csv.push('"' + column + '"');
}
}
csv = csv + row_csv.join(',') + "\n";
}
return csv;
}
return this;
};