text stringlengths 7 3.69M |
|---|
import Vue from 'vue'
import App from './App'
import uView from "components/uview-ui";
Vue.use(uView);
// 全局正则验证
import reg from 'plugins/regular.js';
Vue.prototype.reg = reg;
// 全局通用方法
import common from 'plugins/public.js';
Vue.prototype.common = common;
// 全局发起请求
import axios from 'plugins/http.js';
Vue.prototype.$axios = axios;
//引入vuex
import store from 'store';
// 全局mixins
import global_minxins from "@/mixin/global_minxins.js";
Vue.mixin(global_minxins);
Vue.config.productionTip = false;
App.mpType = 'app';
const app = new Vue({
...App,
store
});
app.$mount(); |
var chalk = require('chalk');
// connect to DB
// create app (require in express and and plug it into server)
// start server
var server = require('http').createServer();
var createApplication = function () {
// require in express app
var app = require('./app')
// attach it
server.on('request', app);
};
var startServer = function(){
var PORT = process.env.PORT || 1337;
server.listen(PORT, function(){
console.log(chalk.blue('Server started on port', chalk.magenta(PORT)));
})
}
require('../database')
.then(createApplication())
.then(startServer()); |
const knex = require('./knex.js').knex
function Notes() {
return knex('notes')
}
function getAll() {
return Notes().select()
}
function getSingle(noteId) {
return Notes().where('id', parseInt(noteId)).first()
}
function add(note) {
return Notes().insert(note, 'id')
}
module.exports = {
getAll: getAll,
getSingle: getSingle,
add: add
}
|
/**
* 用户修改个人信息的模块
*
*/
const User = require('../models/users');
const fs = require('fs');
/**
* 修改用户信息
* 函数 updateUserProfile
* 请求路径 /profile
* 请求类型 post
*/
exports.updateUserProfile = function(req, res) {
// 解构body
let { _id, nickname, gender } = req.body;
// 文件上传
let file = req.file;
if (file) {
var filename = file.originalname;
var ext = filename.slice(filename.lastIndexOf('.'));
var fpath = file.path;
fs.readFile(fpath, (err, data) => {
if (err) return console.log('文件读取失败');
fs.writeFile(fpath + ext, data, (err) => {
if (err) return console.log('server is error');
fs.unlinkSync(file.path)
console.log('file success')
})
});
}
// 头像路径
var avatar = '\\' + fpath + ext;
// 根据id更新一条数据
User.findByIdAndUpdate(_id, { nickname, gender, avatar }, (err, ret) => {
if (err) return console.log('数据库连接失败');
// 操作成功
if (ret) {
// 刷新页面
req.session.user.nickname = nickname;
req.session.user.gender = gender;
req.session.user.avatar = avatar;
res.redirect('/settings/profile');
}
});
} |
/*
* Speichert eine Kontaktliste in local storage des Browers.
*
*/
class KontakteSpeicher {
/**
* Lädt die Daten aus dem local storage in das '_kontakte'-Array.
*/
constructor() {
this._kontakte = [];
if (typeof(Storage) !== "undefined") {
try {
var i;
this.laden();
for (i = 0; i < this._kontakte.length; ++i) {
var p = this._kontakte[i];
console.log('Kontakt: ' + p.toString());
}
} catch (error) {
alert(error);
}
} else {
alert("Sorry, your browser does not support web storage…");
}
}
/*
* Methoden zum Zugriff auf die Kontaktliste
*/
/**
* Liefert den Kontakt mit der gegebenen id.
*/
findeKontaktZuId(id) {
this.laden();
var kontakt = this._kontakte[id];
return kontakt;
}
/**
* Liefert alle Kontakte als Array.
*/
findeAlle() {
this.laden();
var ergebnis = [];
var i, j = 0;
for (i = 0; i < this._kontakte.length; ++i) {
if (this._kontakte[i].id !== -1) {
ergebnis[j++] = this._kontakte[i];
}
}
ergebnis.sort(
function(p1, p2) {
return p1.id - p2.id;
}
);
return ergebnis;
}
/**
* Liefert ein Array von Kontakten, die zu den übergebenen Filter-
* und Sortierkriterien passen.
*/
findeZuFilterUndSortiere(name, ort, sortierung) {
this.laden();
var ergebnis = [];
var i, j = 0;
for (i = 0; i < this._kontakte.length; ++i) {
if (this._kontakte[i].id !== -1) {
if (this.filter(this._kontakte[i], name, ort)) {
ergebnis[j++] = this._kontakte[i];
}
}
}
this.sortiereKontaktListe(ergebnis, sortierung);
return ergebnis;
}
/**
* Speichert einen neuen Kontakt und vergibt dabei eine ID für den Kontakt.
* Als ID wird die nächste freie Index-Position im Kontakte-Array verwendet.
*/
neuerKontakt(kontakt) {
this.laden();
var i;
for (i = 0; i < this._kontakte.length; ++i) {
if (this._kontakte[i].id == -1) {
break;
}
}
kontakt.id = i;
this._kontakte[kontakt.id] = kontakt;
this.speichern();
}
/**
* Ersetzt den bestehenden Kontakt durch den übergebenen und
* speichert.
*/
aktualisiereKontakt(kontakt) {
this.laden();
if (this.findeKontaktZuId(kontakt.id) !== "undefined") {
this._kontakte[kontakt.id] = kontakt;
this.speichern();
}
};
/**
* Löscht den Kontakt mit der ID 'id', falls er existiert.
* Der Kontakt wird nur logisch gelöscht, d.h. die Index-Position im Array
* wird mit -1 (=frei) markiert.
*/
loescheKontakt(id) {
this.laden();
if (this.findeKontaktZuId(id) !== "undefined") {
this._kontakte[id].id = -1;
this.speichern();
}
}
/*
* Laden und Speichern in local storage
*/
speichern() {
localStorage.setItem('kontakte', JSON.stringify(this._kontakte));
}
laden() {
let kontakteLS = localStorage.kontakte;
if (kontakteLS) {
// String in Objekt-array umwandeln
let array = JSON.parse(kontakteLS);
// geladenene Objekte in Kontakt-Objekte umwandeln
// => dann hat jedes Objekt z.B. eine pruefe-Methode
for (let i = 0; i < array.length; ++i) {
this._kontakte[i] = new Kontakt(
array[i]._id,
array[i]._name,
array[i]._email,
array[i]._ort,
array[i]._plz,
array[i]._strasse);
}
} else {
// leeren LocalStorage-Eintrag erzeugen
this.speichern();
}
console.log('kontakte in LocalStorage: ', kontakteLS);
}
/*
* Hilfsfunktionen
*/
filter(adresse, name, ort) {
var ergebnis = true;
if (name != "" || ort != "") {
if (name != "") {
var indexName = adresse.name.indexOf(name);
ergebnis = (indexName == 0);
}
if (ort != "") {
var indexOrt = adresse.ort.indexOf(ort);
ergebnis = ergebnis && (indexOrt == 0);
}
}
return ergebnis;
};
sortiereKontaktListe(liste, sortierung) {
var sortierFunktion;
if (sortierung == 'Name') {
sortierFunktion = function(p1, p2) {
return -p1.name.localeCompare(p2.name);
};
} else if (sortierung == 'Ort') {
sortierFunktion = function(p1, p2) {
return -p1.ort.localeCompare(p2.ort);
};
} else if (sortierung == 'PLZ') {
sortierFunktion = function(p1, p2) {
return -(parseInt(p1.plz) - parseInt(p2.plz));
};
}
liste.sort(sortierFunktion);
}
}
|
import { checkAtRule } from '../../utils/util.js';
export default [
checkAtRule('font-face'),
];
|
import React from "react";
import BaseLayout from "../layouts/Base";
import PleaseTranslate from "../PleaseTranslate";
import LanguageNotAvailable from "../LanguageNotAvailable";
import OtherMeasurements from "../OtherMeasurements";
import DefaultDocumentation from "../docs/Default";
import PatternOptions from "../docs/PatternOptions";
import PatternOption from "../docs/PatternOption";
import DraftSetting from "../docs/DraftSetting";
export default data => {
const { language, page } = data.pageContext;
const { frontmatter, html, tableOfContents, fileAbsolutePath } = page;
let main = "";
let childProps = {
languageNotAvailable: "",
pleaseTranslate: "",
measurementsBox: "",
isMeasurement: false,
wrapReverse: true,
tocBox: "",
language,
page,
frontmatter,
html,
tableOfContents,
fileAbsolutePath
};
// Language available?
if (language !== page.language) {
childProps.languageNotAvailable = (
<LanguageNotAvailable language={language} />
);
childProps.pleaseTranslate = (
<PleaseTranslate filePath={fileAbsolutePath} language={language} />
);
}
// Breadcrumbs
let docsCrumb = { link: "/docs", label: "app.docs" };
if (
typeof frontmatter.breadcrumbs !== "undefined" &&
typeof frontmatter.breadcrumbs[0] !== "undefined" &&
frontmatter.breadcrumbs[0].link !== "/docs"
)
childProps.frontmatter.breadcrumbs.unshift(docsCrumb);
else childProps.frontmatter.breadcrumbs = [docsCrumb];
if (typeof frontmatter.measurement === "string") {
// Measurements
childProps.isMeasurement = true;
childProps.measurementsBox = <OtherMeasurements language={language} />;
} else if (typeof frontmatter.patternOptions === "string")
main = (
<PatternOptions {...childProps} pattern={frontmatter.patternOptions} />
);
else if (
typeof frontmatter.pattern === "string" &&
typeof frontmatter.option === "string"
)
main = (
<PatternOption
{...childProps}
pattern={frontmatter.pattern}
option={frontmatter.option}
/>
);
else if (typeof frontmatter.setting === "string")
main = (
<DraftSetting
{...childProps}
setting={frontmatter.setting}
language={language}
/>
);
else main = <DefaultDocumentation {...childProps} />;
return <BaseLayout>{main}</BaseLayout>;
};
|
angular.module('weatherApp')
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/');
$stateProvider.state('home', {
url : '/',
templateUrl : 'components/home/home.html'
});
}); |
"use strict";
module.exports = {
db: 'mongodb://localhost:27017/sampleDatabase',
port:8080,
QToInferenceImages:"processQ",
InferencedImagesQ:"processedQ",
rabbitmqURL:"amqp://localhost"
}; |
var exp = module.exports;
var dispatcher = require('./dispatcher');
exp.registration = function(session, msg, app, cb) {
var registrationServers = app.getServersByType('registration');
if(!registrationServers || registrationServers.length === 0) {
cb(new Error('can not find registration servers.'));
return;
}
var res = dispatcher.dispatch(session.get('uid'), registrationServers);
cb(null, res.id);
};
exp.lobby = function(session, msg, app, cb) {
var lobbyServers = app.getServersByType('lobby');
if(!lobbyServers || lobbyServers.length === 0) {
cb(new Error('can not find lobby servers.'));
return;
}
var res = dispatcher.dispatch(session.get('uid'), lobbyServers);
cb(null, res.id);
};
exp.chat = function(session, msg, app, cb) {
var chatServers = app.getServersByType('chat');
if(!chatServers || chatServers.length === 0) {
cb(new Error('can not find chat servers.'));
return;
}
var res = dispatcher.dispatch("mainRoom", chatServers);
cb(null, res.id);
};
exp.editor = function(session, msg, app, cb) {
var editorServers = app.getServersByType('editor');
if(!editorServers || editorServers.length === 0) {
cb(new Error('can not find editor servers.'));
return;
}
var res = dispatcher.dispatch(session.get('uid'), editorServers);
cb(null, res.id);
};
exp.assets = function(session, msg, app, cb) {
var assetsServers = app.getServersByType('assets');
if(!assetsServers || assetsServers.length === 0) {
cb(new Error('can not find assets servers.'));
return;
}
var res = dispatcher.dispatch(session.get('uid'), assetsServers);
cb(null, res.id);
}; |
$(function () {
var $form = $('#modal-form');
var $btn = $("#submit");
$form.validate({
rules: {
merchCo: {
required: true,
rangelength: [5, 15],
remote: {
url: ctx + "/validate/merchant",
type: 'post',
data: {
'merchCo': function () {
return $('#merchCo').val()
},
'oldMerchCo': function () {
return $('#old-merchCo').val();
}
}
}
},
merchNm: {
required: true,
maxlength: 64
},
password: {
required: true,
isPassword: true
},
rePassword: {
required: true,
equalTo: "#password"
},
charset: {
required: false,
maxlength: 8
},
ftpType: {
required: true
},
isDebug: {
required: true,
range: [0, 1]
},
ftpHost: {
required: false,
maxlength: 20
},
ftpUser: {
required: false,
maxlength: 64
},
ftpPwd: {
required: false,
maxlength: 128
},
ftpDir: {
required: false,
maxlength: 128
}
},
submitHandler: function (form, event) {
event.preventDefault();
$btn.button('loading');
$(form).ajaxSubmit({
dataType: 'json',
success: function (response) {
if (response.errCode == 'success') {
window.location.reload();
} else {
Message.error(response.errMsg);
$btn.button('reset');
}
},
error: function () {
Message.error("服务器内部错误,请稍后再试。");
$btn.button('reset');
}
});
},
errorPlacement: function (error, element) {
error.appendTo(element.parent());
},
errorElement: "div",
errorClass: "error"
});
}); |
define([
"jquery", "inputmasklib", "ko", "maskmoneylib"
],
function($, inputmasklib, ko, maskmoneylib) {
"use strict";
// Configura Inputmask
inputmasklib.extendDefaults({
'jitMasking': true,
'greedy': false
});
// Cria funções de máscaras
ko.telephoneMask = function (obj) {
$(obj).inputmask({
mask: ["(99) 9999-9999", '(99) 99999-9999']
});
};
ko.vatIdMask = function (obj) {
$(obj).inputmask({
mask: ['999.999.999-99', '99.999.999/9999-99']
});
};
ko.cnpjMask = function (obj) {
$(obj).inputmask('99.999.999/9999-99');
};
ko.cpfMask = function (obj) {
$(obj).inputmask('999.999.999-99');
};
ko.postcodeMask = function (obj) {
$(obj).inputmask('99999-999');
};
ko.dateMask = function (obj) {
$(obj).inputmask('99/99/9999');
};
ko.moneyPointMask = function (obj) {
$(obj).maskMoney({thousands:'', decimal:'.'});
}
});
|
var mongoose = require('mongoose');
/*exports.getallData = function(req,res){
console.log("All Data");
UserModel.find().lean().exec(function(err,user){
if(!err){
res.send(user);
}
else
{
console.log("Success!");
}
})
}*/
|
function roleArrayToString(roles) {
let roleString = "";
for (let i = 0; i < roles.length; i++) {
roleString += roles[i].name;
if (i !== roles.length - 1) {
roleString += ", "
} else {
roleString += "."
}
}
return roleString;
}
function randomNumberInRange(range) {
return Math.floor(Math.random() * Math.floor(range));
}
module.exports.randomNumberInRange = randomNumberInRange;
module.exports.roleArrayToString = roleArrayToString; |
import React from "react";
import style from'./Card.module.css';
export default function Card({name,image,temperament,weight}){//destucturin de la info de cada card
return(
<div>
<div className={style.box}>
<div className={style.ca}>
<img className={style.image} src={image} alt='Not found'></img>
<h4 className={style.breed}>{name}</h4>
</div>
<div className={style.overlay}>
<div className={style.text}>
<span>Weight:</span>
<h3 className={style.peso}>
{weight} (Lb)
</h3>
<span>Temperament:</span>
<h2 className={style.titleTemps}>
{temperament}
</h2>
</div>
</div>
</div>
</div>
)
}; |
const assert = require('better-assert');
const cli = require('../cli');
const findRegex = require('../find');
describe('findRegex', function() {
describe('extractRegexesFromSource()', function() {
it('should be able to return nothing', function() {
assert([...findRegex.extractRegexesFromSource('abc')].length == 0);
});
it('should find a literal regex', function() {
let found = [...findRegex.extractRegexesFromSource('const a = /ab+c/g')];
assert(found.length == 1);
assert(found[0].pattern == 'ab+c');
assert(found[0].flags == 'g');
assert(found[0].lineno == 1);
});
it('should find the RegExp constructor', function() {
let found = [...findRegex.extractRegexesFromSource('const a = [\nnew RegExp("one"),\nRegExp("two", "flags")]')];
assert(found.length == 2);
assert(found[0].pattern == 'one');
assert(found[0].flags == '');
assert(found[0].lineno == 2);
assert(found[1].pattern == 'two');
assert(found[1].flags == 'flags');
assert(found[1].lineno == 3);
});
var burriedTests = [
"var a = {b: /abc/}",
"function x() { return function* () { yield /abc/ } }",
"function x(y = /abc/) { return y; }",
"a ? /abc/ : null",
"if(/abc/){}", // a bit stupid
"[12, abc, /abc/, ...ghi]",
"for (const a of x.match(/abc/)) {}"
]
burriedTests.forEach(function (code) {
it('should find burried regex ' + code, function() {
let found = [...findRegex.extractRegexesFromSource(code)];
assert(found.length == 1);
assert(found[0].pattern == 'abc');
assert(found[0].flags == '');
});
});
});
});
describe("cli", function() {
describe("parseCode()", function() {
it('should find a literal regex', function() {
let found = [...cli.parseCode('/a(((b)+c))/im', 'fname')];
assert(found.length == 1);
const output = JSON.parse(found[0]);
assert(output.pattern == 'a(((b)+c))');
assert(output.flags == 'im');
assert(output.lineno == '1');
assert(output.filename == 'fname');
assert(!output.error);
});
it('should return errors if necessary', function() {
let found = [...cli.parseCode('/!#~')];
assert(found.length == 1);
assert(JSON.parse(found[0]).error);
assert(!JSON.parse(found[0]).pattern);
});
});
});
|
import axios from "axios";
export default {
//PROJECTS
// Gets all projects
getProjects: function() {
return axios.get("/api/projects");
},
// Gets the project with the given id
getProject: function(id) {
return axios.get("/api/projects/" + id);
},
// Deletes the project with the given id
deleteProject: function(id) {
return axios.delete("/api/projects/" + id);
},
// Updates a project to the database
updateProject: function(id, projectData) {
console.log("API>updateProject");
console.log("projectData:");
console.log(projectData);
return axios.put("/api/projects/" + id, projectData);
},
// Saves a project to the database
saveProject: function(projectData) {
return axios.post("/api/projects", projectData);
},
// DAILY ACTIONS
// Gets the action with the given id
getDailyActions: function(id) {
return axios.get("/api/dailyActions/" + id);
},
// Updates a project to the database
updateDailyActions: function(id, dailyActionData) {
return axios.put("/api/dailyActions/" + id, dailyActionData);
},
// ACTIONS
// Gets all actions
getActions: function() {
return axios.get("/api/actions");
},
// Gets the action with the given id
getAction: function(id) {
return axios.get("/api/actions/" + id);
},
// Deletes the action with the given id
deleteAction: function(id) {
return axios.delete("/api/actions/" + id);
},
// Saves a action to the database
saveAction: function(actionData) {
return axios.post("/api/actions", actionData);
}
};
|
/* eslint-disable import/no-anonymous-default-export */
import db from './03.01-db';
const keyPrefix = 'todos';
const makeKey = (key) => `${keyPrefix}:${key}`;
let autoId = 1;
export async function addTodo(todo) {
const id = autoId++;
const insertable = {
...todo,
id
};
await db.set(makeKey(id), insertable);
}
export function getTodo(id) {
return db.get(makeKey(id));
}
export default {
addTodo,
getTodo
};
|
app.controller("dettaglio", function($scope,$http, $routeParams){
$scope.toSend = {}
$http.get("https://jsonplaceholder.typicode.com/todos/"+$routeParams.id).then(
//primo parametro then
function successCallbach(datiRicevutiDalBackend) {
$scope.dettaglioUtente=datiRicevutiDalBackend.data;
$scope.toSend.title = $scope.dettaglioUtente.title
},
//secondo parametro then
function errorCallbeck(response) {
alert("Si è verificato un errore!");
}
)
$scope.inviaDati = function() {
$http.post("https://jsonplaceholder.typicode.com/posts",$scope.toSend).then(
//primo parametro then
function successCallbach(data) {
alert($scope.toSend.nome + " " +$scope.toSend.email + " ha modificato correttamente il titolo " );
},
//secondo parametro then
function errorCallbeck(response) {
alert("Si è verificato un errore!");
}
)
}
}) |
function showNumberWidthAnimation(i, j, num) {
var numberCell = $(`#number-cell-${i}-${j}`);
numberCell.css({
backgroundColor: getNumberBackgroundColor(num),
color: getNumberColor(num)
});
numberCell.text(num);
numberCell.animate({
width: cellSideLength,
height: cellSideLength,
top: getPositionXY(i),
left: getPositionXY(j)
}, 50);
}
function showMoveAnimation(formx, formy, tox, toy) {
var numberCell = $(`#number-cell-${formx}-${formy}`);
numberCell.animate({
top: getPositionXY(tox),
left: getPositionXY(toy)
}, 200);
}
|
var express = require('express');
var router = express.Router();
var dataBike = [
{name:"BIKO45" ,url:"/images/bike-1.jpg" ,price:679 },
{name:"ZOOK07" ,url:"/images/bike-2.jpg" ,price:999 },
{name:"TITANS" ,url:"/images/bike-3.jpg" ,price:799 },
{name:"CEWO" ,url:"/images/bike-4.jpg" ,price:1300 },
{name:"AMIG039" ,url:"/images/bike-5.jpg" ,price:479 },
{name:"LIK099" ,url:"/images/bike-6.jpg" ,price:869 }
];
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {dataBike:{name:'', url:'', price:''}});
});
/* GET shop page. */
router.get('/shop', function(req, res, next) {
res.render('shop', { title: 'Shop' });
});
module.exports = router;
|
var mongoose = require("mongoose");
var cpuCoolerSchema = new mongoose.Schema({
brand: {type: String, required: true},
name: {type: String, required: true},
type: {type: String, required: true},
fanSize: {type: Number, required: true},
tdp: {type: Number, required: true},
price: {type: Number, required: true}
});
module.exports = mongoose.model("CpuCooler", cpuCoolerSchema); |
//** Import Modules */
import React from 'react';
import { useHistory } from 'react-router-dom';
import { Dropdown } from 'antd';
//** Import Assets */
import completeIcon from '../../../assets/images/gamemodeimg/completed.png';
// Following code is commented out to prevent warnings during compilation
export default function GameMissionProgress(props) {
// Get the history object
const history = useHistory();
// const [isModalVisible, setIsModalVisible] = useState(false);
// Get the current state
const { currentStep } = props;
// Get the base URL
const { baseURL } = props;
// Functions to handle what each button does
const handleStepClick = (step, requirementMet) => {
if (requirementMet) {
props.updateCurStep(step);
history.push(`${baseURL}/${step}`);
} else {
const modalData = {
title: 'You must read before advancing!',
description: 'In order to complete the mission, reading is a MUST!',
buttonTxt: 'Close',
};
props.enableModalWindow(modalData);
}
};
const showGameTips = () => {
return (
<div className="game-tips-container">
<div className="game-tips-text">
<p className="game-tips-text-p">
<img
style={{ width: '48px', height: '48px' }}
src="https://img.icons8.com/flat-round/64/000000/wide-right-arrow.png"
alt="wide right arrow"
/>{' '}
Click on the Read, Draw or Write buttons to navigate through the
mission.
</p>
<p className="game-tips-text-p">
<img
style={{ width: '48px', height: '48px' }}
src="https://img.icons8.com/flat-round/64/000000/wide-right-arrow.png"
alt="wide right arrow"
/>{' '}
You have to complete your current step before you can move on to the
next step
</p>
<p className="game-tips-text-p">
<img
style={{ width: '48px', height: '48px' }}
src="https://img.icons8.com/flat-round/64/000000/wide-right-arrow.png"
alt="wide right arrow"
/>{' '}
Once you have completed all the steps, you can click back and forth
between all of them.
</p>
</div>
<button className="game-tips-gotit-btn">Got it!</button>
</div>
);
};
return (
<div>
<div>
<Dropdown overlay={showGameTips} trigger={['click']}>
{/*Lightbulb Icon*/}
<div className="game-tips-icon-container">
<img
style={{ width: '40px', height: '38px', cursor: 'pointer' }}
src="https://img.icons8.com/external-flat-juicy-fish/60/000000/external-crisis-crisis-management-flat-flat-juicy-fish-6.png"
alt="lightbulb"
/>
<p className="tips">Tips</p>
</div>
</Dropdown>
</div>
<div id="mission-progress">
<h3>Your Mission</h3>
<div className="steps">
<StepButton
stepNum="1"
stepName="read"
currentStep={currentStep}
handleStepClick={handleStepClick}
isComplete={props.submissionData.HasRead}
stepBGColor="#c6fd7e"
/>
<StepButton
stepNum="2"
stepName="draw"
currentStep={currentStep}
handleStepClick={handleStepClick}
isComplete={props.submissionData.HasDrawn}
requiredStep={props.submissionData.HasRead}
stepBGColor="#ff845d"
/>
<StepButton
stepNum="3"
stepName="write"
currentStep={currentStep}
handleStepClick={handleStepClick}
isComplete={props.submissionData.HasWritten}
requiredStep={props.submissionData.HasRead}
stepBGColor="#ffd854"
/>
</div>
</div>
</div>
);
}
//** Component for the step buttons */
const StepButton = props => {
const { stepNum, stepName, handleStepClick, currentStep } = props;
const completedClass = props.isComplete ? 'completed' : '';
const activeClass = currentStep === stepName ? 'active' : '';
const stepBGColor =
props.stepBGColor !== undefined ? props.stepBGColor : '#ffffff';
const requirementMet =
props.requiredStep !== undefined ? props.requiredStep : true;
return (
<button
id={`step-${stepNum}`}
className={`step ${activeClass} ${completedClass}`}
onClick={() => handleStepClick(stepName, requirementMet)}
>
<span style={{ backgroundColor: stepBGColor }}>
{props.isComplete ? (
<img src={completeIcon} alt="Completed" />
) : (
stepNum
)}
</span>
{stepName}
</button>
);
};
|
const sequelize = require('sequelize');
const model = require('../../config/model');
const notify = model.define('notify', {
message : { type : sequelize.STRING, allowNull : false },
type : { type : model.purpose, allowNull : false }
});
module.exports = notify;
|
'use strict'
import React, { Component } from 'react'
import { BackAndroid } from 'react-native'
import { connect } from 'react-redux'
import Toast from 'react-native-root-toast'
import * as types from './constant'
import {
navigationPush,
tabbarSwitch,
navigationLoginDefault
} from './action'
import MainPage from './mainpage'
class MainContainer extends Component {
constructor(props) {
super(props)
this.handleBack = this._handleBack.bind(this, props.tabRoutes)
this.pendingExitTab = ''
this.pendingExit = 0 // 等待退出应用标记
}
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', this.handleBack)
}
componentWillUnmount() {
BackAndroid.removeEventListener('hardwareBackPress', this.handleBack)
this.props.navigationLoginReset()
}
_handleBack (tabRoutes) {
// 判断当前处在哪个tab的导航内
let navigatorName
tabRoutes.forEach((_tab) => {
let tabName = getTabName(_tab.name)
let constantType = getConstantType(_tab.name)
if (tabName === this.props.selectedTab) {
navigatorName = constantType
}
})
if (!navigatorName) {
return true
}
let navigationState = this.props.navigationStates[navigatorName]
if (navigationState.index > 0) {
// 不在首页, 则执行当前导航的POP
this.props.navigationPop(types.NAVIGATOR_NAME_HOME)
return true
}
let currentTime = new Date().getTime()
if (this.props.selectedTab !== this.pendingExitTab || currentTime - this.pendingExit > 1500) {
Toast.show('再按一次退出应用', {
duration: Toast.durations.SHORT, // toast显示时长
position: Toast.positions.BOTTOM, // toast位置
shadow: false, // toast是否出现阴影
animation: true, // toast显示/隐藏的时候是否需要使用动画过渡
hideOnPress: true, // 是否可以通过点击事件对toast进行隐藏
delay: 0 // toast显示的延时
})
this.pendingExitTab = this.props.selectedTab
this.pendingExit = currentTime
return true
}
return false
}
handleTabPress(tabProps) {
switch (tabProps.key) {
case 'UserTab':
let hasLogin = true
// 如果未登录, 直接切换tab, 否则弹出登录页
if (hasLogin) {
this.props.tabbarSwitch(tabProps)
} else {
this.props.navigationLoginDefault()
}
break
default:
this.props.tabbarSwitch(tabProps)
}
}
render() {
return (
<MainPage selectedTab={this.props.selectedTab}
tabRoutes={this.props.tabRoutes}
onTabPress={this.handleTabPress.bind(this)} />
)
}
}
function getTabName (name) {
return name.replace(/(\w)/, e => e.toUpperCase()) + 'Tab'
}
function getConstantType (name) {
return `NAVIGATOR_NAME_${name.toUpperCase()}`
}
function mapStateToProps(state) {
return {
navigationStates: state.navigation.navigationStates,
selectedTab: state.navigation.tabbarState.selectedTab
}
}
export default connect(
mapStateToProps, {
navigationPush,
tabbarSwitch,
navigationLoginDefault
}
)(MainContainer) |
import { Component } from 'react';
import * as React from 'react'
import { Platform, StyleSheet, View,
Image,} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {connect} from 'react-redux';
import Login from './screens/Login';
import Register from './screens/Register';
import ResetPassword from './screens/Reset-Password/ResetPassword';
import ResetPasswordOtp from './screens/Reset-Password/ResetPasswordOtp';
import ResetPasswordNew from './screens/Reset-Password/ResetPasswordNew';
import ResetPasswordSuccess from './screens/Reset-Password/ResetPasswordSucces';
import FooterTab from './components/Footer';
import Dashboard from './screens/Student/Dashboard/Dashboard';
import Chat from './screens/Chats/Chat'
import ChooseFriends from './screens/Chats/ChooseFriends'
import MyClass from './screens/Student/Activity/MyClass';
import ClassDetail from './screens/Student/Activity/ClassDetail';
import ClassProgress from './screens/Student/Activity/ClassProgress';
import Activity from './screens/Student/Activity/Activity'
import ForYou from './screens/Student/Dashboard/ForYou'
import Member from './screens/Student/Activity/Member'
class App extends Component
{
constructor(){
super();
this.state={
isVisible : true,
jwt: '',
loading: true
}
this.newJWT = this.newJWT.bind(this);
}
newJWT(jwt){
this.setState({
jwt: jwt
});
}
Hide_Splash_Screen=()=>{
this.setState({
isVisible : false
});
}
componentDidMount(){
var that = this;
setTimeout(function(){
that.Hide_Splash_Screen();
}, 5000);
}
render()
{
const {Navigator, Screen} = createStackNavigator();
let Splash_Screen = (
<View style={styles.SplashScreen_RootView}>
<View style={styles.SplashScreen_ChildView}>
<Image source={require('./assets/img/logo-GrowEd.png')} />
</View>
</View> )
return(
<NavigationContainer style={styles.NavigationContainer}>
<Navigator headerMode={'none'}>
{!this.props.authReducers.isLogin ? (
<>
<Screen name="Login" component={Login} />
<Screen name="Register" component={Register} />
<Screen name="ResetPassword" component={ResetPassword} />
<Screen name="ResetPasswordOtp" component={ResetPasswordOtp} />
<Screen name="ResetPasswordNew" component={ResetPasswordNew} />
<Screen name="ResetPasswordSuccess" component={ResetPasswordSuccess} />
</> ) : (
<>
<Screen name="FooterTab" component={FooterTab} />
<Screen name="Dashboard" component={Dashboard} />
<Screen name="ForYou" component={ForYou} />
<Screen name="Chat" component={Chat} />
<Screen name="ChooseFriends" component={ChooseFriends} />
<Screen name="Activity" component={Activity} />
<Screen name="MyClass" component={MyClass} />
<Screen name="ClassDetail" component={ClassDetail} />
<Screen name="ClassProgress" component={ClassProgress} />
<Screen name="Member" component={Member} />
</>
)}
</Navigator>
{
(this.state.isVisible === true) ? Splash_Screen : null
}
</NavigationContainer>
);
}
}
const styles = StyleSheet.create(
{
NavigationContainer: {
backgroundColor: '#F9F9F9',
},
SplashScreen_RootView:
{
justifyContent: 'center',
flex:1,
position: 'absolute',
width: '100%',
height: '100%',
},
SplashScreen_ChildView:
{
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#CBDAF3',
flex:1,
},
});
const mapStateToProps = state => {
return {
authReducers: state.authReducers,
};
};
// const mapDispatchToProps = dispatch => {
// return {
// onSnackbarHide: () => dispatch(snackbarHide()),
// };
// };
const ConnectedApp = connect(mapStateToProps)(App);
export default ConnectedApp;
|
$(document).ready(function () {
$(".tab-content > .tab-pane > .panel").niceScroll({
cursorcolor: "#90A4AE",
cursorwidth: "8px",
horizrailenabled: false
});
$('#btnProfileUpload').change(function () {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgPhoto').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
$('#btnCustomerProfileUpload').change(function () {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgCustomerPhoto').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
$('#btnLeadProfileUpload').change(function () {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgLeadPhoto').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
$('.remove-pic').click(function () {
$('#imgPhoto').attr('src', '../Theme/images/profile-pic.jpg');
$('#imgCustomerPhoto').attr('src', '../Theme/images/profile-pic.jpg');
$('#imgLeadPhoto').attr('src', '../Theme/images/profile-pic.jpg');
});
//Fetching API url
var apirul = $('#hdApiUrl').val();
CheckSection();
//For Loading The items section on page load(Initial Load)
RefreshTableItem();
loadAdditionalData();
loadSupplierCountry();
loadCustomerCountry();
loadLeadCountry();
//Gets the datatable for the selected li
$('#menu > li').click(function () {
var selected = $(this).attr('id');
switch (selected) {
case 'Item':
RefreshTableItem();
loadAdditionalData();
break;
case 'Brand':
RefreshTableBrand();
break;
case 'Group':
RefreshTableGroup();
break;
case 'Category':
RefreshTableCategory();
break;
case 'Type':
RefreshTableType();
break;
case 'Tax':
RefreshTableTax();
break;
case 'Unit':
RefreshTableUnit();
break;
case 'Vehicles':
RefreshTableVehicle();
break;
case 'Despatch':
RefreshTableDespatch();
break;
case 'Supplier':
RefreshTableSuppliers();
loadSupplierCountry();
case 'Customer':
RefreshTableCustomer();
loadCustomerCountry();
break;
case 'Leads':
RefreshTableLead(null, null, null, null);
loadLeadCountry();
loadLeadEmployee();
break;
//case 'service':
// RefreshTableService();
// loadAdditionalData();
// break;
default:
break;
}
});
$('#Lead').click(function () {
alert('');
})
$('#serviceTab').click(function () {
RefreshTableService();
loadAdditionalData();
})
///* Functions to load the Tables *///
//Brand Table
function RefreshTableBrand() {
$.ajax({
url: apirul + 'api/Brands/get',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableBrand').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: function (inventories) { return '<a href="#" class="edit-entry underline">' + inventories.Name + '</a>' } },
{ data: 'Order' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-brand"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-brand"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Service Table
function RefreshTableService() {
$.ajax({
url: apirul + 'api/Items/GetDetailsForService',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableService').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ItemID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'SellingPrice' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-service"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-service"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Item table
function RefreshTableItem() {
$.ajax({
url: apirul + 'api/Items/get/',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableItem').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ItemID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'TaxPercentage' },
{ data: 'Brand' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-Item"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-item"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Group Table
function RefreshTableGroup() {
$.ajax({
url: apirul + 'api/Groups/get/',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableGroup').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Order' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-Group"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-group"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Category Table
function RefreshTableCategory() {
$.ajax({
url: apirul + 'api/Categories/get/',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableCategory').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Order' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-Category"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-category"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Product type Table
function RefreshTableType() {
$.ajax({
url: apirul + 'api/ProductTypes/get/',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableType').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Order' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-Type"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-type"><i class="md md-delete text-danger"></i></a>'
}
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Tax Table
function RefreshTableTax() {
$.ajax({
url: apirul + 'api/Taxes/get/',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableTax').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Percentage' },
{ data: 'Type' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-tax"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-tax"><i class="md md-delete text-danger"></i></a>'
}
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Unit Table
function RefreshTableUnit() {
$.ajax({
url: apirul + 'api/units/get/',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableUnit').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'ShortName' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-Unit"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-unit"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Vehicle Table
function RefreshTableVehicle() {
$.ajax({
url: apirul + 'api/Vehicles/get',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableVehicle').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Number' },
{ data: 'Type' },
{ data: 'Owner' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-vehicle"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-vehicle"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Despatch Table
function RefreshTableDespatch() {
$.ajax({
url: apirul + 'api/despatch/get',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableDespatch').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Address' },
{ data: 'MobileNo' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-despatch"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-despatch"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Suppliers Table
function RefreshTableSuppliers() {
$.ajax({
url: apirul + 'api/Suppliers/get/',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableSuppliers').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Phone1' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-Supplier"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-supplier"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Customer Table
function RefreshTableCustomer() {
$.ajax({
url: apirul + 'api/Customers/get/',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableCustomer').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Phone1' },
{ data: 'Status', 'render': function (status) { if (status == 1) return '<label class="label label-success"> Active  </label>'; else return '<label class="label label-default">Inactive</label>' } },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-customer"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-customer"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//Lead Table
function RefreshTableLead(status, employeeId, from, to) {
$.ajax({
url: apirul + 'api/Leads/GetLeads/?Status=' + status + '&EmployeeId=' + employeeId + '&From=' + from + '&To=' + to,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
$('#tableLead').dataTable({
responsive: true,
dom: 'Blfrtip',
lengthMenu: [[10, 25, 50, -1], ['10 rows', '25 rows', '50 rows', 'Show all']],
buttons: ['excel', 'csv', 'print'],
data: response,
destroy: true,
columns: [
{ data: 'ID', className: 'hidden-td' },
{ data: 'Name' },
{ data: 'Phone1' },
{
data: function () {
return '<a href="#" data-toggle="tooltip" data-placement="auto left" title="Edit" class="edit-entry-Lead"><i class="md md-edit"></i></a><span class="divider">   </span><a data-toggle="tooltip" data-placement="auto left" title="Delete" href="#" class="delete-entry-Lead"><i class="md md-delete text-danger"></i></a>'
},
sorting: false
}
],
"language": {
"paginate": {
"previous": "<<",
"next": ">>"
}
}
});
$('[data-toggle="tooltip"]').tooltip();
},
error: function (xhr) {
alert(xhr.responseText);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
}
//////* Functions to Save or Update *//////
//Saves Brand
$('#btnAddBrand').click(function () {
var brand = {};
brand.Name = $('#txtBrandName').val();
brand.Order = $('#txtBrandOrder').val();
brand.Status = $('#ddlBrandStatus').val();
brand.ID = $('#hdnBrandID').val();
brand.CompanyId = $.cookie("bsl_1");
brand.CreatedBy = $.cookie('bsl_3');
brand.ModifiedBy = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/Brands/save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(brand),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
RefreshTableBrand();
reset();
$('#btnAddBrand').html('Save');
$('#hdnBrandID').val("0");
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Save Service
$('#btnAddService').click(function () {
var item = {};
item.Name = $('#txtServiceName').val();
item.ItemCode = $('#txtServiceItemCode').val();
item.Description = $('#txtServiceDescription').val();
item.SellingPrice = $('#txtServiceRate').val();
item.TaxId = $('#ddlServiceTax').val();
item.Status = $('#ddlServiceStatus').val();
item.ItemID = $('#hdServiceId').val();
item.IsService = 1;
item.CompanyId = $.cookie("bsl_1");
item.CreatedBy = $.cookie('bsl_3');
item.ModifiedBy = $.cookie('bsl_3');
if ($('#chkTrackService').prop('checked') == true) {
track_Inventory = 1;
}
else {
track_Inventory = 0;
}
item.TrackInventory = track_Inventory;
$.ajax({
url: apirul + 'api/Items/save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(item),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
RefreshTableService();
reset();
$('#btnAddService').html('<i></i> Save');
$('#hdServiceId').val("0");
$('.track-service').attr('checked', false);
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Saves Category
$('#btnAddCategory').click(function () {
var Category = {};
Category.Name = $('#txtCategoryName').val();
Category.Order = $('#txtCategoryOrder').val();
Category.Status = $('#ddlCategoryStatus').val();
Category.CompanyId = $.cookie("bsl_1");
Category.CreatedBy = $.cookie('bsl_3');
Category.ID = $('#hdnCategoryID').val();
Category.ModifiedBy = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/Categories/Save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Category),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
RefreshTableCategory();
reset();
$('#btnAddCategory').html('Save');
$('#hdnCategoryID').val("0");
}
else {
errorAlert(data.Message)
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Saves Group
$('#btnAddNewGroup').click(function () {
var Group = {};
Group.Name = $('#txtGroupName').val();
Group.Order = $('#txtGroupOrder').val();
Group.Status = $('#ddlGroupStatus').val();
Group.ID = $('#hdnGroupID').val();
Group.CompanyId = $.cookie("bsl_1");
Group.CreatedBy = $.cookie('bsl_3');
Group.ModifiedBy = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/Groups/Save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Group),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableGroup();
$('#btnAddNewGroup').html('Save');
$('#hdnGroupID').val("0");
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Saves Product Type
$('#btnAddType').click(function () {
var Type = {};
Type.Name = $('#txtTypeName').val();
Type.Order = $('#txtTypeOrder').val();
Type.Status = $('#ddlTypeStatus').val();
Type.CompanyId = $.cookie("bsl_1");
Type.CreatedBy = $.cookie('bsl_3');
Type.ID = $('#hdnTypeID').val();
Type.Modifiedby = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/ProductTypes/Save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Type),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableType();
$('#btnAddType').html('Save');
$('#hdnTypeID').val("0");
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Save Tax
$('#btnAddTax').click(function () {
var Tax = {};
Tax.Name = $('#txtTaxName').val();
Tax.Percentage = $('#txtTaxPercentage').val();
Tax.Type = $('#txtTaxType').val();
Tax.Status = $('#ddlTaxStatus').val();
Tax.ID = $('#hdnTaxID').val();
Tax.ModifiedBy = $.cookie('bsl_3');
Tax.CompanyId = $.cookie("bsl_1");
Tax.CreatedBy = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/Taxes/save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Tax),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
RefreshTableTax();
reset();
$('#btnAddTax').html('Save');
$('#hdnTaxID').val("0");
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Save Unit
$('#btnAddUOM').click(function () {
var Unit = {};
Unit.Name = $('#txtUOMName').val();
Unit.ShortName = $('#txtUOMShortName').val();
Unit.Status = $('#ddlUOMStatus').val();
Unit.ID = $('#hdnUnitID').val();
Unit.ModifiedBy = $.cookie('bsl_3');
Unit.CompanyId = $.cookie("bsl_1");
Unit.CreatedBy = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/Units/Save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Unit),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableUnit();
$('#btnAddUOM').html('Save');
$('#hdnUnitID').val("0");
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Save Items
$('#btnAddItem').click(function () {
var track_Inventory = 0;
//Added to check whether the item should check the stock in entry page
//If Track Inventory is true or 1 checks the stock at the time of entry
if ($('#chkTrack').prop('checked') == true) {
track_Inventory = 1;
}
else {
track_Inventory = 0;
}
var Item = {};
Item.Name = $('#txtItemName').val();
Item.ItemCode = $('#txtItemCode').val();
Item.UnitID = $('#ddlItemUOM').val();
Item.Description = $('#txtItemDescription').val();
Item.HSCode = $('#txtItemHSCode').val();
Item.OEMCode = $('#txtItemHSCode').val();
Item.TypeID = $('#ddlItemType').val();
Item.CategoryID = $('#ddlItemCategory').val();
Item.GroupID = $('#ddlItemGroup').val();
Item.BrandID = $('#ddlItemBrand').val();
Item.TaxId = $('#ddlItemTax').val();
Item.MRP = $('#txtItemMRP').val();
Item.Barcode = $('#txtItemBarcode').val();
Item.SellingPrice = $('#txtItemSP').val();
$('#lblPriceText').addClass('hidden')
Item.CostPrice = $('#txtItemCP').val();
Item.ItemCode = $('#txtItemCode').val();
Item.Status = $('#ddlItemStatus').val();
Item.ItemID = $('#hdnItemID').val();
Item.ModifiedBy = $.cookie('bsl_3');
Item.CompanyId = $.cookie("bsl_1");
Item.CreatedBy = $.cookie('bsl_3');
Item.TrackInventory = track_Inventory;
$.ajax({
url: apirul + 'api/Items/Save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Item),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableItem();
$('#btnAddItem').html('<i ></i>Save');
$('#hdnItemID').val("0");
$('#instanceTable').addClass('hidden');
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Save Vehicles
$('#btnAddVehicle').click(function () {
var Vehicle = {};
Vehicle.Name = $('#txtVehicleName').val();
Vehicle.Number = $('#txtVehicleNumber').val();
Vehicle.Type = $('#txtVehicleType').val();
Vehicle.Owner = $('#txtVehicleOwner').val();
Vehicle.Status = $('#ddlVehicleStatus').val();
Vehicle.ID = $('#hdnVehicleID').val();
Vehicle.ModifiedBy = $.cookie('bsl_3');
Vehicle.CompanyId = $.cookie("bsl_1");
Vehicle.CreatedBy = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/Vehicles/save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Vehicle),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableVehicle();
$('#btnAddVehicle').html('Save');
$('#hdnVehicleID').val("0");
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Save Despatch
$('#btnAddDespatch').click(function () {
var Despatch = {};
Despatch.Name = $('#txtDespatchName').val();
Despatch.Address = $('#txtDespatchAddress').val();
Despatch.PhoneNo = $('#txtDespatchNumber').val();
Despatch.MobileNo = $('#txtDespatchMobile').val();
Despatch.ContactPerson = $('#txtDespatchContact').val();
Despatch.ContactPersonPhone = $('#txtDespatchContactPhone').val();
Despatch.Status = $('#ddlDespatchStatus').val();
Despatch.Narration = $('#txtDespatchNarration').val();
Despatch.ID = $('#hdnDespatchID').val();
Despatch.ModifiedBy = $.cookie('bsl_3');
Despatch.CompanyId = $.cookie("bsl_1");
Despatch.CreatedBy = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/Despatch/save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Despatch),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableDespatch();
$('#btnAddDespatch').html('Save');
$('#hdnDespatchID').val("0");
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Save Supplier
$('#btnAddSupplier').click(function () {
var Supplier = {};
Supplier.Name = $('#txtSupplierName').val();
Supplier.Address1 = $('#txtSupplierAddres1').val();
Supplier.Address2 = $('#txtSupplierAddress2').val();
Supplier.CountryId = $('#ddlSupplierCountry').val();
Supplier.StateId = $('#ddlSupplierState').val();
Supplier.Phone1 = $('#txtSupplierPhone1').val();
Supplier.Phone2 = $('#txtSupplierPhone2').val();
Supplier.Email = $('#txtSupplierEmail').val();
Supplier.Taxno1 = $('#txtSupplierTax1').val();
Supplier.Taxno2 = $('#txtSupplierTax1').val();
Supplier.Status = $('#ddlSupplierStatus').val();
Supplier.ID = $('#hdnSupplierID').val();
Supplier.Salutation = $('#ddlSupplierSalutation').val();
Supplier.City = $('#txtSupplierCity').val();
Supplier.ZipCode = $('#txtSupplierZipCode').val();
Supplier.Contact_Name = $('#txtSupplierContactName').val();
Supplier.ProfileImageB64 = $('#imgPhoto').attr('src').split(',')[1];
Supplier.ModifiedBy = $.cookie('bsl_3');
Supplier.CompanyId = $.cookie("bsl_1");
Supplier.CreatedBy = $.cookie('bsl_3');
$.ajax({
url: apirul + 'api/Suppliers/Save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Supplier),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableSuppliers();
$('#btnAddSupplier').html('Save');
$('#hdnSupplierID').val("0");
$('#imgPhoto').attr('src', '../Theme/images/profile-pic.jpg');
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
});
//Save Customer
$('#btnAddCustomer').click(function () {
var Customer = {};
Customer.Name = $('#txtCustomerName').val();
Customer.Address1 = $('#txtCustomerAddress1').val();
Customer.Address2 = $('#txtCustomerAddress2').val();
Customer.CountryId = $('#ddlCustomerCountry').val();
Customer.StateId = $('#ddlCustomerState').val();
Customer.Phone1 = $('#txtCustomerPhone1').val();
Customer.Phone2 = $('#txtCustomerPhone2').val();
Customer.Email = $('#txtCustomerEmail').val();
Customer.Taxno1 = $('#txtCustomerTax1').val();
Customer.Taxno2 = $('#txtCustomerTax2').val();
Customer.CreditAmount = $('#txtCustomerCreditAmount').val();
Customer.CreditPeriod = $('#txtCustomerCreditPeriod').val();
Customer.LockPeriod = $('#txtCustomerLockPeriod').val();
Customer.LockAmount = $('#txtCustomerLockAmount').val();
Customer.ID = $('#hdnCustomerID').val();
Customer.Status = $('#ddlCustomerStatus').val();
Customer.ModifiedBy = $.cookie('bsl_3');
Customer.CompanyId = $.cookie("bsl_1");
Customer.CreatedBy = $.cookie('bsl_3');
Customer.Salutation = $('#ddlCustSalutation').val();
Customer.City = $('#txtCustomerCity').val();
Customer.ZipCode = $('#txtCustomerZipCode').val();
Customer.Contact_Name = $('#txtCustContactName').val();
Customer.ProfileImageB64 = $('#imgCustomerPhoto').attr('src').split(',')[1];
$.ajax({
url: apirul + 'api/Customers/save',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Customer),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableCustomer();
$('#btnAddCustomer').html('Save');
$('#hdnCustomerID').val("0");
$('#imgCustomerPhoto').attr('src', '../Theme/images/profile-pic.jpg');
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
})
//Save Lead
$('#btnAddLead').click(function () {
var Lead = {};
Lead.Name = $('#txtLeadName').val();
Lead.Address1 = $('#txtLeadAddr1').val();
Lead.Address2 = $('#txtLeadAddr2').val();
Lead.CountryId = $('#ddlLeadCountry').val();
Lead.StateId = $('#ddlLeadState').val();
Lead.Phone1 = $('#txtLeadPh1').val();
Lead.Phone2 = $('#txtLeadPh2').val();
Lead.Email = $('#txtLeadEmail').val();
Lead.Taxno1 = $('#txtLeadTax1').val();
Lead.Taxno2 = $('#txtLeadTax2').val();
Lead.ID = $('#hdLeadId').val();
Lead.City = $('#txtLeadCity').val();
Lead.ZipCode = $('#txtLeadZipCode').val();
Lead.ContactName = $('#txtLeadContactName').val();
Lead.Salutation = $('#ddlLeadSalutation').val();
Lead.ModifiedBy = $.cookie('bsl_3');
Lead.CompanyId = $.cookie("bsl_1");
Lead.CreatedBy = $.cookie('bsl_3');
Lead.Status = $('#ddlLeadPrimaryStatus').val();
Lead.ProfileImageB64 = $('#imgLeadPhoto').attr('src').split(',')[1];
Lead.Source = $('#ddlLeadSource').val();
Lead.AssignId = $('#ddlAssign').val();
$.ajax({
url: apirul + 'api/Leads/SaveLeads',
method: 'POST',
dataType: 'JSON',
data: JSON.stringify(Lead),
contentType: 'application/json;charset=utf-8',
success: function (data) {
if (data.Success) {
successAlert(data.Message);
reset();
RefreshTableLead(null, null, null, null);
$('#btnAddLead').html('Save');
$('#hdLeadId').val("0");
$('#imgLeadPhoto').attr('src', '../Theme/images/profile-pic.jpg');
}
else {
errorAlert(data.Message);
}
},
error: function (xhr) {
errorAlert(data.Message);
miniLoading('stop');
},
beforeSend: function () { miniLoading('start'); },
complete: function () { miniLoading('stop'); },
});
})
//////* Functions To Get The Data For Update *//////
//Edit Brand
$(document).on('click', '.edit-entry-brand', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Brands/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#txtBrandName').val(response.Name);
$('#txtBrandOrder').val(response.Order);
$('#ddlBrandStatus').val(response.Status);
$('#hdnBrandID').val(response.ID);
$('#btnAddBrand').html('<i></i> Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Service
$(document).on('click', '.edit-entry-service', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Items/GetDetailsForService/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
console.log(response[0]);
$('#txtServiceName').val(response[0].Name);
$('#txtServiceDescription').val(response[0].Description);
$('#ddlServiceTax').val(response[0].TaxId);
$('#txtServiceRate').val(response[0].SellingPrice);
$('#ddlServiceStatus').val(response[0].Status);
$('#hdServiceId').val(response[0].ItemID);
$('#txtServiceItemCode').val(response[0].ItemCode);
$('#btnAddService').html('<i></i>Update');
if (response[0].TrackInventory) {
$('.track-service').attr('checked', true);
}
else {
$('.track-service').attr('checked', false)
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Group
$(document).on('click', '.edit-entry-Group', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Groups/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#txtGroupName').val(response.Name);
$('#txtGroupOrder').val(response.Order);
$('#ddlGroupStatus').val(response.Status);
$('#hdnGroupID').val(response.ID);
$('#btnAddNewGroup').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Category
$(document).on('click', '.edit-entry-Category', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Categories/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#txtCategoryName').val(response.Name);
$('#txtCategoryOrder').val(response.Order);
$('#ddlCategoryStatus').val(response.Status);
$('#hdnCategoryID').val(response.ID);
$('#btnAddCategory').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Product Type
$(document).on('click', '.edit-entry-Type', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/ProductTypes/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#txtTypeName').val(response.Name);
$('#txtTypeOrder').val(response.Order);
$('#ddlTypeStatus').val(response.Status);
$('#hdnTypeID').val(response.ID);
$('#btnAddType').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Tax
$(document).on('click', '.edit-entry-tax', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Taxes/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#txtTaxName').val(response.Name);
$('#txtTaxPercentage').val(response.Percentage);
$('#txtTaxType').val(response.Type);
$('#ddlTaxStatus').val(response.Status);
$('#hdnTaxID').val(response.ID);
$('#btnAddTax').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Unit
$(document).on('click', '.edit-entry-Unit', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Units/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#txtUOMName').val(response.Name);
$('#txtUOMShortName').val(response.ShortName);
$('#ddlUOMStatus').val(response.Status);
$('#hdnUnitID').val(response.ID);
$('#btnAddUOM').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Items
$(document).on('click', '.edit-entry-Item', function () {
$('#instanceTable').removeClass('hidden');
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Items/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#instanceTable tbody').children().remove();
//$('#txtItemCode').prop('disabled', false);
$('#txtItemCode').val(response.ItemCode);
$('#txtItemName').val(response.Name);
$('#txtItemDescription').val(response.Description);
$('#txtRemarks').val(response.Remarks);
$('#txtItemOEMCode').val(response.OEMCode);
$('#txtItemHSCode').val(response.HSCode);
$('#ddlItemUOM').val(response.UnitID);
$('#ddlItemTax').val(response.TaxId);
$('#ddlItemType').val(response.TypeID);
$('#ddlItemCategory').val(response.CategoryID);
$('#ddlItemGroup').val(response.GroupID);
$('#ddlItemBrand').val(response.BrandID);
$('#txtItemBarcode').val(response.Barcode);
$('#hdnItemID').val(response.ItemID);
$('#txtItemMRP').val(response.MRP);
$('#txtItemCP').val(response.CostPrice);
$('#txtItemSP').val(response.SellingPrice);
$('#lblPriceText').addClass('hidden')
$('#ddlItemStatus').val(response.Status);
//Added to check whether the item should check the stock in entry page
//If Track Inventory is true checks the stock at the time of entry
if (response.TrackInventory) {
$('.track').attr('checked', true);
}
else {
$('.track').attr('checked', false)
}
$('#btnAddItem').html('<i ></i> Update');
$(response.Instances).each(function () {
$('#instanceTable tbody').prepend('<tr><td class="hidden">' + this.ID + '</td><td contenteditable="false">' + this.Mrp + '</td><td contenteditable="false">' + this.CostPrice + '</td><td contenteditable="false">' + this.SellingPrice + '</td><td contenteditable="false">' + this.Barcode + '</td><td><i class="text-info md-edit editInstance"></i> <i class="md-delete text-danger deleteInstance"></i> <i class="md-clear text-danger cancelInstance hidden"></i></td></tr>');
});
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Vehicles
$(document).on('click', '.edit-entry-vehicle', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Vehicles/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#txtVehicleName').val(response.Name);
$('#txtVehicleNumber').val(response.Number);
$('#txtVehicleType').val(response.Type);
$('#txtVehicleOwner').val(response.Owner);
$('#ddlVehicleStatus').val(response.Status);
$('#hdnVehicleID').val(response.ID);
$('#btnAddVehicle').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Despatch
$(document).on('click', '.edit-entry-despatch', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Despatch/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
$('#txtDespatchName').val(response.Name);
$('#txtDespatchAddress').val(response.Address);
$('#txtDespatchNumber').val(response.PhoneNo);
$('#txtDespatchMobile').val(response.MobileNo);
$('#txtDespatchContact').val(response.ContactPerson);
$('#txtDespatchContactPhone').val(response.ContactPersonPhone);
$('#txtDespatchNarration').val(response.Narration);
$('#ddlDespatchStatus').val(response.Status);
$('#hdnDespatchID').val(response.ID);
$('#btnAddDespatch').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
});
//Edit Suppliers
$(document).on('click', '.edit-entry-Supplier', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Suppliers/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
var countryId = response.CountryId;
$.ajax({
url: apirul + 'api/Customers/getStates/' + countryId,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (data) {
$('#ddlSupplierCountry').val(response.CountryId);
$('#ddlSupplierState').children('option').remove();
$('#ddlSupplierState').append('<option value="0">--select--</option>');
$(data).each(function () {
$('#ddlSupplierState').append('<option value="' + this.StateId + '">' + this.State + '</option>');
});
$('#txtSupplierName').val(response.Name);
$('#txtSupplierAddres1').val(response.Address1);
$('#txtSupplierAddress2').val(response.Address2);
$('#txtSupplierPhone1').val(response.Phone1);
$('#txtSupplierPhone2').val(response.Phone2);
$('#txtSupplierEmail').val(response.Email);
$('#txtSupplierTax1').val(response.Taxno1);
$('#txtSupplierTax2').val(response.Taxno2);
$('#ddlSupplierStatus').val(response.Status);
$('#ddlSupplierState :selected').val(response.StateId);
$('#ddlSupplierState').select2('val', response.StateId);
$('#ddlSupplierState').val(response.StateId);
$('#ddlSupplierCountry').val(response.CountryId);
$('#hdnSupplierID').val(response.ID);
$('#txtSupplierCity').val(response.City);
$('#txtSupplierZipCode').val(response.ZipCode);
$('#ddlSupplierSalutation').val(response.Salutation).trigger('change');
$('#txtSupplierContactName').val(response.Contact_Name);
$('#imgPhoto').attr('src', response.ProfileImagePath != '' ? response.ProfileImagePath : '../Theme/images/profile-pic.jpg');
$('#btnAddSupplier').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
complete: loading('stop', null);
},
});
}
});
});
//Edit Customer
$(document).on('click', '.edit-entry-customer', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Customers/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
var countryId = response.CountryId;
$.ajax({
url: apirul + 'api/Customers/getStates/' + countryId,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (data) {
$('#ddlCustomerCountry').val(response.CountryId);
$('#ddlCustomerState').children('option').remove();
$('#ddlCustomerState').append('<option value="0">--select--</option>');
$(data).each(function () {
$('#ddlCustomerState').append('<option value="' + this.StateId + '">' + this.State + '</option>');
});
$('#ddlCustomerState').val(response.StateId);
$('#txtCustomerName').val(response.Name);
$('#txtCustomerAddress1').val(response.Address1);
$('#txtCustomerAddress2').val(response.Address2);
$('#txtCustomerPhone1').val(response.Phone1);
$('#txtCustomerPhone2').val(response.Phone2);
$('#txtCustomerTax1').val(response.Taxno1);
$('#txtCustomerTax2').val(response.Taxno2);
$('#txtCustomerEmail').val(response.Email);
//$('#txtCustomerTax1').val(response.Taxno1);
//$('#txtCustomertax2').val(response.Taxno2);
$('#txtCustomerCreditAmount').val(response.CreditAmount);
$('#txtCustomerCreditPeriod').val(response.CreditPeriod);
$('#txtCustomerLockAmount').val(response.LockAmount);
$('#txtCustomerLockPeriod').val(response.LockPeriod);
$('#ddlCustomerStatus').val(response.Status);
$('#hdnCustomerID').val(response.ID);
$('#txtCustomerCity').val(response.City);
$('#txtCustomerZipCode').val(response.ZipCode);
$('#txtCustContactName').val(response.Contact_Name);
$('#ddlCustSalutation').val(response.Salutation).trigger('change');
$('#imgCustomerPhoto').attr('src', response.ProfileImagePath != '' ? response.ProfileImagePath : '../Theme/images/profile-pic.jpg');
$('#btnAddCustomer').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
complete: loading('stop', null);
},
});
}
});
});
//Edit Lead
$(document).on('click', '.edit-entry-Lead', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
$.ajax({
url: apirul + 'api/Leads/GetLeads/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
var countryId = response.CountryId;
$.ajax({
url: apirul + 'api/Customers/getStates/' + countryId,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (data) {
$('#ddlLeadCountry').val(response.CountryId);
$('#ddlLeadState').children('option').remove();
$('#ddlLeadState').append('<option value="0">--select--</option>');
$(data).each(function () {
$('#ddlLeadState').append('<option value="' + this.StateId + '">' + this.State + '</option>');
});
$('#ddlLeadState').val(response.StateId);
$('#txtLeadName').val(response.Name);
$('#txtLeadAddr1').val(response.Address1);
$('#txtLeadAddr2').val(response.Address2);
$('#txtLeadPh1').val(response.Phone1);
$('#txtLeadPh2').val(response.Phone2);
$('#txtLeadTax1').val(response.Taxno1);
$('#txtLeadTax2').val(response.Taxno2);
$('#txtLeadEmail').val(response.Email);
$('#hdLeadId').val(response.ID);
$('#txtLeadCity').val(response.City);
$('#txtLeadZipCode').val(response.ZipCode);
$('#ddlLeadSalutation').val(response.Salutation);
$('#txtLeadContactName').val(response.ContactName);
$('#ddlLeadPrimaryStatus').val(response.Status);
$('#ddlLeadSource').val(response.Source);
$('#ddlAssign').val(response.AssignId);
$('#imgLeadPhoto').attr('src', response.ProfileImagePath != '' ? response.ProfileImagePath : '../Theme/images/profile-pic.jpg');
$('#btnAddLead').html('<i></i>Update');
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
complete: loading('stop', null);
},
});
}
});
});
//////* Functions To Delete the Selected data *//////
//Delete brand
$(document).on('click', '.delete-entry-brand', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = ($.cookie("bsl_3"));
deleteMaster({
"url": apirul + 'api/Brands/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Brand has been deleted from inventory',
"successFunction": RefreshTableBrand
});
});
//Delete Service
$(document).on('click', '.delete-entry-service', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = ($.cookie("bsl_3"));
deleteMaster({
"url": apirul + 'api/Items/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Service has been deleted from inventory',
"successFunction": RefreshTableService
});
});
//Delete Group
$(document).on('click', '.delete-entry-group', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/Groups/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Group has been deleted from inventory',
"successFunction": RefreshTableGroup
});
});
//Delete Category
$(document).on('click', '.delete-entry-category', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3")
deleteMaster({
"url": apirul + 'api/Categories/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Product has been deleted from inventory',
"successFunction": RefreshTableCategory
});
});
//Delete Item
$(document).on('click', '.delete-entry-item', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/Items/delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Product has been deleted from inventory',
"successFunction": RefreshTableItem
});
});
//Delete Type
$(document).on('click', '.delete-entry-type', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/ProductTypes/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Product has been deleted from inventory',
"successFunction": RefreshTableType
});
});
//Delete Tax
$(document).on('click', '.delete-entry-tax', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/Taxes/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Product has been deleted from inventory',
"successFunction": RefreshTableTax
});
reset();
});
//Delete Unit
$(document).on('click', '.delete-entry-unit', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/Units/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Unit has been deleted from inventory',
"successFunction": RefreshTableUnit
});
reset();
});
//Delete Vehicles
$(document).on('click', '.delete-entry-vehicle', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/Vehicles/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Vehicle has been deleted from inventory',
"successFunction": RefreshTableVehicle
});
reset();
});
//Delete Despatch
$(document).on('click', '.delete-entry-despatch', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = ($.cookie("bsl_3"));
deleteMaster({
"url": apirul + 'api/Despatch/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Despatch has been deleted from inventory',
"successFunction": RefreshTableDespatch
});
reset();
});
//Delete Supplier
$(document).on('click', '.delete-entry-supplier', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/Suppliers/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Product has been deleted from inventory',
"successFunction": RefreshTableSuppliers
});
reset();
});
//Delete Customer
$(document).on('click', '.delete-entry-customer', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/Customers/Delete/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Product has been deleted from inventory',
"successFunction": RefreshTableCustomer
});
reset();
});
//Delete Lead
$(document).on('click', '.delete-entry-Lead', function () {
var id = parseInt($(this).closest('tr').children('td:nth-child(1)').text());
var modifiedBy = $.cookie("bsl_3");
deleteMaster({
"url": apirul + 'api/Leads/DeleteLeads/',
"id": id,
"modifiedBy": modifiedBy,
"successMessage": 'Lead has been deleted from inventory',
"successFunction": RefreshTableLead
});
reset();
});
//////* Additional Funtions *//////
//Function to Load the dropdown list data for Items
function loadAdditionalData() {
var Company = $.cookie("bsl_1");
$.ajax({
type: "POST",
async: false,
url: apirul + "api/items/GetAsscociateData?CompanyID=" + Company,
contentType: "application/json; charset=utf-8",
data: JSON.stringify($.cookie("bsl_1")),
dataType: "json",
success: function (data) {
$('#ddlItemType').empty();
$('#ddlItemType').append('<option value="0">--Select--</option>');
$('#ddlItemBrand').empty();
$('#ddlItemBrand').append('<option value="0">--Select--</option>');
$('#ddlItemCategory').empty();
$('#ddlItemCategory').append('<option value="0">--Select--</option>');
$('#ddlItemGroup').empty();
$('#ddlItemGroup').append('<option value="0">--Select--</option>');
$('#ddlItemTax').empty();
$('#ddlItemTax').append('<option value="0">--Select--</option>');
$('#ddlServiceTax').empty();
$('#ddlServiceTax').append('<option value="0">--Select--</option>');
$('#ddlItemUOM').empty();
$('#ddlItemUOM').append('<option value="0">--Select--</option>');
$.each(data.Types, function () {
$("#ddlItemType").append($("<option/>").val(this.Type_Id).text(this.Name));
});
$.each(data.Brands, function () {
$('#ddlItemBrand').append($("<option/>").val(this.Brand_ID).text(this.Name));
});
$.each(data.Categories, function () {
$('#ddlItemCategory').append($("<option/>").val(this.Category_Id).text(this.Name));
});
$.each(data.Groups, function () {
$('#ddlItemGroup').append($("<option/>").val(this.Group_ID).text(this.Name));
});
$.each(data.Taxes, function () {
$('#ddlItemTax').append($("<option/>").val(this.Tax_Id).text(this.Percentage));
});
$.each(data.Taxes, function () {
$('#ddlServiceTax').append($("<option/>").val(this.Tax_Id).text(this.Percentage));
});
$.each(data.Unit, function () {
$('#ddlItemUOM').append($("<option/>").val(this.Unit_Id).text(this.Short_Name));
});
},
failure: function () {
$('.master-section-error').text('Sorry. Something went wrong. Try again later');
$('#masterSectionPError').css('display', 'block');
}
});
}
//Function to load supplier country
function loadSupplierCountry() {
var company = $.cookie("bsl_1");
$.ajax({
type: "POST",
url: apirul + "api/customers/Getcountry?companyId=" + company,
contentType: "application/json; charset=utf-8",
data: JSON.stringify($.cookie("bsl_1")),
dataType: "json",
success: function (data) {
$('ddlSupplierCountry').empty();
$('ddlSupplierCountry').append('<option value="0">--Select--</option>');
$.each(data, function () {
$("#ddlSupplierCountry").append($("<option/>").val(this.Country_Id).text(this.Name));
});
},
failure: function () {
console.log("Error")
}
});
}
//Function to load Customer country
function loadCustomerCountry() {
var company = $.cookie("bsl_1");
$.ajax({
type: "POST",
url: apirul + "api/customers/Getcountry?companyId=" + company,
contentType: "application/json; charset=utf-8",
data: JSON.stringify($.cookie("bsl_1")),
dataType: "json",
success: function (data) {
$('ddlCustomerCountry').empty();
$('ddlCustomerCountry').append('<option value="0">--Select--</option>');
$.each(data, function () {
$("#ddlCustomerCountry").append($("<option/>").val(this.Country_Id).text(this.Name));
});
},
failure: function () {
console.log("Error")
}
});
}
//Function to load Lead country
function loadLeadCountry() {
var company = $.cookie("bsl_1");
$.ajax({
type: "POST",
url: apirul + "api/customers/Getcountry?companyId=" + company,
contentType: "application/json; charset=utf-8",
data: JSON.stringify($.cookie("bsl_1")),
dataType: "json",
success: function (data) {
$('ddlLeadCountry').empty();
$('ddlLeadCountry').append('<option value="0">--Select--</option>');
$.each(data, function () {
$("#ddlLeadCountry").append($("<option/>").val(this.Country_Id).text(this.Name));
});
},
failure: function () {
console.log("Error")
}
});
}
//load employee
function loadLeadEmployee() {
var company = $.cookie("bsl_1");
$.ajax({
type: "POST",
url: apirul + "api/Leads/GetEmployee?companyId=" + company,
contentType: "application/json; charset=utf-8",
data: JSON.stringify($.cookie("bsl_1")),
dataType: "json",
success: function (data) {
$('ddlAssign').empty();
$('ddlAssign').append('<option value="0">--Select--</option>');
$.each(data, function () {
$("#ddlAssign").append($("<option/>").val(this.Employee_Id).text(this.First_Name));
});
},
failure: function () {
console.log("Error")
}
});
}
//Event to load State by getting the coountry ID
$('#ddlSupplierCountry').change(function () {
var selected = $('#ddlSupplierCountry').val();
if (selected == 0) {
$('#ddlSupplierState').empty();
$('#ddlSupplierState').append("<option>--Select States--</option>")
}
else {
$('#ddlSupplierState').empty();
$('#ddlSupplierState').append("<option>--Select States--</option>")
$.ajax({
type: "POST",
url: apirul + "api/customers/GetStates?id=" + selected,
contentType: "application/json; charset=utf-8",
data: JSON.stringify($.cookie("bsl_1")),
dataType: "json",
success: function (data) {
$('#ddlSupplierState').empty;
$.each(data, function () {
$("#ddlSupplierState").append($("<option/>").val(this.StateId).text(this.State));
});
},
failure: function () {
console.log("Error");
}
});
}
});
//Load Customer State by getting the coountry ID
$('#ddlCustomerCountry').change(function () {
var selected = $('#ddlCustomerCountry').val();
if (selected == 0) {
$('#ddlCustomerState').empty();
$('#ddlCustomerState').append("<option value='0'>--Select States--</option>")
}
else {
$('#ddlCustomerState').empty();
$('#ddlCustomerState').append("<option value='0'>--Select States--</option>")
$.ajax({
type: "POST",
url: apirul + "api/customers/GetStates?id=" + selected,
contentType: "application/json; charset=utf-8",
data: JSON.stringify($.cookie("bsl_1")),
dataType: "json",
success: function (data) {
$('#ddlCustomerState').empty;
$.each(data, function () {
$("#ddlCustomerState").append($("<option/>").val(this.StateId).text(this.State));
});
},
failure: function () {
console.log("Error");
}
});
}
});
//Load Lead country state by getting the country id
$('#ddlLeadCountry').change(function () {
var selected = $('#ddlLeadCountry').val();
if (selected == 0) {
$('#ddlLeadState').empty();
$('#ddlLeadState').append("<option>--Select States--</option>")
}
else {
$('#ddlLeadState').empty();
$('#ddlLeadState').append("<option>--Select States--</option>")
$.ajax({
type: "POST",
url: apirul + "api/customers/GetStates?id=" + selected,
contentType: "application/json; charset=utf-8",
data: JSON.stringify($.cookie("bsl_1")),
dataType: "json",
success: function (data) {
$('#ddlLeadState').empty;
$.each(data, function () {
$("#ddlLeadState").append($("<option/>").val(this.StateId).text(this.State));
});
},
failure: function () {
console.log("Error");
}
});
}
});
//Adding Instances
$('.addInstance').click(function () {
var editingCount = $('.updateInstance').length;
if (editingCount > 0) {
}
else if ($('#hdnItemID').val() != '0') {
$('#instanceTable tbody').prepend('<tr><td class="hidden">0</td><td contenteditable="true">0.00</td><td contenteditable="true">0.00</td><td contenteditable="true">0.00</td><td contenteditable="true">0</td><td><i class="md-done text-info updateInstance"></i> <i class="md-delete text-danger deleteInstance hidden"></i> <i class="md-clear text-danger cancelInstance"></i></td></tr>');
}
else {
errorAlert('You cannot create an instance to a new product. Save one first.');
}
});
//Removing Instances
$('body').on('click', '.cancelInstance', function () {
$(this).closest('tr').remove();
});
//Deleting Instances
$('body').on('click', '.deleteInstance', function () {
var tr = $(this).closest('tr');
swal({
title: "",
text: "Are you sure you want to delete?",
showCancelButton: true,
showConfirmButton: true,
closeOnConfirm: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Delete"
},
function (isConfirm) {
if (isConfirm) {
$.ajax({
url: $('#hdApiUrl').val() + 'api/ItemInstance/Delete/' + tr.children('td').eq(0).text(),
method: 'DELETE',
dataType: 'JSON',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify($.cookie('bsl_3')),
success: function (response) {
if (response.Success) {
successAlert(response.Message);
tr.remove();
}
else {
errorAlert(response.Message);
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
});
});
//Updating Instance
$('body').on('click', '.updateInstance', function () {
var updateButton = $(this);
var row = $(this).closest('tr');
var instance = {};
instance.CreatedBy = $.cookie('bsl_3');
instance.ModifiedBy = $.cookie('bsl_3');
instance.ID = row.children('td').eq(0).text();
instance.ItemId = $('#hdnItemID').val();
instance.Mrp = row.children('td').eq(1).text();
instance.SellingPrice = row.children('td').eq(3).text();
instance.CostPrice = row.children('td').eq(2).text();
instance.Barcode = row.children('td').eq(4).text();
$.ajax({
url: $('#hdApiUrl').val() + 'api/ItemInstance/Save',
method: 'POST',
dataType: 'JSON',
contentType: 'application/Json;charset=utf-8',
data: JSON.stringify(instance),
success: function (response) {
if (response.Success) {
successAlert(response.Message);
row.children('td').eq(0).text(response.Object);
row.find('td:not(:last-child)').removeAttr('contenteditable');
updateButton.addClass('md-edit editInstance').removeClass('md-done updateInstance');
row.find('.deleteInstance').removeClass('hidden');
row.find('.cancelInstance').addClass('hidden');
}
else {
errorAlert(response.Message);
}
},
error: function (xhr) { alert(xhr.responseText); console.log(xhr); }
});
});
//Editing Instance
$('body').on('click', '.editInstance', function () {
$(this).closest('tr').find('td:not(:last-child)').attr('contenteditable', true);
$(this).removeClass('md-edit editInstance').addClass('md-done updateInstance');
$(this).closest('td').find('.cancelInstance').addClass('hidden');
$(this).closest('td').find('.deleteInstance').removeClass('hidden');
});
//Used to Refresh The Page Contents
$('.refresh-data').on('click', function () {
reset();
$('#hdnItemID').val("0");
$('#hdnBrandID').val("0");
$('#hdnCategoryID').val("0");
$('#hdnTypeID').val("0");
$('#hdnUnitID').val("0");
$('#hdnTaxID').val("0");
$('#hdnVehicleID').val("0");
$('#hdnGroupID').val("0");
$('#hdnDespatchID').val("0");
$('#hdnSupplierID').val("0");
$('#hdnCustomerID').val("0");
$('#hdServiceId').val("0");
$('#hdLeadId').val("0");
$('#instanceTable tr').remove();
$('#lblPriceText').addClass('hidden')
//$('#txtItemCode').attr('disabled', 'disabled');
$('#btnAddBrand').html('<i class="fa fa-plus"></i> Add Brand');
$('#btnAddCategory').html('<i class="fa fa-plus"></i> Add Category');
$('#btnAddNewGroup').html('<i class="fa fa-plus"></i> Add Group');
$('#btnAddType').html('<i class="fa fa-plus"></i> Add Type');
$('#btnAddTax').html('<i class="fa fa-plus"></i> Add Tax');
$('#btnAddUOM').html('<i class="fa fa-plus"></i> Add Unit');
$('#btnAddItem').html('<i ></i>Save');
$('#btnAddVehicle').html('<i class="fa fa-plus"></i> Add Vehicle');
$('#btnAddDespatch').html('<i class="fa fa-plus"></i> Add Despatch');
$('#btnAddSupplier').html('<i class="fa fa-plus"></i> Add Supplier');
$('#btnAddCustomer').html('<i class="fa fa-plus"></i> Add Customer');
$('#btnAddService').html('<i class="fa fa-plus"></i> Add Service');
$('#btnAddLead').html('<i class="fa fa-plus"></i> Add Lead');
$('.track-service').attr('checked', false);
})
//check if selling price is grater than oru equal to Mrp
function CheckSellingPrice() {
var sp = parseFloat($('#txtItemSP').val());
var TaxPer = parseFloat($('#ddlItemTax option:selected').text());
var Mrp = parseFloat($('#txtItemMRP').val());
if ((sp * (TaxPer / 100) + sp) > Mrp) {
$('#lblPriceText').removeClass('hidden')
}
else {
$('#lblPriceText').addClass('hidden')
}
}
//Events to Check selling price is greater than MRP
$('#txtItemSP,#txtItemCP,#ddlItemTax').change(function () {
CheckSellingPrice();
});
//Function to perform Url operations
function CheckSection() {
var ID = $('#hdnID').val();
var Mode = $('#hdnMode').val();
var Section = $('#hdnSectionName').val();
$('#v-5').removeClass('active');
if (ID != "0" && Mode == 'EDIT') {
switch (Section) {
case 'ITEM':
$('#v-5').addClass('active');
GetItems(ID, Mode);
break;
case 'SERVICE':
$('#v-12').addClass('active');
$('#Item').removeClass('active');
RefreshTableService();
GetSErvice(ID, Mode);
break;
case 'BRAND':
$('#menu >li').removeClass('active');
$('#v-1').addClass('active');
$('#Item').removeClass('active');
RefreshTableBrand();
getBrands(ID, Mode);
break;
case 'GROUP':
$('#menu >li').removeClass('active');
$('#Group').addClass('active');
$('#v-4').addClass('active');
RefreshTableGroup();
getGroups(ID, Mode);
break;
case 'TYPE':
$('#menu >li').removeClass('active');
$('#Type').addClass('active');
$('#v-8').addClass('active');
RefreshTableType();
getProductType(ID, Mode);
break;
case 'CATEGORY':
$('#menu >li').removeClass('active');
$('#Category').addClass('active');
$('#v-2').addClass('active');
RefreshTableCategory();
GetCategory(ID, Mode);
break;
case 'UNIT':
$('#menu >li').removeClass('active');
$('#Unit').addClass('active');
$('#v-9').addClass('active');
RefreshTableUnit();
GetUnit(ID, Mode);
break;
case 'TAX':
$('#menu >li').removeClass('active');
$('#v-7').addClass('active');
$('#Tax').addClass('active');
RefreshTableTax();
GetTax(ID, Mode);
break;
case 'DESPATCH':
$('#menu >li').removeClass('active');
$('#v-11').addClass('active');
$('#Despatch').addClass('active');
RefreshTableDespatch();
getDespatch(ID, Mode);
break;
case 'VEHICLE':
$('#menu >li').removeClass('active');
$('#v-10').addClass('active');
$('#Vehicles').addClass('active');
RefreshTableVehicle();
GetVehicle(ID, Mode);
break;
case 'SUPPLIER':
$('#menu >li').removeClass('active');
$('#v-6').addClass('active');
$('#Supplier').addClass('active');
RefreshTableSuppliers();
getSupplierData(ID, Mode);
break;
case 'CUSTOMER':
$('#menu >li').removeClass('active');
$('#v-3').addClass('active');
$('#Customer').addClass('active');
RefreshTableCustomer();
getCustomerData(ID, Mode);
break;
case 'LEAD':
$('#menu >li').removeClass('active');
$('#v-12').addClass('active');
$('#Lead').addClass('active');
RefreshTableLead(null, null, null, null);
getLeadData(ID, Mode);
loadLeadEmployee();
break;
default:
$('#v-5').addClass('active');
break;
}
}
else if (ID != "0" && Mode == "CLONE") {
switch (Section) {
case 'ITEM':
$('#v-5').addClass('active');
GetItems(ID, Mode);
$('#hdnItemID').val("0");
$('#btnAddBrand').html('<i class="fa fa-clone"></i> Clone');
break;
case 'BRAND':
$('#menu >li').removeClass('active');
$('#v-1').addClass('active');
$('#Item').removeClass('active');
RefreshTableBrand();
$('#hdnBrandID').val("0");
getBrands(ID, Mode);
$('#btnAddBrand').html('<i class="fa fa-clone"></i> Clone');
break;
case 'SERVICE':
$('#menu >li').removeClass('active');
$('#v-12').addClass('active');
$('#Item').removeClass('active');
RefreshTableService();
$('#hdServiceId').val("0");
getService(ID, Mode);
$('#btnAddService').html('<i class="fa fa-clone"></i> Clone');
break;
case 'GROUP':
$('#menu >li').removeClass('active');
$('#Group').addClass('active');
$('#v-4').addClass('active');
RefreshTableGroup();
getGroups(ID, mode);
$('#hdnGroupID').val("0");
break;
case 'TYPE':
$('#menu >li').removeClass('active');
$('#Type').addClass('active');
$('#v-8').addClass('active');
RefreshTableType();
getProductType(ID, Mode);
$('#hdnTypeID').val("0");
break;
case 'CATEGORY':
$('#menu >li').removeClass('active');
$('#Category').addClass('active');
$('#v-2').addClass('active');
RefreshTableCategory();
GetCategory(ID, Mode);
break;
case 'UNIT':
$('#menu >li').removeClass('active');
$('#Unit').addClass('active');
$('#v-9').addClass('active');
RefreshTableUnit();
GetUnit(ID, Mode);
$('#hdnUnitID').val("0");
break;
case 'TAX':
$('#menu >li').removeClass('active');
$('#v-7').addClass('active');
$('#Tax').addClass('active');
RefreshTableTax();
GetTax(ID, Mode);
$('#hdnTaxID').val("0");
break;
case 'DESPATCH':
$('#menu >li').removeClass('active');
$('#v-11').addClass('active');
$('#Despatch').addClass('active');
RefreshTableDespatch();
getDespatch(ID, Mode);
$('#hdnDespatchID').val("0");
break;
case 'VEHICLE':
$('#menu >li').removeClass('active');
$('#v-10').addClass('active');
$('#Vehicles').addClass('active');
RefreshTableVehicle();
GetVehicle(ID, Mode);
$('#hdnVehicleID').val("0");
break;
case 'SUPPLIER':
$('#menu >li').removeClass('active');
$('#v-6').addClass('active');
$('#Supplier').addClass('active');
RefreshTableSuppliers();
getSupplierData(ID, Mode);
$('#hdnSupplierID').val("0");
break;
case 'CUSTOMER':
$('#menu >li').removeClass('active');
$('#v-3').addClass('active');
$('#Customer').addClass('active');
RefreshTableCustomer();
getCustomerData(ID, Mode);
$('#hdnCustomerID').val("0");
break;
case 'LEAD':
$('#menu >li').removeClass('active');
$('#v-12').addClass('active');
$('#Customer').addClass('active');
RefreshTableLead(null, null, null, null);
getLeadData(ID, Mode);
loadLeadEmployee();
$('#hdLeadId').val("0");
break;
default:
$('#v-5').addClass('active');
break;
}
}
else if (ID == "0") {
switch (Section) {
case 'ITEM':
$('#v-5').addClass('active');
loadAdditionalData();
break;
case 'BRAND':
$('#menu >li').removeClass('active');
$('#v-1').addClass('active');
$('#Item').removeClass('active');
RefreshTableBrand();
break;
case 'SERVICE':
$('#menu >li').removeClass('active');
$('#v-12').addClass('active');
$('#Item').removeClass('active');
RefreshTableService();
break;
case 'GROUP':
$('#menu >li').removeClass('active');
$('#Group').addClass('active');
$('#v-4').addClass('active');
break;
case 'TYPE':
$('#menu >li').removeClass('active');
$('#Type').addClass('active');
$('#v-8').addClass('active');
RefreshTableType();
break;
case 'CATEGORY':
$('#menu >li').removeClass('active');
$('#Category').addClass('active');
$('#v-2').addClass('active');
RefreshTableCategory();
break;
case 'TAX':
$('#menu >li').removeClass('active');
$('#v-7').addClass('active');
$('#Tax').addClass('active');
RefreshTableTax();
break;
case 'VEHICLE':
$('#menu >li').removeClass('active');
$('#v-10').addClass('active');
$('#Vehicles').addClass('active');
RefreshTableVehicle();
break;
case 'SUPPLIER':
$('#menu >li').removeClass('active');
$('#v-6').addClass('active');
$('#Supplier').addClass('active');
RefreshTableSuppliers();
break;
case 'CUSTOMER':
$('#menu >li').removeClass('active');
$('#v-3').addClass('active');
$('#Customer').addClass('active');
RefreshTableCustomer();
break;
case 'LEAD':
$('#menu >li').removeClass('active');
$('#v-12').addClass('active');
$('#Leads').addClass('active');
RefreshTableLead(null, null, null, null);
loadLeadEmployee();
break;
case 'DESPATCH':
$('#menu >li').removeClass('active');
$('#v-11').addClass('active');
$('#Despatch').addClass('active');
RefreshTableDespatch();
break;
default:
$('#v-5').addClass('active');
loadAdditionalData();
break;
}
}
else {
$('#v-5').addClass('active');
loadAdditionalData();
}
}
//Gets the items
function GetItems(id, Mode) {
$.ajax({
url: apirul + 'api/Items/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#instanceTable tbody').children().remove();
$('#instanceTable').removeClass('hidden');
//$('#txtItemCode').prop('disabled', false);
$('#txtItemCode').val(response.ItemCode);
$('#txtItemName').val(response.Name);
$('#txtItemDescription').val(response.Description);
$('#txtRemarks').val(response.Remarks);
$('#txtItemOEMCode').val(response.OEMCode);
$('#txtItemHSCode').val(response.HSCode);
$('#ddlItemUOM').val(response.UnitID);
$('#ddlItemTax').val(response.TaxId);
$('#ddlItemType').val(response.TypeID);
$('#ddlItemCategory').val(response.CategoryID);
$('#ddlItemGroup').val(response.GroupID);
$('#ddlItemBrand').val(response.BrandID);
$('#txtItemBarcode').val(response.Barcode);
$('#txtItemMRP').val(response.MRP);
$('#txtItemCP').val(response.CostPrice);
$('#txtItemSP').val(response.SellingPrice);
$('#lblPriceText').addClass('hidden')
$('#ddlItemStatus').val(response.Status);
if (Mode == 'CLONE') {
$('#hdnItemID').val("0");
$('#btnAddItem').html('<i class="fa fa-clone"></i> Clone');
}
else {
$('#hdnItemID').val(response.ItemID);
$('#btnAddItem').html('<i class="md md-check"></i> Update');
}
$(response.Instances).each(function () {
$('#instanceTable tbody').prepend('<tr><td class="hidden">' + this.ID + '</td><td contenteditable="false">' + this.Mrp + '</td><td contenteditable="false">' + this.CostPrice + '</td><td contenteditable="false">' + this.SellingPrice + '</td><td contenteditable="false">' + this.Barcode + '</td><td><i class="text-info md-edit editInstance"></i> <i class="md-delete text-danger deleteInstance"></i> <i class="md-clear text-danger cancelInstance hidden"></i></td></tr>');
});
} catch (e) {
errorAlert('No Data Found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
//Brand for edit
function getBrands(id, mode) {
$.ajax({
url: apirul + 'api/Brands/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtBrandName').val(response.Name);
$('#txtBrandOrder').val(response.Order);
$('#ddlBrandStatus').val(response.Status);
if (mode == 'CLONE') {
$('#hdnBrandID').val("0");
$('#btnAddBrand').html('<i class="fa fa-clone"></i>Clone');
} else {
$('#hdnBrandID').val(response.ID);
$('#btnAddBrand').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No Data Found');
}
},
error: function (xhr) {
errorAlert("No data Found");
}
});
}
//Get Service
function getService(id, mode) {
$.ajax({
url: apirul + 'api/Items/GetDetailsForService/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtServiceName').val(response.Name);
$('#txtServiceDescription').val(response.Description);
$('#ddlServiceTax').val(response.TaxId);
$('#txtServiceRate').val(response.SellingPrice);
$('#ddlServiceStatus').val(response.Status);
if (mode == 'CLONE') {
$('#hdServiceId').val("0");
$('#btnAddService').html('<i class="fa fa-clone"></i>Clone');
} else {
$('#hdServiceId').val(response.ItemID);
$('#btnAddService').html('<i></i>Update');
}
} catch (e) {
errorAlert('No Data Found');
}
},
error: function (xhr) {
errorAlert("No data Found");
}
});
}
//Groups for edit
function getGroups(id, mode) {
$.ajax({
url: apirul + 'api/Groups/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtGroupName').val(response.Name);
$('#txtGroupOrder').val(response.Order);
$('#ddlGroupStatus').val(response.Status);
if (true) {
$('#hdnGroupID').val("0");
$('#btnAddNewGroup').html('<i class="fa fa-clone"></i>Clone');
}
else {
$('#hdnGroupID').val(response.ID);
$('#btnAddNewGroup').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert("No data Found");
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
//Category for edit
function GetCategory(id, mode) {
$.ajax({
url: apirul + 'api/Categories/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtCategoryName').val(response.Name);
$('#txtCategoryOrder').val(response.Order);
$('#ddlCategoryStatus').val(response.Status);
if (mode == 'CLONE') {
$('#hdnCategoryID').val("0");
$('#btnAddCategory').html('<i class="fa fa-clone"></i>Clone');
}
else {
$('#hdnCategoryID').val(response.ID);
$('#btnAddCategory').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert("No data Found");
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
function GetUnit(id, mode) {
$.ajax({
url: apirul + 'api/Units/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtUOMName').val(response.Name);
$('#txtUOMShortName').val(response.ShortName);
$('#ddlUOMStatus').val(response.Status);
if (mode == 'CLONE') {
$('#hdnUnitID').val("0");
$('#btnAddUOM').html('<i class="fa fa-clone"></i>Clone');
}
else {
$('#hdnUnitID').val(response.ID);
$('#btnAddUOM').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No data Found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
function GetTax(id, mode) {
$.ajax({
url: apirul + 'api/Taxes/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtTaxName').val(response.Name);
$('#txtTaxPercentage').val(response.Percentage);
$('#txtTaxType').val(response.Type);
$('#ddlTaxStatus').val(response.Status);
if (mode == 'CLONE') {
$('#hdnTaxID').val("0");
$('#btnAddTax').html('<i class="fa fa-clone"></i>Clone');
}
else {
$('#hdnTaxID').val(response.ID);
$('#btnAddTax').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No Data Found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
function getProductType(id, mode) {
$.ajax({
url: apirul + 'api/ProductTypes/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtTypeName').val(response.Name);
$('#txtTypeOrder').val(response.Order);
$('#ddlTypeStatus').val(response.Status);
if (mode == 'CLONE') {
$('#hdnTypeID').val("0");
$('#btnAddType').html('<i class="fa fa-clone"></i>Clone');
}
else {
$('#hdnTypeID').val(response.ID);
$('#btnAddType').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No data found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
function GetVehicle(id, mode) {
$.ajax({
url: apirul + 'api/Vehicles/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtVehicleName').val(response.Name);
$('#txtVehicleNumber').val(response.Number);
$('#txtVehicleType').val(response.Type);
$('#txtVehicleOwner').val(response.Owner);
$('#ddlVehicleStatus').val(response.Status);
if (mode == 'CLONE') {
$('#hdnVehicleID').val("0");
$('#btnAddVehicle').html('<i class="fa fa-clone"></i>Clone');
}
else {
$('#hdnVehicleID').val(response.ID);
$('#btnAddVehicle').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No Data Found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
function getDespatch(id, mode) {
$.ajax({
url: apirul + 'api/Despatch/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
reset();
try {
$('#txtDespatchName').val(response.Name);
$('#txtDespatchAddress').val(response.Address);
$('#txtDespatchNumber').val(response.PhoneNo);
$('#txtDespatchMobile').val(response.MobileNo);
$('#txtDespatchContact').val(response.ContactPerson);
$('#txtDespatchContactPhone').val(response.ContactPersonPhone);
$('#txtDespatchNarration').val(response.Narration);
$('#ddlDespatchStatus').val(response.Status);
if (mode == 'CLONE') {
$('#hdnDespatchID').val("0");
$('#btnAddDespatch').html('<i class="fa fa-clone"></i>Update');
}
else {
$('#hdnDespatchID').val(response.ID);
$('#btnAddDespatch').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No data found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
}
});
}
function getSupplierData(id, mode) {
$.ajax({
url: apirul + 'api/Suppliers/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
try {
var countryId = response.CountryId;
$.ajax({
url: apirul + 'api/Customers/getStates/' + countryId,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (data) {
try {
$('#ddlSupplierCountry').val(response.CountryId);
$('#ddlSupplierState').children('option').remove();
$('#ddlSupplierState').append('<option value="0">--select--</option>');
$(data).each(function () {
$('#ddlSupplierState').append('<option value="' + this.StateId + '">' + this.State + '</option>');
});
$('#txtSupplierName').val(response.Name);
$('#txtSupplierAddres1').val(response.Address1);
$('#txtSupplierAddress2').val(response.Address2);
$('#txtSupplierPhone1').val(response.Phone1);
$('#txtSupplierPhone2').val(response.Phone2);
$('#txtSupplierEmail').val(response.Email);
$('#txtSupplierTax1').val(response.Taxno1);
$('#txtSupplierTax2').val(response.Taxno2);
$('#ddlSupplierStatus').val(response.Status);
$('#ddlSupplierState').val(response.StateId);
$('#ddlSupplierCountry').val(response.CountryId);
$('#imgPhoto').attr('src', response.ProfileImagePath != '' ? response.ProfileImagePath : '../Theme/images/profile-pic.jpg');
if (mode == 'CLONE') {
$('#hdnSupplierID').val("0");
$('#btnAddSupplier').html('<i class="fa fa-clone"></i>Clone');
}
else {
$('#hdnSupplierID').val(response.ID);
$('#btnAddSupplier').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No Data Found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
complete: loading('stop', null);
},
});
} catch (e) {
errorAlert('No Data Found');
}
}
});
}
function getCustomerData(id, mode) {
$.ajax({
url: apirul + 'api/Customers/get/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
try {
var countryId = response.CountryId;
$.ajax({
url: apirul + 'api/Customers/getStates/' + countryId,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (data) {
try {
$('#ddlCustomerCountry').val(response.CountryId);
$('#ddlCustomerState').children('option').remove();
$('#ddlCustomerState').append('<option value="0">--select--</option>');
$(data).each(function () {
$('#ddlCustomerState').append('<option value="' + this.StateId + '">' + this.State + '</option>');
});
$('#ddlCustomerState').val(response.StateId);
$('#txtCustomerName').val(response.Name);
$('#txtCustomerAddress1').val(response.Address1);
$('#txtCustomerAddress2').val(response.Address2);
$('#txtCustomerPhone1').val(response.Phone1);
$('#txtCustomerPhone2').val(response.Phone2);
$('#txtCustomerTax1').val(response.Taxno1);
$('#txtCustomerTax2').val(response.Taxno2);
$('#txtCustomerEmail').val(response.Email);
//$('#txtCustomerTax1').val(response.Taxno1);
//$('#txtCustomertax2').val(response.Taxno2);
$('#txtCustomerCreditAmount').val(response.CreditAmount);
$('#txtCustomerCreditPeriod').val(response.CreditPeriod);
$('#txtCustomerLockAmount').val(response.LockAmount);
$('#txtCustomerLockPeriod').val(response.LockPeriod);
$('#ddlCustomerStatus').val(response.Status);
$('#imgCustomerPhoto').attr('src', response.ProfileImagePath != '' ? response.ProfileImagePath : '../Theme/images/profile-pic.jpg');
if (mode == 'CLONE') {
$('#hdnCustomerID').val("0");
$('#btnAddCustomer').html('<i class="fa fa-clone"></i>Update');
}
else {
$('#hdnCustomerID').val(response.ID);
$('#btnAddCustomer').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No Data Found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
complete: loading('stop', null);
},
});
} catch (e) {
errorAlert('No Data Found');
}
}
});
}
//Lead data for edit
function getLeadData(id, mode) {
$.ajax({
url: apirul + 'api/Leads/GetLeads/' + id,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (response) {
try {
var countryId = response.CountryId;
$.ajax({
url: apirul + 'api/Customers/getStates/' + countryId,
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'Json',
data: JSON.stringify($.cookie("bsl_1")),
success: function (data) {
try {
$('#ddlLeadCountry').val(response.CountryId);
$('#ddlLeadState').children('option').remove();
$('#ddlLeadState').append('<option value="0">--select--</option>');
$(data).each(function () {
$('#ddlLeadState').append('<option value="' + this.StateId + '">' + this.State + '</option>');
});
$('#ddlLeadState').val(response.StateId);
$('#txtLeadName').val(response.Name);
$('#txtLeadAddr1').val(response.Address1);
$('#txtLeadAddr2').val(response.Address2);
$('#txtLeadPh1').val(response.Phone1);
$('#txtLeadPh2').val(response.Phone2);
$('#txtLeadTax1').val(response.Taxno1);
$('#txtLeadTax2').val(response.Taxno2);
$('#txtLeadEmail').val(response.Email);
$('#ddlLeadPrimaryStatus').val(response.Status);
$('#ddlLeadSource').val(response.Source);
$('#ddlAssign').val(response.AssignId);
$('#imgLeadPhoto').attr('src', response.ProfileImagePath != '' ? response.ProfileImagePath : '../Theme/images/profile-pic.jpg');
if (mode == 'CLONE') {
$('#hdLeadId').val("0");
$('#btnAddLead').html('<i class="fa fa-clone"></i>Update');
}
else {
$('#hdLeadId').val(response.ID);
$('#btnAddLead').html('<i class="md md-check"></i>Update');
}
} catch (e) {
errorAlert('No Data Found');
}
},
error: function (xhr) {
alert(xhr.responseText);
console.log(xhr);
complete: loading('stop', null);
},
});
} catch (e) {
errorAlert('No Data Found');
}
}
});
}
loading("stop");
}); |
/* global require */
/* global console:true */
'use strict';
require.config({
paths: {
angular: '../components/angular/angular',
moment: '../components/moment/moment'
},
shim: {
angular: {
exports: 'angular'
},
moment: {
exports: 'moment'
}
}
});
require(['angular', 'app', 'controllers/main'], function(angular){
console = window.console || (console = { log: function(){} });
angular.bootstrap(document,['uni']);
}); |
const R = require('R');
R.Namespace({
RLabel: (function() {
function RLabel() {
return {
setFont(font) {
if (!font) {
R.ErrorID(101);
return;
}
if (font instanceof cc.BitmapFont) {
this.release();
}
this.font = font;
this.retain();
},
retain() {
if (!this.font instanceof cc.BitmapFont) {
return;
}
R.loader.retain(this.font.spriteFrame._textureFilename);
},
release() {
if (!this.font instanceof cc.BitmapFont) {
return;
}
R.loader.release(this.font.spriteFrame._textureFilename);
},
onDestroy() {
this.release();
this._assembler && this._assembler._resetAssemblerData && this._assembler._resetAssemblerData(this._assemblerData);
this._assemblerData = null;
this._letterTexture = null;
if (this._ttfTexture) {
this._ttfTexture.destroy();
this._ttfTexture = null;
}
this._super();
}
}
}
return RLabel();
})()
}); |
import React from "react";
import "./UserInfo.css";
import AccountCircleIcon from "@material-ui/icons/AccountCircle";
import MoreHorizIcon from "@material-ui/icons/MoreHoriz";
function UserInfo() {
return (
<div className="userInfoContainer">
<AccountCircleIcon />
<div className="userInfoName">
<p>jackie chan</p>
<p>@jackiejack</p>
</div>
<MoreHorizIcon />
</div>
);
}
export default UserInfo;
|
var photo1 = document.querySelector('.photo1');
photo1.addEventListener('click',function(){
showImage(photo1);
openLightbox();
}) |
"use strict";
function selectTable(tableId)
{
var id = document.getElementById(tableId);
var tableValue = document.getElementById(tableId).childNodes[0].value;
var tableListId = document.getElementById("table_list");
var tableIdString = String(tableId);
if(parseInt(tableValue))
{
id.style.boxShadow = "0px 0px 10px 2px rgba(0,0,0,0.25)";
id.style.backgroundColor = "rgba(70,70,70,1.0)";
id.childNodes[0].value = 0;
var newtext = (tableIdString.replace("table_","")) + ",";
var newtext2 = tableListId.value;
newtext2 = newtext2.replace((newtext),"");
tableListId.value = newtext2;
}
else
{
id.style.boxShadow = "0px 0px 10px 2px rgba(255,140,0,1.0)";
id.style.backgroundColor = "rgba(90,90,90,1.0)";
id.childNodes[0].value = 1;
tableListId.value += (tableIdString.replace("table_","")) + ",";
}
} |
var mysql = require('mysql');
var dbConfig = require('./config.js');
var pool = mysql.createPool({
connectionLimit : dbConfig.connectionLimit,
host : dbConfig.host,
user : dbConfig.user,
password : dbConfig.password,
database : dbConfig.database,
debug : dbConfig.debug
});
module.exports = pool; |
const { ObjectID } = require('mongodb');
const jwt = require('jsonwebtoken');
var { Todo } = require('../../models/todo.model');
var { User } = require('../../models/user.model');
var userOneId = new ObjectID();
var userTwoId = new ObjectID();
const users = [{
_id: userOneId,
email: 'jmblanco@gmail.com',
password: 'userOnePass',
tokens: [{
access: 'auth',
token: jwt.sign({_id: userOneId, access: 'auth'}, process.env.JWT_SECRET).toString()
}]
},
{
_id: userTwoId,
email: 'vishop@gmail.com',
password: 'userTwoPass',
tokens: [{
access: 'auth',
token: jwt.sign({_id: userTwoId, access: 'auth'}, process.env.JWT_SECRET).toString()
}]
}];
const todos = [{
_id: new ObjectID(),
text: 'First test Todo',
_creator: userOneId
},
{
_id: new ObjectID(),
text: 'Second test Todo',
completed: true,
completedAt: new Date().getTime(),
_creator: userTwoId
}];
const populateTodos = (done) => {
Todo.remove().then(() => {
return Todo.insertMany(todos);
}).then(() => done());
};
const populateUsers = (done) => {
User.remove().then(() => {
var userPromises = [];
users.forEach(user => {
userPromises.push(new User(user).save());
});
return Promise.all(userPromises);
}).then(() => done()).catch((err) => done());
};
module.exports = {
todos,
populateTodos,
users,
populateUsers
}; |
import React, { Component } from 'react'
import GoogleMapReact from 'google-map-react'
const AnyReactComponent = ({ text }) => (
<div>
<img src='/car2go_logo.jpg' style={{height: '32px', width: '32px'}} />
{text}
</div>
)
// https://github.com/istarkov/google-map-react
export default class MeshPointMap extends Component {
static defaultProps = {
center: { lat: 30.247203, lng: -97.7941559 },
zoom: 11
};
render() {
return (
<div style={{ height: '500px' }}>
<GoogleMapReact
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
>
<AnyReactComponent
lat={30.2672}
lng={-97.7431}
text={'Alice'}
/>
<AnyReactComponent
lat={30.2672}
lng={-97.8431}
text={'Bob'}
/>
</GoogleMapReact>
</div>
)
}
}
|
/**
* ListUsers/code2.js
* @file Displays users with certain user rights in div
* <tt>code2.js</tt> allows for the exclusion of users in other rights
* groups via the addition of classes to the <tt>.listusers</tt> div.
* Also, minor i18n configuration added. Made for Diep.io Wikia.
* @authors Eizen <dev.wikia.com/wiki/User_talk:Eizen> (code2.js author)
* Slyst <dev.wikia.com/wiki/User_talk:Slyst> (original author)
* @external "mediawiki.util"
* @external "jQuery"
* @external "wikia.window"
* @external "mw"
*/
/*jslint browser, this:true */
/*global mw, jQuery, window, require, wk, console */
require(["mw", "wikia.window"], function (mw, wk) {
"use strict";
if (window.isListUsersLoaded || !jQuery(".listusers").exists()) {
return;
}
window.isListUsersLoaded = true;
// Remember to leave $1 placeholder
var $i18n = {
"en": {
talk: "talk",
contribs: "contribs",
edits: "edits",
nogroup: "No user group found.",
nousers: "No users were found in the $1 group."
}
};
var $lang = jQuery.extend(
$i18n.en,
$i18n[wk.wgUserLanguage.split("-")[0]],
$i18n[wk.wgUserLanguage]
);
// Defining custom jQuery method to acquire class list array
jQuery.fn.getClassList = function () {
return this[0].className.split(/\s+/);
};
var ListUsers = {
/**
* @method constructLink
* @description Method returns an assembled HTML string, specifically a
* <tt><a></tt> link element, used in the assembly of user
* list elements.
* @param {string} $href
* @param {$text}
* @returns {string}
*/
constructLink: function ($href, $text) {
return mw.html.element("a", {
href: mw.util.getUrl($href),
title: $text
}, $text);
},
/**
* @method getExcludedGroups
* @description The method iterates through the list of element classes
* to determine which (if any) user groups to exclude from
* view in later stages of the script's HTML assembly.
* @param {Object[]} $classes - string array of element classes
* @returns {Object[]} $excludedGroups - string array of excluded groups
*/
getExcludedGroups: function ($classes) {
var $excludedGroups = [];
$classes.forEach(function ($class) {
switch ($class) {
case "LU-exclude-bot":
$excludedGroups.push("bot");
break;
case "LU-exclude-bureaucrat":
$excludedGroups.push("bureaucrat");
break;
case "LU-exclude-chatmoderator":
$excludedGroups.push("chatmoderator");
break;
case "LU-exclude-content-moderator":
$excludedGroups.push("content-moderator");
break;
case "LU-exclude-rollback":
$excludedGroups.push("rollback");
break;
case "LU-exclude-staff":
$excludedGroups.push("staff");
break;
case "LU-exclude-sysop":
$excludedGroups.push("sysop");
break;
case "LU-exclude-threadmoderator":
$excludedGroups.push("threadmoderator");
break;
}
});
return $excludedGroups;
},
/**
* @method assembleHMTL
* @description Method assembles a string of HTML <tt><li></tt> and
* <tt><a></tt> elements based upon the wiki's window
* variable customization options and returns the string.
* @param {string} $username
* @param {int} $editcount
* @param {string} $html
*/
assembleHTML: function ($username, $editCount) {
var $html = "<li>" +
this.constructLink("User:" + $username, $username);
if (this.listUsers.talk) {
$html += " " +
this.constructLink(
"User talk:" + $username,
"(" + $lang.talk + ")"
);
}
if (this.listUsers.contribs) {
$html += " " +
this.constructLink(
"Special:Contributions/" + $username,
"(" + $lang.contribs + ")"
);
}
if (this.listUsers.editcount) {
$html += " " + $editCount + " " + $lang.edits;
}
$html += "</li>";
return $html;
},
/**
* @method getUsersList
* @description getUsersList queries the API to acquire a list of users
* who hold a given right. Each user's additional groups
* are included in the returned data for use in exclusion.
* @param {function} callback
* @param {string} $group
* @param {Object[]} $excludedGroups - string array of excluded groups
*/
getUsersList: function (callback, $group, $excludedGroups) {
var $gmgroups = $group + "|" + $excludedGroups.join("|");
jQuery.ajax({
type: "GET",
url: mw.util.wikiScript("api"),
data: {
action: "query",
list: "groupmembers",
gmgroups: $gmgroups,
gmlimit: this.listUsers.limit,
format: "json"
}
}).done(function ($data) {
if (!$data.error) {
console.log($data);
callback($data, $group, $excludedGroups);
}
});
},
/**
* @method handleUsersList
* @description Method handles the data from the API call in such a way
* to only display users who possess the given right and
* are not also members of any of the excluded user rights
* groups. Once assembled, the html is added to the
* <tt>ul</tt> element.
* @param {json} $data
* @param {string} $group
* @param {Object[]} $excludedGroups - string array of excluded groups
* @returns {void}
*/
handleUsersList: function ($data, $group, $excludedGroups) {
var $allUsers = $data.users;
var $html = "";
jQuery(".listusers#" + $group).html(mw.html.element("ul", {}));
if ($allUsers[0].id === 0) {
jQuery(".listusers#" + $group).html(
$lang.nousers.replace("$1", $group)
);
} else {
$allUsers.forEach(function ($user) {
var $myName = $user.name;
var $myGroups = $user.groups;
var $isNotInExcluded = $myGroups.every(function ($right) {
return jQuery.inArray($right, $excludedGroups) === -1;
});
// Testing purposes only
console.log(
$myName + ": " + "$isNotInExcluded=" + $isNotInExcluded
);
if ($isNotInExcluded) {
$html +=
ListUsers.assembleHTML($myName, $user.editcount);
}
});
}
jQuery(".listusers#" + $group + " ul").html($html);
},
/**
* @method main
* @description main method sorts through user groups and
* <tt>.listusers</tt> elements, getting group-exclusion
* classes and querying the getUsersList method for group
* data.
* @param {Object[]} $groups - string array of user groups
* @returns {void}
*/
main: function ($groups) {
var that = this;
var $elementClasses;
var $excludedGroups;
$groups.forEach(function ($group) {
jQuery(".listusers").each(function () {
$elementClasses = jQuery(this).getClassList();
$excludedGroups = that.getExcludedGroups($elementClasses);
switch (jQuery(this).attr("id")) {
case $group:
that.getUsersList(
that.handleUsersList,
$group,
$excludedGroups
);
break;
case "":
case undefined:
jQuery(this).html($lang.nogroup);
break;
}
});
});
},
/**
* @method init
* @description init method sets basic preferences via window variable
* values, assembles the user rights array, and accounts
* for custom user groups. The array is then passed to main
* @returns {void}
*/
init: function () {
this.listUsers = jQuery.extend({
talk: true,
contribs: false,
editcount: false,
limit: 50,
active: true
}, window.listUsers);
var $userRightsGroups = [
"staff",
"helper",
"voldev",
"vstf",
"vanguard",
"council",
"checkuser",
"bot",
"bureaucrat",
"sysop",
"content-moderator",
"threadmoderator",
"chatmoderator",
"rollback"
];
if (window.listUsers && window.listUsers.customgroups) {
window.listUserscustomgroups.forEach(function ($customGroup) {
$userRightsGroups.push($customGroup);
});
}
this.main($userRightsGroups);
}
};
mw.loader.using("mediawiki.util").then(
jQuery.proxy(ListUsers.init, ListUsers)
);
});
|
import { combineReducers } from 'redux'
import activities from '../../features/activities'
const rootReducer = combineReducers({
[activities.constants.NAMESPACE]: activities.reducer
})
export default rootReducer
|
#!/usr/bin/env node
'use strict';
var optimist = require('optimist');
var appup = require('../');
var path = require('path');
var cwd = process.cwd();
var argv = optimist
.usage('appup [options] file')
.describe('pages' , 'port to start pages server on')
.describe('watchdir' , 'directory to watch for client side JavaScript changes in order to automatically refresh')
.describe('dedupe' , 'if set it will [dynamically dedupe] (https://github.com/thlorenz/dynamic-dedupe)\n\t all modules as they are being required to work around the fact that symlinks break `npm dedupe`')
.describe('api' , 'port to start api server on')
.describe('apihost' , 'address at which api server is hosted')
.describe('tunnel' , 'sets up local tunnel pointing to pages port and logs url to connect to from remote client')
.describe('config' , 'point to a config file to override routes, etc. for the pages and api server')
.describe('nocluster', 'if set, single servers are launched instead of a cluster of them, which maybe preferred during development')
.default ('apihost' , 'localhost')
.boolean ('dedupe')
.argv;
function usageAndBail () {
optimist.showHelp();
process.exit();
}
if (argv.help) usageAndBail();
var entry = argv._[0];
if (!entry) {
console.error('Please provide path to entry file as last argument');
usageAndBail();
}
var config = path.join(cwd, argv.config);
var pagesPort = argv.pages;
var apiPort = argv.api;
var dedupe = !!argv.dedupe;
var watchdir = argv.watchdir && path.resolve(argv.watchdir);
appup({
config : config
, entry : entry
, pagesPort : pagesPort
, apiPort : apiPort
, apiHost : argv.apihost
, tunnel : argv.tunnel
, nocluster : argv.nocluster
, watchdir : watchdir
, dedupe : dedupe
});
|
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { getCharactersById } from '../services/avatarApi';
import { Link } from 'react-router-dom';
export default function DetailPage() {
const [character, setCharacter] = useState({});
const { id } = useParams();
console.log(id, 'character id');
useEffect(() => {
getCharactersById(id).then((character) => setCharacter(character));
}, []);
const { name, allies, enemies, gender, hair, photoUrl } = character;
return (
<div>
<h1>{name}</h1>
<img src={photoUrl} />
<ul>
<li>Allies: {allies}</li>
<li>Enemies: {enemies}</li>
<li>Gender: {gender}</li>
<li>Hair Color: {hair}</li>
</ul>
<Link to="/">List Page</Link>
</div>
);
}
|
const VERSION = 'v1';
self.addEventListener('install', function(e) {
console.log(`install event !!`, e);
// キャッシュ完了まで待機する
e.waitUntil(
caches.open(VERSION).then((cache) => {
return cache.addAll([
'./index.html',
'./main.js',
'./ServiceWorkerTest.js',
]);
})
);
});
self.addEventListener('fetch', function(e) {
console.log('fetch event !!', e);
e.respondWith(
// リクエストに一致するデータがキャッシュにあるかどうか
caches.match(e.request).then(function(cacheResponse) {
console.log('has cache: ', cacheResponse);
// キャッシュがあればそれを返す、なければリクエストを投げる
return cacheResponse || fetch(e.request).then(function(response) {
return caches.open(VERSION).then(function(cache) {
// レスポンスをクローンしてキャッシュに入れる
cache.put(e.request, response.clone());
// オリジナルのレスポンスはそのまま返す
return response;
});
});
})
);
});
self.addEventListener('activate', function(e) {
console.log(`activate event !!`, e);
});
|
import styled from 'styled-components'
let Button = styled.button`
${props => props.bootstrap && `
&:focus{
outline: 0;
}
`}
${props => !props.bootstrap && `
/*
failed:
rgb(174, 74, 74);
rgb(174, 74, 74);
rgb(174, 74, 74);
success + borders:
#1ecd97
#1ecd97
#1ecd97
#1ecd97
#1ecd97
#1ecd97
#1ecd97
*/
@keyframes rotate {
0%{transform: rotate(360deg)}
}
@keyframes bounce {
0%{transform: scale(0.9)}
}
display: inline-block;
width: 220px;
height: 60px;
font-size: 20px;
font-weight: bold;
text-align: center;
line-height: 56px;
box-sizing: border-box;
border-radius: 50px;
outline: none;
/* */
transition: all ease 0.6s;
&.initial {
border: 2px solid #45bec7;
color: #45bec7;
background-color: white;
${'' /* display: inline-block;
width: 220px;
height: 60px;
border: 2px solid #45bec7;
color: #45bec7;
font-size: 20px;
font-weight: bold;
text-align: center;
line-height: 56px;
box-sizing: border-box;
border-radius: 50px;
background-color: white;;
outline: none;
transition: all ease 0.6s;
*/}
}
&:active{
outline: none;
border: none
}
&:focus{
outline: 0;
}
&.hovered{
opacity:1;
color: white;
background: #45bec7;
}
${'' /* &.initial:hover{
opacity:1;
color: white;
background: #45bec7;
} */}
&.hovered:active{
letter-spacing: 2px;
}
&.hovered:after{
content: ''
}
&.pending{
display: inline-block;
width: 220px;
height: 60px;
border: 2px solid #fff;
color: #45bec7;
font-size: 20px;
font-weight: bold;
text-align: center;
line-height: 56px;
box-sizing: border-box;
border-radius: 50px;
background-color: transparent;
outline: none;
/* */
transition: all ease 0.6s;
font-size: 0;
width: 50px;
height: 50px;
border-radius: 50%;
border-left-color: #45bec7;
animation: rotate 1s ease 0.6s infinite
}
&.success{
display: inline-block;
width: 220px;
height: 60px;
border: 2px solid #45bec7;
color: white;
font-size: 20px;
font-weight: bold;
text-align: center;
line-height: 56px;
box-sizing: border-box;
border-radius: 50px;
background-color: #45bec7;
outline: none;
transition: all ease 0.5s;
position: relative;
animation: bounce .3s ease-in;
}
&.success:before{
content: '';
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
width: 31px;
height: 31px;
line-height: 31px;
top: 8px;
}
&.failed {
display: inline-block;
width: 220px;
height: 60px;
border: 2px solid #e57e32;
color: white;
font-size: 20px;
font-weight: bold;
text-align: center;
line-height: 56px;
box-sizing: border-box;
border-radius: 50px;
background:#e57e32;
background-color:#e57e32;
outline: none;
/* */
transition: all ease 0.5s;
position: relative;
animation: bounce .3s ease-in;
}
&.failed:after{
content: '';
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
width: 31px;
height: 31px;
line-height: 31px;
top: 8px;
}`
}
${props => props.theme && props.theme.button}
`
export { Button } |
var info;
var displayedProjects;
var search;
var resize;
var toggleSwitches = [true, false, true, true, true, true, true, true, true, true, true, true, true, true, true];
function shortcut(title = "Projects", val){
document.getElementById("page_title").innerHTML = title;
let temp = toggleSwitches;
toggleSwitches = val;
search();
toggleSwitches = temp;
};
function toggleSettings(){
let x = document.getElementById("settingsContainer");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
};
function toggleCheck(ele){
let el = ele.children[0];
let result;
if (el.src.includes("imgs/checkedBox.png")) {
result = false;
el.src = "imgs/uncheckedBox.png";
} else {
result = true;
el.src = "imgs/checkedBox.png";
}
let on = true;
switch (ele.id){
case "newToOldButtonCheck":
toggleSwitches[14]=result;
on = false;
break;
case "byTagButtonCheck":
toggleSwitches[13]=result;
break;
case "byTitleButtonCheck":
toggleSwitches[12]=result;
break;
case "byDescriptionButtonCheck":
toggleSwitches[11]=result;
break;
case "byDateButtonCheck":
toggleSwitches[10]=result;
break;
case "inProgressButtonCheck":
toggleSwitches[9]=result;
break;
case "recentButtonCheck":
toggleSwitches[8]=result;
break;
case "oldButtonCheck":
toggleSwitches[7]=result;
break;
case "otherButtonCheck":
toggleSwitches[6]=result;
break;
case "artButtonCheck":
toggleSwitches[5]=result;
break;
case "eventsButtonCheck":
toggleSwitches[4]=result;
break;
case "projectsButtonCheck":
toggleSwitches[3]=result;
break;
case "documentsButtonCheck":
toggleSwitches[2]=result;
break;
case "noneButtonCheck":
toggleSwitches[1]=result;
if(result)
{
for(let i = 0; i<toggleSwitches.length-1;i++){ // -1 is for the 15th element
toggleSwitches[i] = false;
document.getElementsByClassName("toggleButton")[i].children[0].src = "imgs/uncheckedBox.png";
}
toggleSwitches[1] = true;
document.getElementById("noneButtonCheck").children[0].src = "imgs/checkedBox.png";
toggleSwitches[0] = false;
document.getElementById("allButtonCheck").children[0].src = "imgs/uncheckedBox.png";
}
on = false;
break;
case "allButtonCheck":
toggleSwitches[0]=result;
if(result)
{
for(let i = 0; i<toggleSwitches.length-1;i++){
toggleSwitches[i] = true;
document.getElementsByClassName("toggleButton")[i].children[0].src = "imgs/checkedBox.png";
}
toggleSwitches[1] = false;
document.getElementById("noneButtonCheck").children[0].src = "imgs/uncheckedBox.png";
}
break;
default: console.log("error with "+ele.id);
}
if(!result && on){
toggleSwitches[0] = false;
document.getElementById("allButtonCheck").children[0].src = "imgs/uncheckedBox.png";
}
else if(ele.id != "noneButtonCheck" && on){
toggleSwitches[1] = false;
document.getElementById("noneButtonCheck").children[0].src = "imgs/uncheckedBox.png";
}
};
printValues = function(arr){
for(let i = 0; i<arr.length;i++){
console.log("Element " + i + ": " + arr[i]);
}
};
search = function(val ="") {
// console.log("searching for: " + val);
let value = val.toLowerCase();
displayedProjects = [];
words = value.split(" ");
for(let i = 0; i<info.length;i++){
let show = false;
if(value != "" && value != null && !(value.indexOf("all") >= 0) && !(value.indexOf("everything") >= 0)){ // indexOf or includes?
let dd = info[i].date;
let d = " " + dd.m + "" + dd.d + "" + dd.y + " "+dd.m + "/" + dd.d + "/" + dd.y + " "+ dd.m + "-" + dd.d + "-" + dd.y + " "+ dd.m + " " + dd.d + " " + dd.y + " "+ dd.m + "\\" + dd.d + "\\" + dd.y + " ";
d = d.toLowerCase();
for(let wordCount = 0; wordCount<words.length;wordCount++){
let str = words[wordCount];
if( (toggleSwitches[11] && info[i].description.toLowerCase().indexOf(str) >= 0)
|| (toggleSwitches[12] && info[i].title.toLowerCase().indexOf(str) >= 0)
|| (toggleSwitches[13] && info[i].tags.toLowerCase().indexOf(str) >= 0)
){
show = true;
}
}
if(toggleSwitches[10] && (d.indexOf(value) >= 0 || value.indexOf((dd.y + "").trim()) >= 0)){
show = true;
}
}
else {show=true;}
if ( show &&
(
(info[i].type.toLowerCase().indexOf("doc") >= 0 && toggleSwitches[2])
|| (info[i].type.toLowerCase().indexOf("proj") >= 0 && toggleSwitches[3])
|| (info[i].type.toLowerCase().indexOf("event") >= 0 && toggleSwitches[4])
|| (info[i].type.toLowerCase().indexOf("art") >= 0 && toggleSwitches[5])
|| ((info[i].type.toLowerCase().indexOf("other") >= 0 || info[i].type.toLowerCase().indexOf("othr") >= 0)&& toggleSwitches[6])
)
&&
(
(info[i].state.toLowerCase().indexOf("old") >= 0 && toggleSwitches[7])
|| (info[i].state.toLowerCase().indexOf("recent") >= 0 && toggleSwitches[8])
|| (((info[i].state.toLowerCase().indexOf("in progress") >= 0) || (info[i].state.toLowerCase().indexOf("inprogress") >= 0) || (info[i].state.toLowerCase().indexOf("in-progress") >= 0)) && toggleSwitches[9])
)
){
show = true;
}
else{
show = false;
}
if(show == true){
displayedProjects.push(info[i]);
}
}
// console.log("search complete");
if(displayedProjects.length <= 0){
alert("No match for \""+val+"\" found");
// displayedProjects = [];
}
else{
}
// console.log("Sorting...");
sort();
// console.log("Sort complete");
// console.log("Loading Files & Graphics...");
resize(toggleSwitches[14]);
// console.log("Resize complete");
// console.log("Done");
};
sort = function(){
//order by date
if(displayedProjects.length > 1){
displayedProjects = f.shell(displayedProjects);
}
};
fit = function(str, ln = 27, breakWords = true, breaker = "<br>", splitter = "-"){ // by char
str = str.trim();
let lastIndex = 0, previousIndex = 0, i = 0, temp;
// console.log("str is " + str.length + "chars long");
safetyLength = (breaker.length) * str.length;
while (i < str.length && i < safetyLength) {
temp = str.indexOf(breaker, i);
i = str.indexOf(" ", i);
if(temp >=0 && temp <= i){
i = temp + breaker.length;
lastIndex = i;
previousIndex = i;
// console.log("continued");
continue;
}
// console.log("i = " + i);
// console.log("last is "+lastIndex+" & previous index is "+previousIndex);
if(i < 0){
// console.log("CASE 1");
if(str.length - lastIndex > ln+4){
// console.log("CASE 1.1");
str = str.substring(0, lastIndex+ln).concat(splitter, breaker, str.substring(lastIndex+ln));
}
break;
} else if(breakWords && i - previousIndex > ln){
// console.log("CASE 2");
str = str.substring(0, previousIndex + ln).concat(splitter, breaker, str.substring(previousIndex + ln + splitter.length));
previousIndex = previousIndex + ln + splitter.length;
lastIndex = i;
} else if(i - lastIndex > ln){
// console.log("CASE 3");
lastIndex = previousIndex;
str = str.substring(0, previousIndex).concat(breaker, str.substring(previousIndex+1));
previousIndex = i + breaker.length;
} else {
previousIndex = i;
i++;
}
}
return str;
};
//console.log(fit("Hi your\nmy hat is george", 12));
resize = function(bool) {
//sort();
if(bool == undefined){
bool = toggleSwitches[14];
}
// console.log("bool is " + bool);
let w = window.innerWidth;
let dpl = displayedProjects.length;
if(dpl <=0) return;
let cols;
if(w > 2400){ cols = 7;}
else if(w > 1800){ cols = 6;}
else if(w > 1500){ cols = 5;}
else if(w > 1100){ cols = 4;}
else if(w > 800){ cols = 3;}
else if(w > 520){ cols = 2;}
else { cols = 1;}
let table = document.getElementById("project_table");
// remove all child elements from table
while (table.firstChild) {
table.removeChild(table.firstChild);
}
let _create, create = function (num, tr){
let td = document.createElement("td"); // box/el
tr.appendChild(td);
td.style.backgroundColor = displayedProjects[num].backgroundColor;
td.setAttribute("class","hoverableElement");
td.setAttribute("id","displayedProjectNum"+num); // changes with disp project
_create(displayedProjects[num], td);
};
_create = function(current_project, td){
let projectImg = document.createElement("img");
projectImg.setAttribute("src", current_project.img);
projectImg.setAttribute("alt", "Image would be here");
projectImg.setAttribute("class", "projectImage");
try {
let ttemp = current_project.transform;
if(ttemp != null && ttemp != ""){
projectImg.style.transform = ttemp;
}
}
catch(error) {
//console.log(error);
}
projectImg.style.WebkitFilter = current_project.imageFilter;
projectImg.style.filter = current_project.imageFilter;
try { // erronouse
if(typeof current_project.rotation !== 'undefined' && current_project.rotation != null && current_project.rotation != 0){
let foo = current_project.rotation;
foo = (typeof foo === String && foo.includes("rotate("))? foo : (typeof foo==='number')? (Math.abs(foo)<3.15)? `rotate(${foo})`: `rotate(${foo}deg)`: `rotate(${foo})`;
projectImg.style.transform = foo;
}
}
catch(error) {
console.log(error);
}
projectImg.style.width = "100%";
td.appendChild(projectImg);
let dateNode = document.createElement("a");
dateNode.setAttribute("class", "dateOfProject");
dateNode.style.color = current_project.dateTextColor;
let d = current_project.date;
let dytemp = d.y ? d.y : "-";
let dmtemp = d.m ? d.m : "-";
if(typeof d.y != "string" && d.y > 2000){ // i could make it be a typeof number?
d.y = d.y - 2000;
}
if(typeof dmtemp== "string" && !(dmtemp == "" || dmtemp == "-" || dmtemp == " " || dmtemp == null)){
if(dmtemp.toLowerCase().indexOf("jan") >= 0){ dmtemp = 1 }
else if(dmtemp.toLowerCase().indexOf("jan") >= 0){ dmtemp = 1 }
else if(dmtemp.toLowerCase().indexOf("feb") >= 0){ dmtemp = 2 }
else if(dmtemp.toLowerCase().indexOf("mar") >= 0){ dmtemp = 3 }
else if(dmtemp.toLowerCase().indexOf("apr") >= 0){ dmtemp = 4 }
else if(dmtemp.toLowerCase().indexOf("may") >= 0){ dmtemp = 5 }
else if(dmtemp.toLowerCase().indexOf("jun") >= 0){ dmtemp = 6 }
else if(dmtemp.toLowerCase().indexOf("jul") >= 0){ dmtemp = 7 }
else if(dmtemp.toLowerCase().indexOf("aug") >= 0){ dmtemp = 8 }
else if(dmtemp.toLowerCase().indexOf("sep") >= 0){ dmtemp = 9 }
else if(dmtemp.toLowerCase().indexOf("oct") >= 0){ dmtemp = 10 }
else if(dmtemp.toLowerCase().indexOf("nov") >= 0){ dmtemp = 11 }
else if(dmtemp.toLowerCase().indexOf("dec") >= 0){ dmtemp = 12 }
}
dateNode.innerHTML = dmtemp + "/" + ((d.d != null && d.d != undefined)? d.d: "-") + "/"+dytemp; // could probrably make this better
td.appendChild(dateNode);
let overlayObj = document.createElement("div");
overlayObj.setAttribute("class", "overlay");
td.appendChild(overlayObj);
let overlayText = document.createElement("div");
overlayText.setAttribute("class", "boxOverlayText");
description = current_project.description;
switch (description.substring(0,3).toUpperCase()){ // DO NOT USE WITH LINKS
case "[F]": // fit
description = fit(description.substring(3));
break;
case "[R]": // remove \ns then fit
description = fit(description.substring(3).replace(/\n/g, " ").replace(/<br>/g, " "));
break;
}
overlayText.innerHTML = description;
overlayObj.appendChild(overlayText);
let textContainer = document.createElement("div");
textContainer.setAttribute("class", "textContainer");
td.appendChild(textContainer);
let projectTitle = document.createElement("p");
projectTitle.innerHTML = current_project.title;
textContainer.appendChild(projectTitle);
};
let rs = Math.floor(dpl/cols);
if(!bool){ // past at top
for(let r = 0; r < rs;r++){
let tr = document.createElement("tr");
table.appendChild(tr);
for(let i=0;i<cols;i++){
create((r*cols) + i, tr);
}
}
if(dpl%cols != 0){
let tr = document.createElement("tr");
table.appendChild(tr);
for(let i = ((rs) * cols); i< dpl; i++){
create(i, tr);
}
for(let i = 0; i< cols-(dpl +1); i++){
let td = document.createElement("td");
tr.appendChild(td);
td.setAttribute("class", "spacer");
}
}
}
else { // new at top
// console.log("experimental resize");
let sub = dpl-1;
for(let r = 0; r < rs;r++){
let tr = document.createElement("tr");
table.appendChild(tr);
for(let i=0;i<cols;i++){
create(sub - ((r*cols) + i), tr);
}
}
if(dpl%cols != 0){
let tr = document.createElement("tr");
table.appendChild(tr);
for(let i = ((rs) * cols); i< dpl; i++){
create(sub - i, tr);
}
for(let i = 0; i< cols-(dpl +1); i++){
let td = document.createElement("td");
tr.appendChild(td);
td.setAttribute("class", "spacer");
}
}
}
};
window.addEventListener("load", function(event) {
console.log("V3.04a"); //25 char max
let request = new XMLHttpRequest();
let callback = function(zone) {
info = zone;
let temp = location.href;
if (location.href.includes("#art")){
this.shortcut('Art',[true, false, false, false, false, true, false, true, true, true, false, false, false, true, true]);
} else {
let temp2 = temp.substr(temp.indexOf("julientoons.github.io/projects/#") + ("julientoons.github.io/projects/#").length );
console.log(temp + " .. XXX" + temp2);
if(temp2.length <= 0 || temp == "julientoons.github.io/projects" || temp == "julientoons.github.io/projects/" || !temp.includes("#")){
search();
}
else{
search(temp2);
}
}
//this.shortcut("Projects",[true, false, false, true, false, false, false, true, true, true, false, false, false, true, true]);
};
request.addEventListener("load", function(event) {
callback(JSON.parse(this.responseText));
}, { once:true });
request.open("GET", "project_info.json");
request.send();
window.addEventListener("resize" , resize);
}); |
"use strict" // latest javaScript standart
$(function(){
// document elements
var canvas = document.getElementById('field');
var context = canvas.getContext('2d');
var startBtn = document.getElementById('start');
var stopBtn = document.getElementById('stop');
var generation = document.getElementById('generationNum');
var info = document.getElementsByClassName('info');
var interval;
// other variables
var num = 30; // field dimendion
var height = canvas.clientHeight;
var width = canvas.clientWidth;
var cellHeight = height/num;
var cellWidth = width/num;
var lineWidth = 1; // widht of border between cells
var curField = [];
var nextField = [];
var Game = {};
// methods definitions
Game.getStartPosition = function() {
Game.renderField();
Game.initFields();
canvas.addEventListener('click', Game.fieldClick);
stopBtn.addEventListener('click', Game.stopGame);
startBtn.value = "Start";
stopBtn.value = "Stop";
generation.innerHTML = '0';
info[0].style.visibility = "visible";
stopBtn.disabled = true;
stopBtn.classList.remove('activeBtn');
stopBtn.classList.add('disabledBtn');
}
Game.gaming = function() {
interval = setInterval(Game.update, 1000);
canvas.removeEventListener('click', Game.fieldClick);
info[0].style.visibility = "hidden";
stopBtn.value = "Stop";
stopBtn.removeEventListener('click', Game.getStartPosition);
stopBtn.addEventListener('click', Game.stopGame);
startBtn.disabled = true;
startBtn.classList.remove('activeBtn');
startBtn.classList.add('disabledBtn');
stopBtn.disabled = false;
stopBtn.classList.remove('disabledBtn');
stopBtn.classList.add('activeBtn');
}
Game.stopGame = function() {
clearInterval (interval);
startBtn.disabled = false;
startBtn.classList.remove('disabledBtn');
startBtn.classList.add('activeBtn');
startBtn.value = "Continue";
stopBtn.value = "New Game";
stopBtn.removeEventListener('click', Game.stopGame);
stopBtn.addEventListener('click', Game.getStartPosition);
}
Game.update = function() {
generation.innerHTML = Number(generation.innerHTML) + 1;
for (var i = 0; i < num; i++){
for (var j = 0; j < num; j++){
var n = Game.aliveNeighbors(i, j);
if (curField[i][j] === 1){
if (n < 2 || n > 3)
nextField[i][j] = 0;
else
nextField[i][j] = 1;
}
else{
if (n === 3)
nextField[i][j] = 1;
else
nextField[i][j] = 0;
}
}
}
for (var i = 0; i < num; i++){
for (var j = 0; j < num; j++){
if (nextField[i][j] !== curField[i][j]){
var sx = j*cellWidth;
var sy = i*cellHeight;
Game.drawRect (sx+lineWidth, sy+lineWidth, cellWidth-2*lineWidth, cellHeight-2*lineWidth, nextField[i][j]);
}
}
}
for (var i = 0; i < nextField.length; i++)
curField[i] = nextField[i].slice();
}
Game.aliveNeighbors = function(r, c) {
var cnt = 0;
if (r === 0){
if (curField[num-1][c] === 1)
cnt++;
if (c === 0){
if (curField[num-1][num-1] === 1)
cnt++;
}
else
if (curField[num-1][c-1] === 1)
cnt++;
if (c === num-1){
if (curField[num-1][0] === 1)
cnt++;
}
else
if (curField[num-1][c+1] === 1)
cnt++;
}
else{
if (curField[r-1][c] === 1)
cnt++;
if (c === 0){
if (curField[r-1][num-1] === 1)
cnt++;
}
else
if (curField[r-1][c-1] === 1)
cnt++;
if (c === num-1){
if (curField[r-1][0] === 1)
cnt++;
}
else
if (curField[r-1][c+1] === 1)
cnt++;
}
if (c === 0){
if (curField[r][num-1] === 1)
cnt++;
}
else
if (curField[r][c-1] === 1)
cnt++;
if (c === num-1){
if (curField[r][0] === 1)
cnt++;
}
else
if (curField[r][c+1] === 1)
cnt++;
if (r === num-1){
if (curField[0][c] === 1)
cnt++;
if (c === 0){
if (curField[0][num-1] === 1)
cnt++;
}
else
if (curField[0][c-1] === 1)
cnt++;
if (c === num-1){
if (curField[0][0] === 1)
cnt++;
}
else
if (curField[0][c+1] === 1)
cnt++;
}
else{
if (curField[r+1][c] === 1)
cnt++;
if (c === 0){
if (curField[r+1][num-1] === 1)
cnt++;
}
else
if (curField[r+1][c-1] === 1)
cnt++;
if (c === num-1){
if (curField[r+1][0] === 1)
cnt++;
}
else
if (curField[r+1][c+1] === 1)
cnt++;
}
return cnt;
}
Game.renderField = function() {
context.clearRect(0,0,width,height);
context.strokeStyle="#000";
for (var i = 0; i < num - 1; i++){
var dx = width/num*(i+1);
var dy = height/num*(i+1);
context.beginPath();
context.lineWidth=lineWidth;
context.moveTo(0, dy);
context.lineTo(width, dy);
context.stroke();
context.beginPath();
context.moveTo(dx, 0);
context.lineTo(dx, height);
context.stroke();
}
}
Game.initFields = function() {
for (var i = 0; i < num; i++){
curField[i] = [];
nextField[i] = [];
for (var j = 0; j < num; j++){
curField[i][j] = 0;
nextField[i][j] = 0;
}
}
}
Game.fieldClick = function(e) {
var rect = canvas.getBoundingClientRect();
var x = e.clientX - Math.floor(rect.left);
var y = e.clientY - Math.floor(rect.top);
var row = Math.floor(y/cellHeight);
var column = Math.floor(x/cellWidth);
var sx = (column)*cellWidth;
var sy = (row)*cellHeight;
if (curField[row][column] === 0){
curField[row][column] = 1;
Game.drawRect(sx+lineWidth, sy+lineWidth, cellWidth-2*lineWidth, cellHeight-2*lineWidth, 1);
}
else if (curField[row][column] === 1){
curField[row][column] = 0;
Game.drawRect(sx+lineWidth,sy+lineWidth,cellWidth-2*lineWidth,cellHeight-2*lineWidth,0);
}
else{
alert('clickProcess: the value of chosen cell: ' + curField[row][column]);
}
}
Game.drawRect = function(sx, sy, width, height, val) {
if (val === 1){
context.fillStyle = "#4aa54d";
}
if (val === 0){
context.fillStyle = "#7c7c7c";
}
context.fillRect(sx, sy, width, height);
}
// first call of game
Game.getStartPosition();
startBtn.addEventListener('click', Game.gaming);
}); |
import React from 'react'
import { BrowserRouter, Route , IndexRoute, Redirect } from 'react-router-dom'
import App from '../App'
import Home from '../views/home'
import test from '../views/test'
import notFind from '../views/404'
class Routers extends React.Component {
constructor(props){
super(props)
}
render (){
return(
<BrowserRouter>
<App>
<Route exact path="/" component={Home} />
<Route path="/test" component={test} />
<Redirect path="*" to="/404" component={notFind}/>
</App>
</BrowserRouter>
)
}
}
export default Routers
|
import axiosins from './axiosins.js';
//获取首页三级分类
export function getBaseCategoryList(){
return axiosins.get('/api/product/getBaseCategoryList')
} |
/**
*
* Author : Sepehr Aliakbary
* A component that informations of Row and Frid
*
* @components Row and Grid
*/
const Row = React.createClass({
/**
* render the Row DOM at html page
* @method render
*/
render: function () {
var row = [];
for (var i = 0; i < this.props.width; i++) {
row.push(<Cell snakes={this.props.snakes} key={i} rowId={this.props.rowId} colId={i}
width={this.props.width} height={this.props.height}
size={this.props.size}
pegs={this.props.pegs}/>);
}
return (
<div className="row">
{row}
</div>
);
},
});
const Grid = React.createClass({
/**
* render the Grid DOM at html page
* @method render
*/
render: function () {
var rows = [];
for (var i = 0; i < this.props.height; i++) {
rows.push(<Row snakes={this.props.snakes}
width={this.props.width} height={this.props.height}
key={i} rowId={i} num={this.props.height} size={this.props.width * this.props.height}
pegs={this.props.pegs}/>);
}
return (
<div className="grid columns eight">
{rows}
</div>
);
},
}); |
const defaultStream = require('../default-stream');
const f = require('flyd');
const R = require('ramda');
f.filter = require('flyd/module/filter');
const getStorage = key => JSON.parse(localStorage.getItem(key));
const setStorage = R.curry((key, value) => localStorage.setItem(key, JSON.stringify(value)));
const storageEventStream = () => {
const stream = f.stream();
window.addEventListener('storage', stream);
return f.map(e => ({key: e.key, value: JSON.parse(e.newValue)}), stream);
};
/**
* @return driver:{
* input:({key: stream(value:JSON)}),
* output:{
* state:stream({key:string, value:string})
* - setting
* - set
* get:(key) -> stream(value:JSON)
* }
* }
*/
const create = () => {
const state = f.stream();
const keys = {};
const createKey = name => {
const inputs = {
driver: f.stream(),
storage: f.map(R.prop('value'), f.filter(R.propEq('key', name), storageEventStream()))
};
const setValue = f.filter(value => !R.equals(inputs.storage(), value), inputs.driver);
f.on(value => {
state({ key: name, value: 'setting'});
setStorage(name, value);
state({ key: name, value: 'set'});
}, setValue);
const output = defaultStream(getStorage(name), inputs.storage);
return {input: inputs.driver, output};
};
const getKey = name => keys[name] ? keys[name] : keys[name] = createKey(name);
const output = {
get: name => getKey(name).output,
state
};
const input = R.mapObjIndexed((stream, key) => f.on(getKey(key).input, stream));
return {input, output};
};
module.exports = {create};
|
const startup = function(cb) {
import('./index.js').then((invitro) => {
cb(invitro.default);
});
}
export default startup;
|
export default function ({ dispatch }) {
return next => action => {
const { types, request } = action
if (!types) {
return next(action)
}
const [ requestType, successType ] = types
/**
* Given that the fixtures are not asnyc and will always work, just dispatch
* the request and success actions together. Normally this would await api
* responses and dispatch the appropriate success / failure actions.
*/
dispatch({
type: requestType
})
const response = request()
dispatch({
type: successType,
response
})
}
}
|
import React, { Component } from 'react';
import axios from "axios";
const getNavStates = (indx, length) => {
let styles = []
for (let i = 0; i < length; i++) {
if (i < indx) {
styles.push('done')
} else if (i === indx) {
styles.push('doing')
} else {
styles.push('todo')
}
}
return { current: indx, styles: styles }
}
const checkNavState = (currentStep, stepsLength) => {
if (currentStep > 0 && currentStep < stepsLength - 1) {
return {
showPreviousBtn: true,
showSubmitBtn: false,
showNextBtn: true
}
} else if (currentStep === 0) {
return {
showPreviousBtn: false,
showSubmitBtn: false,
showNextBtn: true
}
} else if (currentStep === 4) {
return {
showPreviousBtn: true,
showNextBtn: false,
showSubmitBtn: true
}
} else {
return {
showPreviousBtn: true,
showSubmitBtn: false,
showNextBtn: false
}
}
}
export default class MultiStep extends Component {
state = {
showPreviousBtn: false,
showSubmitBtn: false,
showNextBtn: true,
compState: 0,
navState: getNavStates(0, this.props.steps.length),
}
setNavState = next => {
this.setState({
navState: getNavStates(next, this.props.steps.length)
})
if (next < this.props.steps.length) {
this.setState({ compState: next })
}
this.setState(checkNavState(next, this.props.steps.length))
}
handleKeyDown = evt => {
if (evt.which === 13) {
this.next()
}
}
handleOnClick = evt => {
if (
evt.currentTarget.value === this.props.steps.length - 1 &&
this.state.compState === this.props.steps.length - 1
) {
this.setNavState(this.props.steps.length)
} else {
this.setNavState(evt.currentTarget.value)
}
}
next = () => {
this.setNavState(this.state.compState + 1)
}
previous = () => {
if (this.state.compState > 0) {
this.setNavState(this.state.compState - 1)
}
}
getClassName = (className, i) => {
return className + '-' + this.state.navState.styles[i]
}
renderSteps = () => {
return this.props.steps.map((s, i) => (
<li
className={this.getClassName('progtrckr', i)}
onClick={this.handleOnClick}
key={i}
value={i}
>
<span>{this.props.steps[i].name}</span>
</li>
))
}
submit = event => {
event.preventDefault();
axios.post(`/api/user/get`, {
key:this.props.profile.name,
username: sessionStorage.getItem('userName'),
userPic: sessionStorage.getItem('userPic'),
gender: sessionStorage.getItem('gender'),
location: sessionStorage.getItem('location'),
occupation: sessionStorage.getItem('occupation'),
bio: sessionStorage.getItem('bio'),
idealLiving: sessionStorage.getItem('living'),
pets: sessionStorage.getItem('pets'),
})
.then((response) => {
console.log(response.data)
window.location = '/dashboard'
})
.catch((err) => {
console.log(err)
})
}
render () { console.log(this.props)
return (
<div className="uk-width-1-2@l" onKeyDown={this.handleKeyDown}>
<ol className='progtrckr'>
{this.renderSteps()}
</ol>
{this.props.steps[this.state.compState].component}
<div className="uk-margin" style={this.props.showNavigation ? {} : { display: 'none' }}>
<button
style={this.state.showPreviousBtn ? {} : { display: 'none' }}
onClick={this.previous}
id="delete-button"
>
Previous
</button>
<span> </span>
<button
style={this.state.showNextBtn ? {} : { display: 'none' }}
onClick={this.next}
id="login-button"
>
Next
</button>
<button
style={this.state.showSubmitBtn ? {} : { display: 'none' }}
onClick={this.submit}
id="login-button"
>
Submit
</button>
</div>
</div>
)
}
}
MultiStep.defaultProps = {
showNavigation: true
}
|
/*
设置-帮助界面
*/
let Dialog = require("../../frameworks/mvc/Dialog");
cc.Class({
extends: Dialog,
properties: {
scrollview: cc.ScrollView
},
onLoad() {
this._super();
let node = new cc.Node();
let sprite = node.addComponent(cc.Sprite);
cc.loader.loadRes(qf.res.setting_help_1, cc.SpriteFrame, (err, spriteFrame) => {
sprite.spriteFrame = spriteFrame;
let r = spriteFrame.getRect();
this.scrollview.content.height = r.height;
});
node.anchorX = 0;
node.anchorY = 1;
this.scrollview.content.addChild(node);
},
onClick(touch, name) {
switch (name) {
case 'close':
this.removeSelf();
break;
}
}
}); |
const tidyLink = (url, name, hoverText) =>
hoverText === undefined ? `[${name}](${url})` : `[${name}](${url} "${hoverText}")`;
const result = tidyLink('https://www.google.com', 'Google');
console.log(result);
// function tidyLink(url, name, hoverText) {
// return `[${name}](${url}` + (hoverText ? ` "${hoverText}")` : ')')
// }
// function tidyLink(url, name, hoverText = "") {
// const check = `${hoverText ? ` "${hoverText}"` : hoverText}`;
// return `[${name}](${url}${check})`;
// }
// const tidyLink = (url, name, hoverText = "") => `[${name}](${url}${hoverText && ` "${hoverText}"`})`;
|
var searchData=
[
['buttondisabledgenericactivity_2ejava',['ButtonDisabledGenericActivity.java',['../_button_disabled_generic_activity_8java.html',1,'']]],
['buttoneventsgenericactivity_2ejava',['ButtonEventsGenericActivity.java',['../_button_events_generic_activity_8java.html',1,'']]],
['buttonprogrammingsamplegenericactivity_2ejava',['ButtonProgrammingSampleGenericActivity.java',['../_button_programming_sample_generic_activity_8java.html',1,'']]],
['buttonresizegenericactivity_2ejava',['ButtonResizeGenericActivity.java',['../_button_resize_generic_activity_8java.html',1,'']]],
['buttonsoverviewgenericactivity_2ejava',['ButtonsOverviewGenericActivity.java',['../_buttons_overview_generic_activity_8java.html',1,'']]]
];
|
export const FETCH_POSTS_REQUEST = "FETCH_POSTS_REQUEST";
export const FETCH_POSTS_SUCCESS = "FETCH_POSTS_SUCCESS";
export const FETCH_POSTS_FAILURE = "FETCH_POSTS_FAILURE";
export const FETCH_POST_REQUEST = "FETCH_POST_REQUEST";
export const FETCH_POST_SUCCESS = "FETCH_POST_SUCCESS";
export const FETCH_POST_FAILURE = "FETCH_POST_FAILURE";
export const FETCH_POSTS_BY_USER_ID_REQUEST = "FETCH_POSTS_BY_USER_ID_REQUEST";
export const FETCH_POSTS_BY_USER_ID_SUCCESS = "FETCH_POSTS_BY_USER_ID_SUCCESS";
export const FETCH_POSTS_BY_USER_ID_FAILURE = "FETCH_POSTS_BY_USER_ID_FAILURE";
export const FETCH_POST_USERS_REQUEST = "FETCH_POST_USERS_REQUEST";
export const FETCH_POST_USERS_SUCCESS = "FETCH_POST_USERS_SUCCESS";
export const FETCH_POST_USERS_FAILURE = "FETCH_POST_USERS_FAILURE";
export const CREATE_POST_REQUEST = "CREATE_POST_REQUEST";
export const CREATE_POST_SUCCESS = "CREATE_POST_SUCCESS";
export const CREATE_POST_FAILURE = "CREATE_POST_FAILURE";
export const UPDATE_POST_REQUEST = "UPDATE_POST_REQUEST";
export const UPDATE_POST_SUCCESS = "UPDATE_POST_SUCCESS";
export const UPDATE_POST_FAILURE = "UPDATE_POST_FAILURE";
export const DELETE_POST_REQUEST = "DELETE_POST_REQUEST";
export const DELETE_POST_SUCCESS = "DELETE_POST_SUCCESS";
export const DELETE_POST_FAILURE = "DELETE_POST_FAILURE";
|
'use strict';
describe('input test',function(){
it('Input 双向绑定的实现',function(){
browser.get("test/e2e/testee/input/web/self.html");
element(by.css(".demo1 input.form-control")).sendKeys(123)
.then(function(){
//输入操作后的回调函数,获取绑定的span innerHTML
var binding_value=element(by.css(".demo1 span.ng-binding"));
expect(binding_value.getText()).toBe("123");
});
});
it('placeholder提示信息',function(){
// browser.get("test/e2e/testee/input/web/self.html");
var rdk_input=element(by.css(".demo2 input.form-control"));
expect(rdk_input.getAttribute("placeholder")).toBe("please enter an number!");
rdk_input.sendKeys(110);
expect(rdk_input.getAttribute("value")).toBe("110");
});
it('readOnly 切换',function(){
// browser.get("test/e2e/testee/input/web/self.html");
var rdk_input=element(by.css(".demo3 input.form-control"));
expect(rdk_input.getAttribute("readonly")).toBe("true");//初始值
element(by.css(".demo3 button")).click();//切换
expect(rdk_input.getAttribute("readonly")).toBe(null);
rdk_input.clear().sendKeys(250);//清除并且输入250
expect(rdk_input.getAttribute("value")).toBe("250");
element(by.css(".demo3 button")).click();
rdk_input.sendKeys(500).then(function(err){
//只有出错才会有err参数
});
expect(rdk_input.getAttribute("value")).toBe("250");//值不变
});
}); |
function PlaySound(clicked_id) {
var path = "audio/"
var snd = new Audio(path + clicked_id + ".mp3");
snd.play();
} |
import { FETCH_START, FETCH_END, FETCH_ERROR, FETCH_CANCEL } from '../actions/fetchActions';
export default (previousState = 0, { type }) => {
switch (type) {
case FETCH_START:
return previousState + 1;
case FETCH_END:
case FETCH_ERROR:
case FETCH_CANCEL:
return Math.max(previousState - 1, 0);
default:
return previousState;
}
};
|
import React, {useEffect, useState, useContext} from "react";
import {Dropdown, Button, Spacer} from "../../components";
import * as TBA from "../../TBA";
import {Link} from "react-router-dom";
import {SettingsContext} from "../../contexts/settings";
// parse the matchKey to readable format. this will later be stored in the store.match
const parseMatch = eventMatchKey => {
const [, matchKey] = eventMatchKey.split("_");
const tokens = matchKey.split(/\d+/);
const parsedTokens = tokens.map(token => {
switch(token) {
case "qf":
return "Quarter Final";
case "sf":
return "Semi Final";
case "f":
return "Final";
case "qm":
return "Qualifier";
case "m":
return "Match";
default:
return "";
}
});
const numbers = matchKey.split(/[a-z]+/).slice(1, 3);
const connected = parsedTokens.filter(word => word).map((word, i) => `${word} ${numbers[i]} `);
return connected;
};
const MatchList = () => {
const [match, setMatch] = useState("");
const [matchList, setMatchList] = useState([]);
const {store} = useContext(SettingsContext);
useEffect( () => {
let cancel = false;
// get the next match in event
const getNextMatch = async (event, callback) => {
if (!cancel) {
const matches = await TBA.fetchMatchesForEvent(event);
const sorted = matches.sort((a, b) => a.time - b.time);
setMatchList(matches.map(match => match.key));
const upcoming = sorted.filter(match => !match.actual_time)[0];
callback(upcoming ? upcoming.key : "");
}
};
getNextMatch(store.event, upcoming => setMatch(upcoming));
return () => {cancel = true;};
}, [store.event]);
const options = matchList.map(matchString => ({value: matchString, text: parseMatch(matchString)}));
return (
<div>
<h1>Scouting</h1>
<h4>choose match</h4>
<Dropdown options={options} onChange={e => setMatch(e.target.value)} value={match}/>
<Spacer />
<Link to={"scouting/" + match}>
<Button disabled={!matchList.includes(match)}>Scout!</Button>
</Link>
</div>
);
};
export default MatchList;
|
import Head from 'next/head';
import classes from '../styles/Home.module.css';
import Link from 'next/link';
import Image from 'next/image';
import Button from '../components/UI/Button/Button';
export default function Home() {
return (
<div className={classes.container}>
<Head>
<title>Stello | Home</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={classes.main}>
<div className={classes.heroImg}>
<Image src="/iphone-12.png" alt="iPhone 12 mini" height={492} width={500} layout="intrinsic" />
</div>
<div className={classes.info}>
<h4 className={classes.heading}>iPhone 12</h4>
<div className={classes.highlights}>
<h1>Blast Past Fast.</h1>
<h1>A14 Bionic chip.</h1>
<h1>5G Just Got Real.</h1>
</div>
<div className={classes.details}>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc imperdiet, tortor a bibendum finibus, lorem velit finibus ipsum, ut efficitur nunc urna vitae mi. Nullam nunc eros, egestas eget sem ut, vehicula semper neque. Proin blandit, ipsum vel accumsan elementum, metus dui accumsan velit, at laoreet quam arcu at purus. Nam accumsan, ligula vel tempus bibendum.</p>
</div>
<Link href="/shop">
<a>
<Button>Discover Now</Button>
</a>
</Link>
</div>
</main>
<div className={classes.backText}>
<span>i</span>
<span>P</span>
<span>H</span>
<span>O</span>
<span>N</span>
<span>E</span>
<span>1</span>
<span>2</span>
</div>
</div>
)
}
|
module.exports = (sequelize, DataTypes) => {
return sequelize.define('user', {
'account': DataTypes.STRING(45),
'password': DataTypes.STRING(125),
'name': DataTypes.STRING(25),
'sex': DataTypes.INTEGER,
'coins': DataTypes.INTEGER,
'face': DataTypes.STRING(125),
'check_times': DataTypes.INTEGER,
'check_days': DataTypes.INTEGER,
})
}
|
import React from 'react';
import { BrowserRouter } from "react-router-dom";
// Testing-specific
import { shallow, mount, render } from 'enzyme';
const state = require('../state');
// Test subjects
import GridItem from '../../src/js/components/GridItem';
describe('<GridItem />', () => {
it('should handle album', () => {
var album = state.core.albums['jest:album:one'];
var dom = shallow(<GridItem item={album} />);
expect(dom.find('.grid__item__name').text()).toEqual('One');
expect(dom.find('.grid__item__secondary__content').length).toBe(1);
});
it('should handle artist', () => {
var artist = state.core.artists['jest:artist:alpha'];
var dom = shallow(<GridItem item={artist} />);
expect(dom.find('.grid__item__name').text()).toEqual('Alpha');
expect(dom.find('.grid__item__secondary__content').childAt(0).render().text()).toEqual('123 followers');
expect(dom.find('.grid__item__secondary__content').childAt(1).render().text()).toEqual('1 albums');
});
it('should handle playlist', () => {
var playlist = state.core.playlists['jest:playlist:one'];
var dom = shallow(<GridItem item={playlist} />);
expect(dom.find('.grid__item__name').text()).toEqual('One');
expect(dom.find('.grid__item__secondary__content').render().text()).toEqual('2 tracks');
});
}); |
const express=require('express')
const rotas=express.Router()
const bcrypt=require('bcryptjs')
const passport=require('passport')
//modulos
const User=require('../modulos/user')
//página de login
rotas.get('/login',(req,res)=>res.render('login'))
//página de registro
rotas.get('/registro',(req,res)=>res.render('registro'))
//registro
rotas.post('/registro',(req,res)=>{
const {name,email,password,password2}=req.body
//verificar campos obrigatorios
let erros=[]
if(!name||!email||!password||!password2){
erros.push({msg:'Por favor preencha os campos'})
}
// verificando senha
if(password!==password2){
erros.push({msg:'senha não confere'})
}
// verificando tamanho da senha
if(password.length<6){
erros.push({msg:'sua senha deve ter no minimo 6 caracteres'})
}
if(erros.length>0){
res.render('registro',{
erros,
name,
email,
password,
password2
})
}else{
//validado
User.findOne({email:email})
.then(user=>{
if(user){
//usuario existe
erros.push({msg:'email já está registrado'})
res.render('registro',{
erros,
name,
email,
password,
password2
})
}else{
const newUser=new User({
name,
email,
password
})
//hash criptografia
bcrypt.genSalt(10,(err,salt)=>
bcrypt.hash(newUser.password,salt,(err,hash)=>{
if(err)throw err
newUser.password=hash
// salvando usuario
newUser.save()
.then(user=>{
req.flash('success_msg','Registrado com sucesso')
res.redirect('/usuarios/login')
})
.catch(console.log(err))
}))
}
})
}
})
//login
rotas.post('/login',(req,res,next)=>{
passport.authenticate('local',{
successRedirect:'/dashboard',
failureRedirect:'/usuarios/login',
failureFlash:true
})(req,res,next)
})
//logout dashboard
rotas.get('/logout',(req,res)=>{
req.logout()
req.flash('success_msg','você não esta mais logado')
res.redirect('/usuarios/login')
})
module.exports =rotas |
'use strict';
const express = require('express');
const logger = require('../../logger')('weather');
const weather = require('../../utils/weather');
const moment = require('moment');
const momentz = require('moment-timezone');
module.exports = middlewares => {
const router = express.Router(); // eslint-disable-line new-cap
if (middlewares) {
middlewares.forEach(middleware => router.use(middleware));
}
const parseData = data => {
return data.rows.map(record => ({
id: record.doc._id,
rev: record.doc._rev,
}));
};
/**
* @swagger
*
* /weather:
* get:
* tags:
* - weather
* description: Get weather data
* produces:
* - application/json
* responses:
* 200:
* description: success
*/
router.get('/getWeather', (req, res) => {
console.log(
momentz(new Date())
.tz('Asia/Seoul')
.format('YYYY/MM/DD/HH/MM/DD')
);
weather
.dbquery('SELECT * FROM t_weather WHERE wth_t_target = ? ORDER BY wth_idx DESC', [
momentz(new Date())
.tz('Asia/Seoul')
.format('YYYY-MM-DD'),
])
.then(results => {
if (results.length > 0) {
res.send(results);
} else {
res.send('{"ERROR": "오늘 데이터가 존재하지 않음"}');
}
})
.catch(err => {
res.send('ERROR: ' + err.toString());
});
});
return router;
};
|
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
import env from '../../../env.json'
require('./LayoutGrid.css')
export default class LayoutGrid extends Component {
getChildElements = () => {
const { data } = this.props
return Object.values(data).map((element) => {
return (
element.poster_path ?
<div className="LayoutGrid-cell" key={element.id}>
<Link to={{ pathname: '/movie', search: `?id=${element.id}` }}>
<img
src={`${env.IMG_URL}/w185${element.poster_path}`}
alt="Movie"
width="182"
height="271"
/>
</Link>
</div> :
null
)
})
}
render() {
if (!this.props.data) return null
const { data } = this.props
return (
<div className="LayoutGrid">
{this.getChildElements()}
</div>
)
}
}
LayoutGrid.PropTypes = {
data: PropTypes.array.isRequired,
}
LayoutGrid.defaultProps = {
data: {}
}
|
import React from 'react';
import {View, Text, SafeAreaView, Image, FlatList} from 'react-native';
import styled from 'styled-components';
import {IMGBG} from '../Assets';
import Scanner from '../Components/ComplexComponents/Scanner/Scanner';
import ButtonCardEvent from '../Components/SimpleComponents/ButtonCardEvent/ButtonCardEvent';
import ButtonChoice from '../Components/SimpleComponents/ButtonChoice/ButtonChoice';
import Logo from '../Components/SimpleComponents/Logo/Logo';
import TextTitle from '../Components/SimpleComponents/TextTitle/TextTitle';
import {colors} from '../Utils/Colors/colors';
export default function Home({navigation}) {
return (
<SafeContainer>
<View style={{padding: 16}}>
<Image
source={IMGBG}
style={{position: 'absolute', top: 103, right: 0}}
/>
<Logo />
<View style={{height: 26}} />
<TextTitle text={'Where do you want to go?'} />
<View style={{height: 36}} />
<TextStandard>Categories</TextStandard>
<View style={{height: 26}} />
<WrapperButton>
<ButtonChoice
onPress={() => {
navigation.navigate('Scanner');
}}
type={`Scan`}
/>
<ButtonChoice type={`Event`} />
<ButtonChoice type={`Alam`} />
</WrapperButton>
<FlatList
data={[0, 1, 3, 4]}
renderItem={ButtonCardEvent}
numColumns={2}
style={{marginTop: 20}}
columnWrapperStyle={{
justifyContent: 'space-around',
}}
/>
</View>
</SafeContainer>
);
}
const SafeContainer = styled.SafeAreaView`
background-color: white;
flex: 1;
`;
const ContainerWrapper = styled.View`
display: flex;
background-color: black;
flex-direction: row;
justify-content: space-around;
`;
const WrapperButton = styled.View`
flex-direction: row;
justify-content: space-between;
`;
const TextStandard = styled.Text`
font-size: 18px;
font-weight: 600;
`;
|
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var cssnano = require('gulp-cssnano');
var webConfig = require('./config/webConfig');
var mainConfig = webConfig.mainConfig();
var build = mainConfig.revision;
gulp.task('css', function() {
return gulp.src('public/css/compiled/*.css')
.pipe(concat('site-simple-bike-' + build + '.min.css'))
.pipe(cssnano())
.pipe(gulp.dest('public/css/compiled/'));
});
gulp.task('css-blog', function() {
return gulp.src('public/css/compiled/*.css')
.pipe(concat('site-simple-bike-blog.min.css'))
.pipe(cssnano())
.pipe(gulp.dest('public/css/compiled/'));
});
gulp.task('js', function () {
gulp.src([
'public/js/controller/*.js'
, 'public/js/services/*.js'
])
.pipe(concat('simple-bike-production-' + build + '.min.js'))
.pipe(uglify())
.pipe(gulp.dest('public/js/compiled/'))
});
var watcher = gulp.watch(
[
'public/js/controller/*.js'
, 'public/js/services/*.js'
], ['js']);
watcher.on('change', function(event) {
console.log(event);
});
gulp.task('default', ['js', 'css', 'css-blog']); |
import React, { useEffect, Fragment } from 'react';
import Contact from './Contact';
import Spinner from '../layout/Spinner';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { getContacts } from '../../actions/contactActions';
const Contacts = ({ getContacts, contacts: { contacts, loading } }) => {
useEffect(() => getContacts(), []);
return (
<Fragment>
<h1 className="display-4 mb-3">
<span className="text-primary">Contacts</span> List
</h1>
{loading ? (
<Spinner />
) : !loading && !contacts.length ? (
<Fragment>
<h1 className="display-4">You dont have any contacts ..</h1>
<Link to="/contact/add" className="btn btn-dark">
Add now
</Link>
</Fragment>
) : (
contacts.map(contact => <Contact contact={contact} key={contact.id} />)
)}
</Fragment>
);
};
const mapStateToProps = state => ({
contacts: state.contact
});
export default connect(
mapStateToProps,
{ getContacts }
)(Contacts);
|
const URLModel = require('./../models/url');
var afterLoad = require('after-load');
const request = require('request');
const {
statusCode,
returnErrorJsonResponse,
returnJsonResponse,
} = require("../Helpers/status.js");
exports.addURL = async (req,res) =>{
try {
const uri = req.body.url;
request({uri: uri}, async (error, response, body) =>{
if(error){
return res.render("pageNotFound");
}
const addURL = await URLModel.create({
url: req.body.url,
url_content: body
});
return res.render('content',{
post:{
content: body
}
});
})
//return res.redirect('/showURL')
} catch (error) {
return res
.status(statusCode.bad)
.render('404')
}
}
exports.showURL = async (req,res) => {
try {
const result = await URLModel.find({});
const showURL = [];
for(i=0; i< result.length; i++){
showURL[i] = {
id: result[i]._id,
URL: result[i].url,
URL_content: result[i].url_content
}
}
return res
.status(statusCode.success)
.json(
returnJsonResponse(
statusCode.success,
"success",
"Employee on Leave",
showURL
)
);
} catch (error) {
return res
.status(statusCode.bad)
.render('404')
}
}
exports.showContent = async (req,res) =>{
try {
const id = req.params.id
const result = await URLModel.findById(id);
request({uri: result.url}, async (error, response, body) =>{
if(error){
return res.render("pageNotFound");
}
return res.render('content',{
post:{
content: body
}
});
})
} catch (error) {
res.status(statusCode.bad).render('404')
}
} |
/**
* @param argv
* argv.mode: {
alias: 'm',
default: 'all',
type: 'string',
desc: 'Docs Generation Mode',
group: 'Docs Generation Options:',
choices: ['api', 'styles', 'all']
},
argv.type: {
alias: 't',
default: 'all',
type: 'string',
desc: 'Type of Project',
group: 'Docs Generation Options:',
choices: ['apps', 'libs', 'all']
},
argv.coverageTest: {
alias: c,
type: 'boolean',
desc: 'Test for docs coverage',
group: 'Docs Generation Options:'
}
*/
module.exports = (argv) => {
const shell = require('shelljs');
const chalk = require('chalk');
const cliConfigs = require('../../configs').angularx;
const _ = require('lodash');
const angularConfigs = require('../../configs').angular;
const fs = require('fs-extra');
let projects = [];
if (argv.type === 'all') {
projects = _.map(_.concat(cliConfigs.apps, cliConfigs.libs), 'name');
}
else if (argv.type === 'apps') {
projects = _.map(cliConfigs.apps, 'name')
}
else {
projects = _.map(cliConfigs.libs, 'name')
}
console.log(projects);
projects.forEach(appName => {
const appConfig = angularConfigs.projects[appName];
const apiOutputPath = (appConfig.projectType === 'application') ? appConfig.architect.build.options.outputPath + '/docs/api-docs'
: _.find(cliConfigs.libs, ['name', appName]).outputPath + '/docs/api-docs';
const stylesOutputPath = (appConfig.projectType === 'application') ? appConfig.architect.build.options.outputPath + '/docs/styles-docs'
: _.find(cliConfigs.libs, ['name', appName]).outputPath + '/docs/styles-docs';
if (argv.mode === 'api' || argv.mode === 'all') {
if (!argv.coverageTest) {
console.log(chalk.yellow('[INFO: AngularX CLI] Generating API Docs - ' + appName));
fs.ensureDir(apiOutputPath);
fs.emptyDir(apiOutputPath);
}
const tsconfigPath = (appConfig.projectType === 'application') ? appConfig.root + '/tsconfig.app.json' : appConfig.root + '/tsconfig.lib.json';
const commandToExecute = (argv.coverageTest) ? './node_modules/.bin/compodoc --coverageTest -p ' + tsconfigPath
: './node_modules/.bin/compodoc -p ' + tsconfigPath + ' -d ' + apiOutputPath;
shell.exec(commandToExecute);
}
if (argv.mode === 'styles' || argv.mode === 'all') {
if (!argv.coverageTest) {
console.log(chalk.yellow('[INFO: AngularX CLI] Generating Styles Docs - ' + appName));
fs.ensureDir(stylesOutputPath);
fs.emptyDir(stylesOutputPath);
}
}
});
};
|
'use strict'
/**
* Dependencies
* @ignore
*/
const base64url = require('base64url')
const crypto = require('@trust/webcrypto')
const TextEncoder = require('../text-encoder')
/**
* AES-GCM
*/
class AES_GCM {
/**
* constructor
*
* @param {string} bitlength
*/
constructor (params) {
this.params = params
}
/**
* encrypt
*
* @description
* Encrypt data and associated additional authentication data using AES-GCM.
*
* @param {CryptoKey} key
* @param {(BufferSource|String)} data
* @param {(BufferSource|String)} aad
*
* @returns {Promise}
*/
encrypt (key, data, aad) {
let algorithm = Object.assign({}, this.params)
// ensure each encryption has a new iv
Object.defineProperty(algorithm, 'iv', {
enumerable: false,
configurable: true,
value: crypto.getRandomValues(new Uint8Array(16))
})
Object.defineProperty(algorithm, 'additionalData', {
enumerable: false,
configurable: true,
value: typeof aad === 'string' ? new TextEncoder().encode(aad) : aad
})
// Normalize data input
if (typeof data === 'string') {
data = new TextEncoder().encode(data)
}
return crypto.subtle
.encrypt(algorithm, key, data)
.then(result => {
// split the result into ciphertext and tag
let tagLength = (algorithm.tagLength / 8) || 16
let tag = result.slice(result.byteLength - tagLength)
let ciphertext = result.slice(0, -tagLength)
return Object.assign({
iv: base64url(Buffer.from(algorithm.iv)),
ciphertext: base64url(Buffer.from(ciphertext)),
tag: base64url(Buffer.from(tag))
},
algorithm.additionalData && algorithm.additionalData.length > 0
? { aad: base64url(Buffer.from(algorithm.additionalData)) }
: {}
)
})
}
/**
* decrypt
*
* @description
* Decrypt the given data (authenticated with the aad) encrypted with iv,
* checking for integrity using the tag provided.
*
* @param {CryptoKey} key
* @param {(BufferSource|String)} ciphertext - Base64URL encoded cipher text.
* @param {(BufferSource|String)} iv - Base64URL encoded intialization vector.
* @param {(BufferSource|String)} tag - Base64URL encoded authentication tag.
* @param {(BufferSource|String)} [aad] - Base64URL encoded additional authenticated data.
*
* @return {Promise}
*/
decrypt (key, ciphertext, iv, tag, aad) {
let algorithm = this.params
// Normalize iv input
if (typeof iv === 'string') {
iv = Uint8Array.from(base64url.toBuffer(iv))
} else {
iv = Uint8Array.from(iv)
}
// Assign non-enumerable iv
Object.defineProperty(algorithm, 'iv', {
enumerable: false,
configurable: true,
value: iv
})
// Normalize aad if present
if (aad) {
if (typeof aad === 'string') {
aad = Uint8Array.from(base64url.toBuffer(aad))
} else {
aad = Uint8Array.from(aad)
}
}
// Assign non-enumerable aad only if used
Object.defineProperty(algorithm, 'additionalData', {
enumerable: false,
configurable: true,
value: aad ? aad : undefined
})
// Decode ciphertext and tag from base64
// String input
if (typeof ciphertext === 'string') {
ciphertext = base64url.toBuffer(ciphertext)
}
// String input
if (typeof tag === 'string') {
tag = base64url.toBuffer(tag)
}
// Concatenate the two buffers
let data = new Uint8Array(ciphertext.length + tag.length)
data.set(new Uint8Array(ciphertext), 0)
data.set(new Uint8Array(tag), ciphertext.length)
data = data.buffer
return crypto.subtle
.decrypt(algorithm, key, data)
.then(plaintext => Buffer.from(plaintext).toString())
}
/**
* encryptKey
*
* @description
* Wrap key using AES-GCM.
*
* @param {CryptoKey} key
* @param {CryptoKey} wrappingKey
*
* @returns {Promise}
*/
encryptKey (key, wrappingKey) {
let algorithm = this.params
return Promise.resolve()
// return crypto.subtle
// .wrapKey('jwk', key, wrappingKey, algorithm)
}
/**
* decryptKey
*
* @description
* Unwrap key using AES-GCM.
*
* @param {string|Buffer} wrappedKey
* @param {CryptoKey} unwrappingKey
* @param {string} unwrappedKeyAlg
*
* @returns {Promise}
*/
decryptKey (wrappedKey, unwrappingKey, unwrappedKeyAlg) {
let algorithm = this.params
return Promise.resolve()
// return crypto.subtle
// .unwrapKey('jwk', wrappedKey, unwrappingKey, algorithm, unwrappedKeyAlgorithm, true, keyUsages)
}
/**
* Generate Key
*
* @description
* Generate key for AES-GCM.
*
* @param {boolean} extractable
* @param {Array} key_ops
* @param {Object} options
*
* @return {Promise}
*/
generateKey (extractable, key_ops, options = {}) {
let algorithm = this.params
return crypto.subtle
.generateKey(algorithm, extractable, key_ops)
}
/**
* Import
*
* @description
* Import a key in JWK format.
*
* @param {CryptoKey} key
*
* @return {Promise}
*/
importKey (key) {
let jwk = Object.assign({}, key)
let algorithm = this.params
let usages = key['key_ops'] || ['encrypt', 'decrypt']
return crypto.subtle
.importKey('jwk', jwk, algorithm, true, usages)
.then(cryptoKey => {
Object.defineProperty(jwk, 'cryptoKey', {
enumerable: false,
value: cryptoKey
})
return jwk
})
}
}
/**
* Export
*/
module.exports = AES_GCM
|
const express = require("express");
const router = express.Router();
const { Genre, validate } = require("../models/genres");
const auth = require("../middlewares/auth");
const admin = require("../middlewares/admin");
router.get("/", async (req, res) => {
const genres = await Genre.find();
res.json(genres);
});
router.get("/:id", async (req, res) => {
const genre = await Genre.findById(req.params.id);
if (!genre) {
res.send("ERROR");
} else {
res.send(genre);
}
});
router.post("/", auth, async (req, res) => {
if (validate(req.body)) return res.status(400).send("THERE IS ERROR");
let genre = new Genre({
name: req.body.name
});
genre = await genre.save();
res.send(genre);
});
router.put("/:id", [auth, admin], async (req, res) => {
validate(req.body);
let genre = await Genre.findByIdAndUpdate(
req.params.id,
{
name: req.body.name
},
{ new: true }
);
if (!genre) {
return res.status(404).send("Resourse is not founded");
}
genre = await genre.save();
res.send(genre);
});
router.delete("/:id", async (req, res) => {
validate(req.body);
let genre = await Genre.findById(req.params.id);
if (!genre) {
return res.status(404).send("Resourse is not founded");
}
await genre.delete();
res.send(genre);
});
module.exports = router;
|
import React, { Component } from 'react'
import styled from 'styled-components';
import PageTitle from '../components/PageTitle';
const Page = styled.div`
padding: 200px 0 0 0;
`
export default class AlbumsPage extends Component {
render() {
return (
<Page>
<PageTitle>Albums</PageTitle>
</Page>
)
}
}
|
import UsersService from './services/usersService';
import AlbumsService from './services/albumsService';
import FailService from './services/failService';
import Home from './components/Home';
import User from './components/User';
import Albums from './components/Albums';
import Fail from './components/Fail';
export const home = {
name: 'home',
url: '/',
component: Home
}
export const user = {
name: 'user',
url: '/user',
component: User,
resolve: [{
token: 'user',
resolveFn: () => UsersService.getUser()
}]
}
export const albums = {
name: 'albums',
url: '/albums',
component: Albums,
resolve: [{
token: 'albums',
resolveFn: () => AlbumsService.getAllAlbums()
}]
}
export const fail = {
name: 'fail',
url: '/fail',
component: Fail,
resolve: [{
token: 'fail',
resolveFn: () => FailService.getSomething()
}]
}
|
module.exports = {
extends: [
'react-app',
'plugin:jsx-a11y/recommended',
'prettier',
'prettier/react',
],
plugins: ['jsx-a11y', 'prettier', 'react-hooks'],
rules: {
'default-case': 'off',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'import/no-anonymous-default-export': 'off',
},
};
|
import React from 'react'
import './Advertisement.css'
const url = "https://www.howtogeek.com/wp-content/uploads/2019/06/slack_logo.png?width=1198&trim=1,1&bg-color=000&pad=1,1";
function Advertisement() {
return (
<div className="advertisement-container">
<p className="advertisement-paragraph">advertisement</p>
{/* <img className="advertisement-image" src={url} alt="" /> */}
</div>
)
}
export default Advertisement
|
import React, { Fragment, useEffect, useRef, useState } from 'react';
import {
Popover,
OverlayTrigger,
Dropdown,
DropdownButton,
Button,
} from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faCheck,
faList,
faPlus,
faTimes,
} from '@fortawesome/free-solid-svg-icons';
import { connect } from 'react-redux';
import { addContentToList } from '../../actions/profile';
const ListPopover = ({
item,
itemType,
open,
close,
addToWatchlist,
watchlist,
customLists,
addContentToList,
}) => {
const [watchlistContent, updateWatchlist] = useState([]);
const [show, setShow] = useState(false);
const target = useRef(null);
const [selectedList, updateSelectedList] = useState(null);
useEffect(() => {
if (itemType === 'movie') {
updateWatchlist(watchlist.movie);
} else {
updateWatchlist(watchlist.tv);
}
close(item.id);
}, [watchlist]);
useEffect(() => {
if (customLists.length > 0) {
updateSelectedList(customLists[0]);
}
}, [customLists]);
const changeCustomList = (item) => {
updateSelectedList(item);
};
return (
<Fragment>
<OverlayTrigger
trigger="click"
target={target.current}
key={`overylay_${item.id}_${itemType}`}
placement="bottom"
onExit={() => {
console.log('popover close');
close(item.id);
}}
onEnter={() => {
console.log('popover open');
open(item.id);
}}
flip
overlay={
<Popover id={`popover-positioned-${item.id}-${itemType}`}>
<Popover.Title className="d-flex flex-row align-items-center justify-content-between pr-3">
<span>Add to Lists</span>
<span>
<FontAwesomeIcon icon={faPlus} />
</span>
</Popover.Title>
<Popover.Content className="d-flex flex-row py-1 align-items-center">
<span style={{ fontSize: '1.2em' }}>Watchlist</span>
<Button
variant={
watchlistContent.includes(item.id) ? 'danger' : 'success'
}
size="sm"
className="ml-auto"
onClick={() =>
addToWatchlist(
watchlist.listId,
item,
watchlistContent.includes(item.id) ? 'remove' : 'add'
)
}
>
<FontAwesomeIcon
icon={watchlistContent.includes(item.id) ? faTimes : faCheck}
/>
</Button>
</Popover.Content>
<hr className="my-1" />
<Popover.Content className="d-flex flex-row py-1 pb-2">
{customLists.length !== 0 && selectedList && (
<DropdownButton
// style={{ width: '85%' }}
size="sm"
className="mr-3 px-0 w-auto"
id="dropdown-basic-button"
title={selectedList.name}
>
{/* <Dropdown.Item href="#/action-1">Action</Dropdown.Item>
<Dropdown.Item href="#/action-2">
Another action
</Dropdown.Item>
<Dropdown.Item href="#/action-3">
Something else
</Dropdown.Item> */}
{customLists.map((list, index) => {
return (
<Dropdown.Item
value={list.name}
key={`list_dropdown_${list.id}`}
onClick={() => changeCustomList(list)}
>
{list.name}
</Dropdown.Item>
);
})}
</DropdownButton>
)}
{customLists.length === 0 && <span>No Custom Lists</span>}
<Button
size="sm"
className="ml-auto"
disabled={customLists.length === 0}
onClick={() =>
addContentToList(
selectedList.listId,
selectedList.type,
itemType,
item
)
}
>
<FontAwesomeIcon icon={faPlus} />
</Button>
</Popover.Content>
</Popover>
}
rootClose
>
<div
className={`align-items-center ${
watchlistContent.includes(item.id) && 'list-icon'
}`}
>
<FontAwesomeIcon
ref={target}
icon={faList}
className="content-options"
onClick={() => {
console.log('IN');
setShow(!show);
}}
/>
</div>
</OverlayTrigger>
</Fragment>
);
};
const mapStateToProps = (state) => ({
watchlist: state.profile.watchlist,
customLists: state.profile.customLists,
});
export default connect(mapStateToProps, { addContentToList })(ListPopover);
|
var widgetHtml = '<iframe src="https://www.prepostseo.com/widget/wordcount" style="border:0;width:100%;min-height:1000px;height:100%;"></iframe>';
var widgetTag = document.getElementById("ppsLink");
if (widgetTag === null){
<<<<<<< HEAD
widgetHtml += '<div style="text-align: center; font-size:12px; color:#333;"><p>Word Counter provided by <a href="https://www.prepostseo.com/word-count-character-count-tool" target="_blank" style="color:#000;">prepostseo.com</a></p></div>';
=======
widgetHtml += '<div style="text-align: center; font-size:12px; color:#333;"><p>Word Counter provided by <a id="ppsLink" href="https://www.prepostseo.com/word-count-character-count-tool" target="_blank" style="color:#000;">prepostseo.com</a></p></div>';
>>>>>>> 9e5ae2cfb8f4a105aecb1e95e58070d7bec88f16
} else {
var linkUrl = widgetTag.getAttribute("href");
if(linkUrl !== 'https://www.prepostseo.com/word-count-character-count-tool'){
<<<<<<< HEAD
widgetHtml += '<div style="text-align: center; font-size:12px; color:#333;"><p>Word Counter provided by <a href="https://www.prepostseo.com/word-count-character-count-tool" target="_blank" style="color:#000;">prepostseo.com</a></p></div>';
=======
widgetHtml += '<div style="text-align: center; font-size:12px; color:#333;"><p>Word Counter provided by <a id="ppsLink" href="https://www.prepostseo.com/word-count-character-count-tool" target="_blank" style="color:#000;">prepostseo.com</a></p></div>';
>>>>>>> 9e5ae2cfb8f4a105aecb1e95e58070d7bec88f16
}
}
var isNew = document.getElementById("ppsWidgetCode");
document.getElementById("ppsWidgetCode").innerHTML = widgetHtml;
|
//Dependencies
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
//Models
var Contract = require(__dirname + '/../models/contracts');
router.get('/', (req, res)=>{
});
router.post('/saveContract', (req, res)=>{
var contract = new Contract(req.body.data)
contract.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('Saved Contract');
}
});
});
module.exports = router; |
console.bog = function() {
var bog = '💩';
var args = [bog];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
};
args.push(bog);
console.log.apply(this, args);
}; |
const fs = require('fs');
const data = JSON.parse(fs.readFileSync(__dirname + '/../json-rpc.json'));
const tpMap = {};
tpMap['AccountNumber'] = 'AccountNumber|Number|String';
tpMap['AccountNumberArray'] = 'AccountNumber[]|Number[]|String[]';
tpMap['StringArray'] = 'String[]';
tpMap['AccountName'] = 'AccountName|String';
tpMap['PublicKey'] = 'String|BC|PublicKey|WalletPublicKey|PrivateKey|KeyPair';
tpMap['Block'] = 'Number';
tpMap['ChangerArray'] = 'Object[]|Changer[]';
tpMap['SenderArray'] = 'Object[]|Sender[]';
tpMap['ReceiverArray'] = 'Object[]|Receiver[]';
function cap(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var ccUS = function (str) {
return str.split(/(?=[A-Z])/).join('_').toLowerCase();
};
var usCC = (function () {
var DEFAULT_REGEX = /[-_]+(.)?/g;
function toUpper(match, group1) {
return group1 ? group1.toUpperCase() : '';
}
return function (str, delimiters) {
return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
};
})();
const NL = '\n';
let gen = '';
Object.keys(data.methods).forEach((m) => {
const md = data.methods[m];
gen += ` /**${NL} * ${md.description}${NL} *${NL}`;
Object.keys(md.params).forEach((p, i) => {
const pd = md.params[p];
gen += ' * @param {';
if (tpMap[pd.type] !== undefined) {
gen += tpMap[pd.type];
} else {
gen += pd.type;
}
if (!pd.required) {
gen += '|null';
}
if (pd.description !== undefined) {
gen += `} ${usCC(pd.name)} - ` + pd.description + NL;
} else {
gen += `} ${usCC(pd.name)}` + NL;
}
});
if (Object.keys(md.params).length > 0) {
gen += ` *${NL}`;
}
gen += ` * @returns {${md.action}}${NL} */${NL}`;
gen += ` ${md.camel}(`;
if (Object.keys(md.params).length > 0) {
gen += '{';
gen += NL;
}
Object.keys(md.params).forEach((p, i) => {
const pd = md.params[p];
gen += ` ${usCC(pd.name)}`;
if (!pd.required) {
gen += ' = null';
}
if (i < Object.keys(md.params).length - 1) {
gen += ', ';
}
gen += NL;
});
if (Object.keys(md.params).length > 0) {
gen += ' }';
}
gen += ') {' + NL;
gen += ` return new ${md.action}('${m}', {`;
if (Object.keys(md.params).length > 0) {
gen += NL;
}
Object.keys(md.params).forEach((p, i) => {
const pd = md.params[p];
switch (pd.type) {
case 'AccountName':
if (pd.required) {
gen += ` ${pd.name}: new AccountName(${usCC(pd.name)})`;
} else {
gen += ` ${pd.name}: ${usCC(pd.name)} !== null ? new AccountName(${usCC(pd.name)}) : ${usCC(pd.name)}`;
}
break;
case 'StringArray':
if (pd.implode !== undefined) {
gen += ` ${pd.name}: ${usCC(pd.name)}.join('${pd.implode}')`;
} else {
if (pd.name !== usCC(pd.name)) {
gen += ` ${pd.name}: ${usCC(pd.name)}`;
} else {
gen += ` ${usCC(pd.name)}`;
}
}
break;
case 'AccountNumber':
if (pd.required) {
gen += ` ${pd.name}: new AccountNumber(${usCC(pd.name)})`;
} else {
gen += ` ${pd.name}: ${usCC(pd.name)} !== null ? new AccountNumber(${usCC(pd.name)}) : ${usCC(pd.name)}`;
}
break;
case 'AccountNumberArray':
gen += ` ${pd.name}: ${usCC(pd.name)}.map((acc) => new AccountNumber(acc))`;
break;
case 'ChangerArray':
gen += ` ${pd.name}: ${usCC(pd.name)}.map((chng) => new Changer(chng))`;
break;
case 'ReceiverArray':
gen += ` ${pd.name}: ${usCC(pd.name)}.map((rec) => new Receiver(rec))`;
break;
case 'SenderArray':
gen += ` ${pd.name}: ${usCC(pd.name)}.map((sen) => new Sender(sen))`;
break;
case 'Number':
case 'Block':
gen += ` ${pd.name}: ${usCC(pd.name)} !== null ? parseInt(${usCC(pd.name)}, 10) : ${usCC(pd.name)}`;
break;
case 'Currency':
if (pd.required) {
gen += ` ${pd.name}: new Currency(${usCC(pd.name)})`;
} else {
gen += ` ${pd.name}: ${usCC(pd.name)} !== null ? new Currency(${usCC(pd.name)}) : ${usCC(pd.name)}`;
}
break;
default:
if (pd.name !== usCC(pd.name)) {
gen += ` ${pd.name}: ${usCC(pd.name)}`;
} else {
gen += ` ${usCC(pd.name)}`;
}
break;
}
if (i < Object.keys(md.params).length - 1) {
gen += ', ' + NL;
}
});
if (Object.keys(md.params).length > 0) {
gen += NL;
gen += ' }, this[P_EXECUTOR], ';
} else {
gen += '}, this[P_EXECUTOR], ';
}
gen += md.return_type + ', ' + md.return_array + ');' + NL;
gen += ' }';
gen += NL + NL;
});
let tpl = fs.readFileSync(__dirname + '/Client.js.tpl');
tpl = tpl.toString().replace('__CONTENT__', gen);
fs.writeFileSync(__dirname + '/../src/Client.js', tpl);
|
const myasciidoctor = require('./src/utils/asciidoc_converter');
const path = require(`path`);
const {createFilePath} = require(`gatsby-source-filesystem`);
// const asciidoctor = require(`asciidoctor`)();
// class ReactAsciidocConverter {
// constructor() {
// this.baseConverter = asciidoctor.Html5Converter.$new();
// }
//
// convert(node, transform) {
// let content = '', text = '', res = '';
// switch (node.getNodeName()) {
//
// // case "section":
// // content = node.getContent();
// // res = `<section>${content}</section>`;
// // break;
//
// // case "paragraph":
// // res = `<p>${node.content}</p>`;
// // break;
//
// // corresponds to display math
// // essentially a asciidoc block
// // generate a virtual DOM according to
// // https://github.com/MatejBransky/react-katex
// case 'stem':
// case 'latexmath':
// // content = node.getContent();
// // res = katex.renderToString(content, {
// // throwOnError: false,
// // displayMode: true,
// // });
// // defer to the react-katex
// // using <div>, <span> with class "math" is jsMath notation
// // need to use MathJax options
// res = `<div class='math'>${node.getContent()}</div>`;
// break;
//
//
// // asciidoctor treats inline math as inline_quoted node.
// // node.getContent() does not seem to work
// // search $convert_inline_quoted in asciidoctor.js
// case 'inline_quoted':
// if (node.type === 'latexmath' || node.type === 'stem') {
// // text = node.text;
// // res = katex.renderToString( text, {
// // throwOnError: false,
// // displayMode: false,
// // });
// res = `<span class='math'>${node.text}</span>`;
// break;
// }
//
// // default is the vanilla html5 converter
// default:
// res = this.baseConverter.convert(node, transform);
// }
// return res;
// }
// }
//
// asciidoctor.ConverterFactory.register(new ReactAsciidocConverter(), ['html5']);
exports.createPages = ({graphql, actions}) => {
const {createPage} = actions;
const blogPost = path.resolve(`./src/templates/blog-post.js`);
return graphql(
`
{
allAsciidoc(
sort: { fields: document___datetime, order: DESC }
limit: 1000
) {
edges {
node {
fields {
slug
}
document {
title
}
}
}
}
}
`,
).then(result => {
if (result.errors) {
throw result.errors;
}
// Create blog posts pages.
const posts = result.data.allAsciidoc.edges;
posts.forEach((post, index) => {
const previous = index === posts.length - 1 ?
null :
posts[index + 1].node;
const next = index === 0 ? null : posts[index - 1].node;
createPage({
path: post.node.fields.slug,
component: blogPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
});
});
return null;
});
};
const onCreateNode = (arg1) => {
let {node, actions, getNode} = arg1;
// modify the node that is a an asciidocpost, add a node field 'slug'
if (node.internal.type === `File` &&
[`adoc`, `asciidoc`].includes(node.extension)) {
return createAsciidocNode(arg1);
}
if (node.internal.type === `Asciidoc`) {
const value = createFilePath({node, getNode});
actions.createNodeField({
name: `slug`,
node,
value,
});
}
};
async function createAsciidocNode({
node,
actions,
pathPrefix,
loadNodeContent,
createNodeId,
reporter,
createContentDigest,
}) {
const createNode = actions.createNode,
createParentChildLink = actions.createParentChildLink;
const content = await loadNodeContent(node); // yield
const asciidocOptions = {};
let doc = await myasciidoctor.load(content, asciidocOptions); // doc may be modified, yield
try {
const html = doc.convert();
// attributes are not completely parsed until after convert
let docAttributes = doc.getAttributes();
if (!docAttributes.hasOwnProperty('publish')) {
return;
}
let pageAttributes = extractPageAttributes(docAttributes);
// Use "partition" option to be able to get title, subtitle, combined
const title = doc.getDocumentTitle({
partition: true,
});
let revision = doc.getRevisionInfo();
let authors = doc.getAuthors();
let tags = docAttributes.tags;
if (tags) {
tags = tags.split(',');
tags = tags.map((t) => t.trim());
} else {
tags = ['misc'];
}
let tldr = docAttributes.tldr;
if (!tldr) {
tldr = '';
}
const asciiNode = {
id: createNodeId(`${node.id} >>> ASCIIDOC`),
parent: node.id,
internal: {
type: `Asciidoc`,
mediaType: `text/html`,
contentDigest: null,
},
children: [],
html,
document: {
title: title.getCombined(),
authors: authors ? authors.map(x => x.getName()) : [],
date: docAttributes.docdate,
datetime: docAttributes.docdatetime,
excerpt: tldr,
tags: tags,
primary_tag: tags[0],
},
title,
revision,
authors,
docAttributes,
pageAttributes,
};
asciiNode.internal.contentDigest = createContentDigest(asciiNode);
createNode(asciiNode);
createParentChildLink({
parent: node,
child: asciiNode,
});
} catch (err) {
reporter.panicOnBuild(`Error processing Asciidoc ${node.absolutePath ?
`file ${node.absolutePath}` :
`in node ${node.id}`}:\n
${err.message}`);
}
}
const extractPageAttributes = allAttributes => Object.entries(allAttributes).
reduce((pageAttributes, [key, value]) => {
if (key.startsWith(`page-`)) {
pageAttributes[key.replace(/^page-/, ``)] = value;
}
return pageAttributes;
}, {});
exports.onCreateNode = onCreateNode; |
var mongoose = require("mongoose");
var FacultySchema = new mongoose.Schema({
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
first_name: { type: String, default: ''},
middle_name: { type: String, default: ''},
last_name: { type: String, default: ''},
email: { type: String, default: ''},
gender: { type: String, default: ''},
date_of_joining: { type: String, default: ''},
date_of_birth: { type: String, default: ''},
school: { type: String, default: ''},
address: { type: String, default: ''},
phone: { type: String, default: ''},
research_summary: { type: String, default: ''},
current_projects: { type: String, default: ''},
department: { type: String, default: ''},
education: { type: String, default: ''},
experience: { type: String, default: ''},
image: { type: String, default: 'https://curve-public-bucket.s3.us-east-2.amazonaws.com/default_profile.png'},
interests: [String],
available: { type: Boolean, default: true},
opportunity:{
type: mongoose.Schema.Types.ObjectId,
ref: "Opportunity"
},
candidates: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Student"
}
]
});
module.exports = mongoose.model("Faculty", FacultySchema); |
import api from '@/utils/api'
const state = {
// Initial state of your store
foods: [],
currentQuestionIndex: -1,
showAnswer: false,
};
const getters = {
// Getters to access your store values
currentQuestion: (state) => {
if (state.currentQuestionIndex < state.foods.length) {
return state.foods[state.currentQuestionIndex]
} else {
return {}
}
},
gameFinished: (state) => {
return state.currentQuestionIndex >= state.foods.length
},
};
const actions = {
saveFoods({commit, state}) {
api.saveFoods(state.foods)
.then(r => {
console.log('response from updateFood')
console.log(r)
})
},
getFoods({commit}) {
console.log('dispatching getFoods action')
api.getFoods()
.then(r => {
console.log('response from getFoods')
console.log(r)
commit('UPDATE_FOOD_PROP', {key: 'foods', value: r.data})
})
},
resetGame({commit}) {
commit('UPDATE_FOOD_PROP', {key: "currentQuestionIndex", value: 0})
},
}
const mutations = {
// Synchronous modifications of your store
UPDATE_FOOD_PROP(state, {key, value}) {
state[key] = value
},
UPDATE_ANSWER(state, {id, answer}) {
const foods = state.foods.map(ele => {
if (ele.id === id) {
ele.answer = answer
}
return ele
})
state.foods = foods
console.log(state)
},
REVEAL_ANSWER(state) {
state.showAnswer = true;
},
UPDATE_QUESTION_INDEX(state, {newIndex}) {
state.showAnswer = false;
state.currentQuestionIndex = newIndex
}
}
export default {
state,
getters,
actions,
mutations
}
|
Ext.Loader.setConfig({ enabled: true });
Ext.Loader.setPath('Ext.ux', '/Scripts/Ext4.0/ux');
Ext.require([
'Ext.form.Panel',
'Ext.ux.form.MultiSelect',
'Ext.ux.form.ItemSelector'
]);
var pageSize = 25;
//創建類型store
//var createTypeStore = Ext.create('Ext.data.Store', {
// fields: ['txt', 'value'],
// data: [
// { "txt": '前臺', "value": "1" },
// { "txt": '後臺', "value": "2" }
// ]
//});
////管理員store
//var ManageUserStore = Ext.create('Ext.data.Store', {
// // fields: ['ParameterCode', 'parameterName'],
// model: 'gigade.paraModel',
// autoLoad: true,
// proxy: {
// type: 'ajax',
// url: '/Parameter/QueryPara?paraType=product_mode',
// noCache: false,
// getMethod: function () { return 'get'; },
// actionMethods: 'post',
// reader: {
// type: 'json',
// root: 'items'
// }
// }
//});
//期望到貨日調整記錄查詢Model
Ext.define('GIGADE.IpoNvdLog', {
extend: 'Ext.data.Model',
fields: [
{ name: 'row_id', type: 'string' },//流水號(自增)
{ name: 'work_id', type: 'string' },//工作編號
{ name: 'ipo_id', type: 'string' },//採購單單號
{ name: 'item_id', type: 'string' },//商品細項編號
//{ name: 'upc_id', type: 'string' },//商品條碼
{ name: 'loc_id', type: 'string' },//商品主料位
{ name: 'add_qty', type: 'string' },//收貨上架數量
{ name: 'made_date', type: 'string' },//收貨上架的製造日期
{ name: 'pwy_dte_ctl', type: 'string' },//是否效期控管
{ name: 'cde_date', type: 'string' },//保存期限
{ name: 'create_user_string', type: 'string' },//創建人
{ name: 'create_datetime', type: 'string' },//創建時間 pwy_dte_ctl
]
});
//獲取grid中的數據
var IpoNvdLogStore = Ext.create('Ext.data.Store', {
pageSize: pageSize,
model: 'GIGADE.IpoNvdLog',
proxy: {
type: 'ajax',
url: '/ReceiptShelves/GetIpoNvdLogList',
actionMethods: 'post',
reader: {
type: 'json',
totalProperty: 'totalCount',
root: 'data'
}
}
});
//加載前
IpoNvdLogStore.on('beforeload', function () {
Ext.apply(IpoNvdLogStore.proxy.extraParams, {
work_id: Ext.htmlEncode(Ext.getCmp('work_id').getValue().trim()),//工作單號
ipo_id: Ext.getCmp('ipo_id').getValue().trim(),//採購單單號
itemId_or_upcId: Ext.getCmp('itemId_or_upcId').getValue().trim(),//商品細項編號、條碼
loc_id: Ext.getCmp('loc_id').getValue().trim(),//商品主料位
time_start: Ext.getCmp('time_start').getValue(),//log創建日期,開始時間
time_end: Ext.getCmp('time_end').getValue()//結束時間
})
});
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
//Ext.getCmp("DeliveryChangeLogGrid").down('#edit').setDisabled(selections.length == 0);
}
}
});
Ext.onReady(function () {
var frm = Ext.create('Ext.form.Panel', {
id: 'frm',
layout: 'anchor',
height: 130,
//flex:1.5,
border: 0,
bodyPadding: 10,
width: document.documentElement.clientWidth,
items: [
{
xtype: 'fieldcontainer',
combineErrors: true,
layout: 'hbox',
items: [
{
xtype: 'textfield',
fieldLabel: '工作編號',
labelWidth: 70,
id: 'work_id',
name: 'work_id',
margin: '0 5 0 0',
//regex: /^[0-9]*$/,
//regexText: '請輸入0-9數字類型的字符',
submitValue: true,
listeners: {
specialkey: function (field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Query();
}
}
}
},
{
xtype: 'textfield',
fieldLabel: '採購單單號',
labelWidth: 85,
id: 'ipo_id',
name: 'ipo_id',
margin: '0 5 0 0',
//regex: /^[0-9]*$/,
//regexText: '請輸入0-9數字類型的字符',
submitValue: true,
listeners: {
specialkey: function (field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Query();
}
}
}
}
//{
// xtype: 'combobox',
// id: 'createType',
// margin: '0 5 0 0',
// fieldLabel: 'ipo_id',
// labelWidth: 60,
// //colName: 'freightType',
// queryMode: 'local',
// editable: false,
// store: createTypeStore,
// displayField: 'txt',
// valueField: 'value',
// submitValue: true,
// emptyText: '全部',
// value: -1
// ,
// listeners: {
// specialkey: function (field, e) {
// if (e.getKey() == Ext.EventObject.ENTER) {
// Query();
// }
// }
// }
//}
]
},
{
xtype: 'fieldcontainer',
combineErrors: true,
layout: 'hbox',
items: [
{
xtype: 'textfield',
fieldLabel: '商品主料位',
labelWidth: 70,
id: 'loc_id',
name: 'loc_id',
margin: '0 5 0 0',
//regex: /^[0-9]*$/,
//regexText: '請輸入0-9數字類型的字符',
submitValue: true,
listeners: {
specialkey: function (field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Query();
}
}
}
},
{
xtype: 'textfield',
fieldLabel: '商品細項編號',
labelWidth: 85,
id: 'itemId_or_upcId',
name: 'item_id',
margin: '0 5 0 0',
//regex: /^[0-9]*$/,
//regexText: '請輸入0-9數字類型的字符',
emptyText:" 或者輸入商品條碼",
submitValue: true,
listeners: {
specialkey: function (field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Query();
}
}
}
},
]
},
{
xtype: 'fieldcontainer',
combineErrors: true,
layout: 'hbox',
items: [
{
xtype: 'displayfield',
value: '創建時間:   ',
margin: '0 5 0 0'
},
{
xtype: 'datefield',
format: 'Y-m-d',
//time: { hour: 00, min: 00, sec: 00 },
id: 'time_start',
name: 'time_start',
margin: '0 5 0 0',
submitValue: true,
editable: false,
//value: Tomorrow(),
listeners: {
select: function (a, b, c) {
//var start = Ext.getCmp("time_start");
//var end = Ext.getCmp("time_end");
//if (end.getValue() != null && start.getValue() > end.getValue()) {
// Ext.Msg.alert("提示信息","開始時間不能大於結束時間");
// start.setValue(setNextMonth(end.getValue(),-1));
//}
var start = Ext.getCmp("time_start");
var end = Ext.getCmp("time_end");
var s_date = new Date(start.getValue());
end.setValue(new Date(s_date.setMonth(s_date.getMonth() + 1)));
},
specialkey: function (field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Query();
}
}
}
},
{
xtype: 'displayfield',
value: '~  '
},
{
xtype: 'datefield',
format: 'Y-m-d',
//time: { hour: 23, min: 59, sec: 59 },
id: 'time_end',
name: 'time_end',
margin: '0 5 0 0',
submitValue: true,
editable: false,
listeners: {
select: function (a, b, c) {
//var start = Ext.getCmp("time_start");
//var end = Ext.getCmp("time_end");
//if (start.getValue() != null && start.getValue() > end.getValue()) {
// Ext.Msg.alert("提示信息", "結束時間不能小於開始時間");
// end.setValue(setNextMonth(start.getValue(),+1));
//}
var start = Ext.getCmp("time_start");
var end = Ext.getCmp("time_end");
var s_date = new Date(start.getValue());
var end_date = new Date(end.getValue());
if (start.getValue() == null)
{
start.setValue(new Date(end_date.setMonth(end_date.getMonth() - 1)));
}
if (end.getValue() < start.getValue())
{
Ext.Msg.alert("提示", "開始時間不能大於結束時間!");
end.setValue(new Date(s_date.setMonth(s_date.getMonth() + 1)));
}
},
specialkey: function (field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Query();
}
}
}
}
]
},
{
xtype: 'fieldcontainer',
combineErrors: true,
layout: 'hbox',
items: [
{
xtype: 'button',
margin: '4 10 0 50',
iconCls: 'icon-search',
text: "查詢",
handler: Query
},
{
xtype: 'button',
margin: '4 10 0 0',
text: '重置',
id: 'btn_reset',
iconCls: 'ui-icon ui-icon-reset',
listeners: {
click: function () {
this.up('form').getForm().reset();
//frm.getForm().reset();
//var datetime1 = new Date();
//datetime1.setFullYear(2000, 1, 1);
//datetime1.setHours(00,00,00);
//var datetime2 = new Date();
//datetime2.setFullYear(2100, 1, 1);
//datetime2.setHours(23, 59, 59);
//Ext.getCmp("time_start").setMinValue(datetime1);
//Ext.getCmp("time_start").setMaxValue(datetime2);
//Ext.getCmp("time_end").setMinValue(datetime1);
//Ext.getCmp("time_end").setMaxValue(datetime2);
}
}
}
]
}
]
, listeners: {
//beforerender: function () {
// var delivery_statu = document.getElementById("Delivery_Status").value;
// var sear = document.getElementById("Search").value;
// var type = document.getElementById("Delivery_Type").value;
// if (delivery_statu != "") {
// Ext.getCmp('shipmentstatus').setValue(delivery_statu);
// }
// if (sear != "") {
// Ext.getCmp('search').setValue(sear);
// }
// if (type != "") {
// Ext.getCmp('shipmenttype').setValue(type);
// }
// //DeliverStore.load({
// // callback: function () {
// // DeliverStore.insert(0, { parameterCode: '0', parameterName: '全部' });
// // Ext.getCmp("shipment").setValue(DeliverStore.data.items[0].data.parameterCode);
// // }
// //});
//}
}
});
//頁面加載時創建grid
var grid = Ext.create('Ext.grid.Panel', {
id: 'IpoNvdLogGrid',
store: IpoNvdLogStore,
// height: 645,
flex: 8.5,
columnLines: true,
frame: true,
columns: [
{ header: '流水號', dataIndex: 'row_id', width: 50, align: 'center' },
{ header: '工作編號', dataIndex: 'work_id', width: 150, align: 'center'},
{
header: '採購單單號', dataIndex: 'ipo_id', width: 150, align: 'center'
},
//{ header: '商品條碼', dataIndex: 'upc_id', width: 120, align: 'center' },
{ header: '商品細項編號', dataIndex: 'item_id', width: 100, align: 'center' },
{ header: '商品主料位', dataIndex: 'loc_id', width: 100, align: 'center' },
{ header: '收貨上架數量', dataIndex: 'add_qty', width: 100, align: 'center' },
{
header: '製造日期', dataIndex: 'made_date', width: 100, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (value.substr(0, 10) == "0001-01-01") {
return ""
}
else {
return value.substr(0, 10);
}
}
},
{
header: '有效日期', dataIndex: 'cde_date', width: 100, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (value.substr(0, 10) == "0001-01-01") {
return ""
}
else {
return value.substr(0, 10);
}
}
},
{
header: '是否效期控管', dataIndex: 'pwy_dte_ctl', width: 90, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
if (value == "Y") {
return "<font color='green'>是<font/>";
}
else {
return "<font color='red'>否<font/>";
}
}
},
{ header: '創建人', dataIndex: 'create_user_string', width: 100, align: 'center' },
{ header: '創建時間', dataIndex: 'create_datetime', width: 150, align: 'center' }
],
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
tbar: [
{
//xtype: 'button',
//text: '編輯',
//disabled: true,
//iconCls: 'icon-user-edit',
//id: 'edit',
//handler: onEditClick
}
],
bbar: Ext.create('Ext.PagingToolbar', {
store: IpoNvdLogStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
})
//selModel: sm
});
Ext.create('Ext.Viewport', {
layout: 'vbox',
items: [frm, grid],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
grid.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
//ToolAuthority();
//DeliversListStore.load({ params: { start: 0, limit: 25 } });
})
setNextMonth = function (source, n) {
var s = new Date(source);
s.setMonth(s.getMonth() + n);
if (n < 0) {
s.setHours(00, 00, 00);
}
else if (n > 0) {
s.setHours(23, 59, 59);
}
return s;
}
function Tomorrow() {
var d;
d = new Date(); // 创建 Date 对象。 // 返回日期。
d.setDate(d.getDate() + 1);
return d;
}
//查询
Query = function () {
var falg = 0;
var work_id = Ext.getCmp('work_id').getValue().trim(); if (work_id != '') { falg++; }
var ipo_id = Ext.getCmp('ipo_id').getValue().trim(); if (ipo_id != '') { falg++; }
var itemId_or_upcId = Ext.getCmp('itemId_or_upcId').getValue().trim(); if (itemId_or_upcId != '') { falg++; }
var loc_id = Ext.getCmp('loc_id').getValue().trim(); if (loc_id != '') { falg++; }
var time_start = Ext.getCmp('time_start').getValue(); if (time_start != null) { falg++; }
var time_end = Ext.getCmp('time_end').getValue(); if (time_end != null) { falg++; }
IpoNvdLogStore.removeAll();
if (falg == 0) {
Ext.Msg.alert("提示", "請輸入查詢條件");
return false;
}
if (time_start != null && time_end == null) {
Ext.Msg.alert("提示", "請選擇結束時間");
return false;
}
if (time_end != null && time_start == null) {
Ext.Msg.alert("提示", "請選擇開始時間");
return false;
}
//alert(Ext.getCmp("query_type").getValue().Tax_Type);
Ext.getCmp("IpoNvdLogGrid").store.loadPage(1, {
params: {
work_id: Ext.htmlEncode(Ext.getCmp('work_id').getValue().trim()),//工作單號
ipo_id: Ext.getCmp('ipo_id').getValue().trim(),//採購單單號
itemId_or_upcId: Ext.getCmp('itemId_or_upcId').getValue().trim(),//商品細項編號、條碼
loc_id: Ext.getCmp('loc_id').getValue().trim(),//商品主料位
time_start: Ext.getCmp('time_start').getValue(),//log創建日期,開始時間
time_end: Ext.getCmp('time_end').getValue()//結束時間
}
});
}
//編輯
//onEditClick = function () {
// var row = Ext.getCmp("deliverExpectArrivalGrid").getSelectionModel().getSelection();
// if (row.length == 0) {
// Ext.Msg.alert(INFORMATION, NO_SELECTION);
// }
// else if (row.length > 1) {
// Ext.Msg.alert(INFORMATION, ONE_SELECTION);
// } else if (row.length == 1) {
// editFunction(row[0], DeliverExpectArrivalStore);
// }
//}
|
/**
* 福利商城首页
*/
import React, { Component, PureComponent } from 'react';
import {
StyleSheet,
Dimensions,
View,
Text,
Button,
TouchableOpacity,
Image,
BackHandler,
} from 'react-native';
import { connect } from 'rn-dva';
// import Swiper from "react-native-swiper";
import moment from 'moment';
import CarouselSwiper from '../../components/CarouselSwiper';
import math from '../../config/math';
import CommonStyles from '../../common/Styles';
import Header from '../../components/Header';
import * as utils from '../../config/utils';
import * as nativeApi from '../../config/nativeApi';
import * as requestApi from '../../config/requestApi';
import ImageView from '../../components/ImageView';
import BannerImage from '../../components/BannerImage';
import FlatListView from '../../components/FlatListView';
import Process from '../../components/Process';
import WMGoodsWrap from '../../components/WMGoodsWrap';
import MallHeaderTitle from '../../components/MallHeaderTitle';
import { showSaleNumText } from '../../config/utils'
import { NavigationComponent } from '../../common/NavigationComponent';
// import BlurredPrice from '../../components/BlurredPrice'
const localCode = global.regionCode;
const { width, height } = Dimensions.get('window');
const listData = [
{
name: '夺奖商品',
icon: require('../../images/home/fuli.png'),
route: '',
},
{
name: '平台大奖',
icon: require('../../images/wm/list_palf_icon.png'),
route: '',
},
{
name: '查看更多',
icon: require('../../images/home/more.png'),
route: '',
},
];
const activityData1 = [
{
// 最新揭晓,所有人参与的
icon: require('../../images/wm/recentlyPrize.png'),
route: 'WMAllLatelyPrize',
}, {
// 大奖晒单
icon: require('../../images/wm/show_order.png'),
route: 'BigPrizeOrder',
},
{ // 活动规则
icon: require('../../images/wm/drawules.png'),
route: 'WMActiveRole',
params: { param: 'type=welfare' },
},
];
class WMScreen extends NavigationComponent {
_didFocusSubscription;
scrollHeight = 0;
constructor(props) {
super(props);
this.state = {
goodsListsType: false,
limit: 10,
goodLists: [],
selectIndex: 0, // 选择查看商品详情的index
};
}
screenWillFocus () {
BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
}
screenWillBlur () {
BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
}
onBackButtonPressAndroid = () => {
const { navigation } = this.props
const isFocused = this.props.navigation.isFocused();
if (isFocused) {
navigation.goBack();
return true;
}
return false
};
componentDidMount() {
this.getData();
}
componentWillUnmount() {
}
// 获取基础数据
getData = (page = 1) => {
this.refresh(page);
};
// 刷新
refresh = (page = 1, address = localCode) => {
const { limit, total, goodLists } = this.state;
const params = {
page,
limit,
jCondition: { districtCode: address },
};
this.props.dispatch({ type: 'welfare/initPageData', payload: { params } });
};
// 抽奖状态
getProcessView = (item) => {
const time = moment(item.expectDrawTime * 1000).format(
'YYYY-MM-DD HH:mm',
);
const processValue = parseInt(item.currentCustomerNum / item.eachSequenceNumber, 10);
const processPercent = `${processValue}%`;
const borderRadius = this.state.goodsListsType ? styles.borderNone : {};
let fixedNumber = item.eachSequenceNumber > 100000 ? 0 : 1;
const showText = `${showSaleNumText(item.currentCustomerNum,fixedNumber)}/${showSaleNumText(item.eachSequenceNumber,fixedNumber)}`
switch (item.drawType) {
case 'bymember':
return (
<View style={[styles.processItem, borderRadius]}>
<Process
labelStyle={styles.labelStyle}
showText={showText}
label="进度:"
height={4}
nowValue={processValue}
/>
</View>
);
case 'bytime_or_bymember':
return (
<React.Fragment>
<View style={[styles.processItem, borderRadius]}>
<Process
labelStyle={styles.labelStyle}
showText={showText}
label="进度:"
height={4}
nowValue={processValue}
/>
</View>
<View
style={[
styles.openPrizeItem,
borderRadius,
{ borderTopColor: '#fff', borderTopWidth: 0, marginTop: 0 },
]}
>
<Text style={styles.openPrizeItemTitle}>时间:</Text>
<Text style={styles.openPrizeItemTime}>{time}</Text>
</View>
</React.Fragment>
);
case 'bytime':
return (
<React.Fragment>
<View
style={[
styles.openPrizeItem,
{ backgroundColor: '#F0F6FF' },
borderRadius,
]}
>
<Text style={styles.openPrizeItemTitle}>时间:</Text>
<Text
style={[
styles.openPrizeItemTime,
{ color: '#4A90FA' },
]}
>
{time}
</Text>
</View>
</React.Fragment>
);
case 'bytime_and_bymember':
return (
<React.Fragment>
<View style={[styles.processItem, borderRadius]}>
<Process
labelStyle={styles.labelStyle}
showText="100%"
label="进度:"
height={4}
nowValue={processValue}
/>
</View>
<View
style={[
borderRadius,
styles.flexStart,
{
paddingLeft: 6,
paddingBottom: 7,
backgroundColor: '#f0f6ff',
},
]}
>
<Text style={styles.openPrizeItemTitle}>时间:</Text>
<Text
style={[
styles.openPrizeItemTime,
{ color: '#4A90FA' },
]}
>
{time}
</Text>
</View>
</React.Fragment>
);
default:
return null;
}
};
getPrizeLable = (drawType) => {
switch (drawType) {
case 'bymember': return (
<Image source={require('../../images/wm/processPrizeicon.png')} />
);
case 'bytime': return (
<Image source={require('../../images/wm/timePrizeicon.png')} />
);
case 'bytime_or_bymember': return (
<Image source={require('../../images/wm/byTimeOrProcess.png')} />
);
case 'bytime_and_bymember': return (
<Image source={require('../../images/wm/byTimeAndProcess.png')} />
);
default: return null;
}
}
handleChangeState(key, value) {
this.setState({
[key]: value,
});
}
// 每项商品
renderItem = ({ item, index }) => {
const { navigation } = this.props;
const { goodsListsType, goodLists } = this.state;
const time = moment(item.expectDrawTime * 1000).format('MM-DD HH:mm');
const value = math.multiply( math.divide(item.currentCustomerNum , item.eachSequenceNumber), 100);
// eslint-disable-next-line radix
const processValue = (value < 1 && value !== 0) ? '1' : parseInt(value);
const processPercent = `${processValue}%`;
let fixedNumber = item.eachSequenceNumber > 100000 ? 0 : 1;
const showText = `${showSaleNumText(item.currentCustomerNum,fixedNumber)}/${showSaleNumText(item.eachSequenceNumber,fixedNumber)}`
const itemBoxRowEnd = index === goodLists && goodLists.length - 1 ? styles.itemBoxRowEnd : null;
const itemBoxColRight = index % 2 !== 0 ? styles.itemBoxColRight : null;
if (!goodsListsType) {
return (
<TouchableOpacity
style={[
styles.goodsListItemWrap,
styles.flexStart_noCenter,
]}
activeOpacity={0.65}
onPress={() => {
this.setState({ selectIndex: index });
navigation.navigate('WMGoodsDetail', {
goodsId: item.goodsId,
sequenceId: item.sequenceId,
});
}}
>
<View style={{
position: 'absolute', top: 15, left: 15, zIndex: 1,
}}
>
{ // 获取开奖类型标签
this.getPrizeLable(item.drawType)
}
</View>
<WMGoodsWrap
imgUrl={item.mainUrl}
imgStyle={styles.imgStyle}
title={() => (
<Text style={styles.goodsViewText} numberOfLines={2}>
<Text style={[styles.red_color]}>{`[${math.divide(item.perPrice, 100)}消费券夺${math.divide(item.price, 100)}元]`}</Text>
{item.goodsName}
</Text>
)}
showProcess
type={item.drawType}
label="参与人次:"
timeLabel="开奖时间:"
labelStyle={styles.labelStyle}
processValue={processValue}
timeValue={time}
showText={showText}
// renderInsertContent={() => (
// <View style={{ height: 14,width: 100,marginTop: 5,marginBottom: 2,paddingHorizontal: 5,backgroundColor:'#FFEFEA',borderRadius: 14,...CommonStyles.flex_center }}>
// <Text style={{ fontSize: 10,color:"#FF8523",textAlign: 'center' }}>中奖后凭券0元兑换</Text>
// </View>
// )}
/>
</TouchableOpacity>
);
}
return (
<TouchableOpacity
activeOpacity={0.65}
style={[
styles.goodsListItemWrap_Col,
itemBoxColRight,
itemBoxRowEnd,
]}
onPress={() => {
this.setState({ selectIndex: index });
navigation.navigate('WMGoodsDetail', {
goodsId: item.goodsId,
sequenceId: item.sequenceId,
});
}}
>
<View style={styles.goodsView}>
<Image
style={styles.goodsViewImage}
source={{ uri: item.mainUrl || '' }}
/>
<Text style={styles.goodsViewText} numberOfLines={1}>
{item.goodsName}
</Text>
<View style={{ height: 14,width: 100,paddingHorizontal: 5,backgroundColor:'#FFEFEA',borderRadius: 14,...CommonStyles.flex_center }}>
<Text style={{ fontSize: 10,color:"#FF8523",textAlign: 'center' }}>订单半额消费券返还</Text>
</View>
<View style={[styles.flexStart, { marginTop: 3 }]}>
<Text style={styles.goodsTicketsText_col}>
消费券:
</Text>
{/* <BlurredPrice> */}
<Text
style={[
styles.goodsTicketsText_col,
{ color: '#222' },
]}
>
{item.perPrice}
</Text>
{/* </BlurredPrice> */}
</View>
{this.getProcessView(item)}
</View>
</TouchableOpacity>
);
};
render() {
const { navigation, wmRecommendList, bannerLists } = this.props;
const { goodsListsType } = this.state;
const goodLists = wmRecommendList.data || [];
return (
<View style={styles.container}>
<Header
navigation={navigation}
goBack
centerView={(
<View style={[styles.headerItem, styles.headerCenterView]}>
<TouchableOpacity
activeOpacity={0.8}
style={styles.headerCenterItem1}
onPress={() => { navigation.navigate('WMSearch'); }}
>
<View style={styles.headerCenterItem1_search}>
<Image source={require('../../images/mall/search.png')} />
</View>
<View style={styles.headerCenterItem1_textView}>
<Text style={styles.headerCenterItem1_text} numberOfLines={1}>搜索你想要的商品</Text>
</View>
</TouchableOpacity>
<View style={{ marginLeft: 15 }}>
<MallHeaderTitle
data={[{
icon: require('../../images/mall/collection.png'),
onPress: () => {
navigation.navigate('WelfareFavorites');
},
},
{
icon: require('../../images/mall/messages.png'),
onPress: () => { nativeApi.createXKCustomerSerChat(); },
},
{
icon: require('../../images/mall/shoppingcart.png'),
onPress: () => {
navigation.navigate('IndianaShopCart');
},
},
{
icon: require('../../images/mall/fg_ling.png'),
onPress: () => {
},
},
{
icon: require('../../images/mall/orders.png'),
onPress: () => {
navigation.navigate('WMOrderList');
},
}]}
/>
</View>
</View>
)}
rightView={<View style={{ width: 0 }} />}
leftView={(
<View>
<TouchableOpacity
style={[styles.headerItem, styles.left]}
onPress={() => {
navigation.goBack();
}}
>
<Image source={require('../../images/mall/goback.png')} />
</TouchableOpacity>
</View>
)}
/>
<FlatListView
flatRef={(e) => { e && (this.flatListRef = e); }}
style={styles.flatList}
store={wmRecommendList.params}
data={goodLists}
onScroll={(e) => {
const y = e.nativeEvent.contentOffset.y;
this.scrollHeight = y;
}}
ListHeaderComponent={(
<View>
{
bannerLists.length !== 0
// eslint-disable-next-line no-mixed-operators
&& (
<CarouselSwiper
key={bannerLists.length}
style={styles.bannerView}
loop
autoplay
onPageChanged={(index) => {
// this.setState({ bannerIndex: index })
}}
index={0}
autoplayTimeout={5000}
showsPageIndicator
pageIndicatorStyle={styles.banner_dot}
activePageIndicatorStyle={styles.banner_activeDot}
>
{
bannerLists.length !== 0 && bannerLists.map((item, index) => {
const data = item.templateContent || [];
return (
<BannerImage
// eslint-disable-next-line react/no-array-index-key
key={index}
navigation={navigation}
style={styles.bannerView}
data={data}
/>
);
})
}
</CarouselSwiper>
) || <View style={styles.bannerView} />
}
<View style={styles.categoryView}>
{listData && listData.length !== 0
&& listData.map((item, index) => (
<TouchableOpacity
// eslint-disable-next-line react/no-array-index-key
key={index}
style={styles.categoryItem}
onPress={() => {
navigation.navigate('WMLists', { index });
}}
>
<ImageView
style={styles.category_img}
resizeMode="cover"
source={item.icon}
sourceWidth={40}
sourceHeight={40}
fadeDuration={0}
/>
<Text
numberOfLines={1}
style={styles.category_text}
>
{item.name}
</Text>
</TouchableOpacity>
))}
</View>
<View style={styles.adTitle}>
<Image source={require('../../images/wm/left-side.png')} />
<Text style={styles.adTitle_text}>下单抽大奖赢好礼</Text>
<Image source={require('../../images/wm/right-side.png')} />
</View>
<View style={[styles.adLists, { minHeight: 120 }]}>
{activityData1.map((item, index) => (
<TouchableOpacity
// eslint-disable-next-line react/no-array-index-key
key={index}
style={[styles.adLists_item]}
onPress={() => { navigation.navigate(item.route, item.params); }}
>
<Image
// resizeMode='center'
source={item.icon}
fadeDuration={0}
/>
</TouchableOpacity>
))}
</View>
<View style={styles.Blockbote} />
<View style={[CommonStyles.flex_center, {
position: 'relative', padding: 15, backgroundColor: '#fff', borderBottomColor: '#f1f1f1', borderBottomWidth: 0.7,
}]}
>
<View style={[CommonStyles.flex_start]}>
<View style={[styles.line]} />
<Text style={{ fontSize: 17, color: '#222', marginHorizontal: 6 }}>商品推荐</Text>
<View style={[styles.line]} />
</View>
<View style={[CommonStyles.flex_start, { position: 'absolute', right: 15, top: 15 }]}>
<Text onPress={() => { this.props.navigation.navigate('WMLists', { index: 10 }); }}>
更多
</Text>
<Image source={require('../../images/index/expand.png')} />
</View>
</View>
</View>
)}
emptyStyle={{
paddingBottom: 40,
}}
ItemSeparatorComponent={() => (
<View style={styles.flatListLine} />
)}
renderItem={this.renderItem}
numColumns={!goodsListsType ? 1 : 2}
refreshData={() => {
console.log('refreshData');
this.handleChangeState('refreshing', true);
this.getData(1);
}}
loadMoreData={() => {
console.log('loadMoreData');
this.refresh(wmRecommendList.page + 1);
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
// backgroundColor:'#EEEEEE'
},
red_color: {
color: '#EE6161',
},
borderNone: {
borderRadius: 0,
},
flexStart: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
},
flexStart_noCenter: {
flexDirection: 'row',
justifyContent: 'flex-start',
},
flex_1: {
flex: 1,
},
headerItem: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
},
headerCenterView: {
flex: 1,
},
headerCenterItem1: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
flex: 1,
height: 30,
borderRadius: 15,
backgroundColor: 'rgba(255,255,255,0.5)',
},
headerCenterItem1_search: {
width: 32,
paddingHorizontal: 8,
marginTop: 1,
},
headerCenterItem1_textView: {
justifyContent: 'center',
alignItems: 'flex-start',
flex: 1,
// height: 20,
marginRight: 8,
},
headerCenterItem1_text: {
fontSize: 14,
color: 'rgba(255,255,255,0.8)',
},
headerCenterItem2: {
width: 114,
},
headerCenterItem2_icon: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
flex: 1,
height: '100%',
},
flatList: {
flex: 1,
backgroundColor: CommonStyles.globalBgColor,
},
flatListLine: {
height: 0,
backgroundColor: '#F1F1F1',
},
bannerView: {
height: 136,
backgroundColor: '#f1f1f1',
},
banner_dot: {
width: 4,
height: 4,
borderRadius: 4,
marginLeft: 1.5,
marginRight: 1.5,
marginBottom: -20,
backgroundColor: '#fff',
},
banner_activeDot: {
width: 12,
height: 4,
borderRadius: 10,
marginLeft: 1.5,
marginRight: 1.5,
marginBottom: -20,
backgroundColor: '#fff',
},
categoryView: {
// ...CommonStyles.shadowStyle,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-between',
width,
height: 87,
marginBottom: 10,
backgroundColor: '#fff',
paddingHorizontal: 15,
overflow: 'hidden',
paddingHorizontal: 34,
},
categoryItem: {
justifyContent: 'center',
alignItems: 'center',
// width: '25%',
height: '100%',
// paddingHorizontal: 5,
},
category_img: {
width: 40,
height: 40,
borderRadius: 20,
},
category_text: {
fontSize: 12,
color: '#222',
marginTop: 5,
},
adTitle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
width,
height: 47,
backgroundColor: '#FBEEDE',
},
adTitle_text: {
fontSize: 17,
color: '#222',
marginHorizontal: 15,
fontWeight: 'bold',
},
adLists: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
width,
backgroundColor: '#FBEEDE',
paddingBottom: 25,
paddingHorizontal: 10,
},
Blockbote: {
backgroundColor: '#f6f6f6',
height: 10,
},
adLists_item: {
// ...CommonStyles.shadowStyle,
position: 'relative',
width: (width - 20) / 3,
// height: 105,
marginTop: 10,
borderRadius: 8,
...CommonStyles.flex_center,
// backgroundColor: '#fff',
},
adLists_item_end: {
marginRight: 10,
},
adLists_item_img: {
// width: 110,
// height: 80,
width: (width - 30) / 3,
height: 110,
// width: '100%',
// height: '100%'
},
adLists_item_textView: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
flex: 1,
},
adLists_item_text: {
fontSize: 14,
color: '#222',
},
adLists_item_icon: {
position: 'absolute',
top: 0,
left: 0,
},
adBtn: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
width,
height: 70,
backgroundColor: '#F6F6F6',
},
adBtnImg: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
width: 279,
height: 50,
},
adBtn_text: {
fontSize: 14,
color: '#fff',
},
itemHeader: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
width,
padding: 15,
paddingBottom: 3,
backgroundColor: '#fff',
},
itemHeaderCol: {
paddingBottom: 13,
},
itemHeader_text: {
fontSize: 17,
marginHorizontal: 6,
color: '#222',
},
headerRight_icon: {
width: 50,
},
itemHeaderTitle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
flex: 1,
},
itemHeaderTitle_line: {
width: 15,
height: 2,
borderRadius: 8,
backgroundColor: '#4A90FA',
},
itemBoxRowEnd: {
marginBottom: 10,
},
learnMore: {
backgroundColor: '#f6f6f6',
height: 44,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
learnMoreText: {
fontSize: 14,
color: '#777',
textAlign: 'center',
},
processItem: {
flexDirection: 'row',
justifyContent: 'flex-start',
backgroundColor: '#f0f6ff',
paddingVertical: 8,
paddingHorizontal: 7,
borderRadius: 4,
marginTop: 5,
},
labelStyle: {
fontSize: 12,
color: '#777',
paddingRight: 7,
},
goodsTicket: {
flexDirection: 'row',
justifyContent: 'space-between',
backgroundColor: '#fff',
paddingLeft: 10,
marginTop: 10,
},
goodsTicketLeft: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
},
goodsTicketLeftTitle: {
fontSize: 12,
color: '#555',
},
goodsTicketLeftNum: {
paddingLeft: 6,
color: '#EE6161',
fontSize: 12,
},
goodsTicketRight: {
fontSize: 12,
color: '#999',
},
openPrizeItem: {
flexDirection: 'row',
justifyContent: 'flex-start',
backgroundColor: '#FFF4E1',
paddingVertical: 8,
paddingHorizontal: 7,
borderRadius: 4,
marginTop: 2,
},
openPrizeItemTitle: {
fontSize: 12,
color: '#777',
paddingRight: 5,
},
openPrizeItemTime: {
fontSize: 12,
color: '#F5A623',
},
nomargin: {
marginTop: 0,
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
backgroundColor: '#F0F6FF',
paddingTop: 0,
backgroundColor: 'red',
},
noBottomRadius: {
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
},
goodsListItemWrap: {
backgroundColor: '#fff',
borderBottomWidth: 0.7,
borderBottomColor: '#F1F1F1',
// padding: 15
},
goodsImg: {
height: 100,
width: 100,
},
goodsInfoWrap: {
paddingLeft: 12,
},
goodsTicketsText: {
fontSize: 12,
color: '#777',
},
goodsListItemWrap_Col: {
width: width / 2 - 2,
borderRadius: 6,
paddingRight: 3.5,
paddingLeft: 10,
marginTop: 10,
},
itemBoxColRight: {
paddingLeft: 3.5,
paddingRight: 10,
},
goodsView: {
borderColor: '#f1f1f1',
borderWidth: 1,
borderRadius: 6,
},
goodsViewImage: {
width: '100%',
height: 168,
borderTopLeftRadius: 6,
borderTopRightRadius: 6,
},
goodsViewText: {
fontSize: 14,
lineHeight: 16,
color: '#101010',
paddingLeft: 6,
paddingTop: 8,
},
goodsTicketsText_col: {
paddingLeft: 6,
fontSize: 12,
color: '#777',
},
goodsTitleStyle: {
fontSize: 14,
lineHeight: 18,
color: '#222',
},
marginHor: {
marginLeft: 0,
},
itemHeaderTitle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
itemHeaderTitle_line: {
width: 15,
height: 2,
borderRadius: 8,
backgroundColor: '#4A90FA',
},
imgStyle: {
borderRadius: 8,
},
line: {
width: 15,
height: 2,
borderRadius: 8,
backgroundColor: '#4A90FA',
},
expenseLabel: {
position: 'absolute',
bottom: 15.5,
left: 15.5,
zIndex: 2,
height: 20,
width: 79,
overflow: 'hidden',
borderBottomLeftRadius: 10,
borderBottomRightRadius: 10,
},
left: {
width: 50,
},
});
export default connect(
state => ({
wmRecommendList: state.welfare.wmRecommendList || {},
bannerLists: state.welfare.bannerList_wm || [],
}),
)(WMScreen);
|
'use strict';
angular.module('FEF-Angular-UI.version', [])
.value('version', '0.1'); |
import React, { Component } from 'react';
import { Col } from 'react-bootstrap';
import Bio from './components/Bio'
import Section from './components/Section'
import KeySkill from "./components/KeySkill";
import Specialization from './components/Specialization'
import Job from './components/Job'
import Training from './components/Training'
import Contact from './components/Contact'
import Footer from './components/Footer'
import './App.css'
import * as $ from './data'
class App extends Component {
state = {
skills: $.Skills,
specializations: $.Specializations,
career: $.Career,
training: $.Training
}
render() {
return (
<div>
<div className="container max">
<Bio />
<Section title="Key ML Skills">
<Col md={{span: 8}} id="skills">
{ this.state.skills.map((skill) => {return <KeySkill key={skill.name} name={skill.name} color={skill.color} />})}
</Col>
</Section>
<Section title="Tech Toolbox" id="specializations">
{ Object.values(this.state.specializations).map((spec) => {
return <Specialization data={spec} key={spec.title}/>
}) }
</Section>
<Section title="Career Development">
{ Object.keys(this.state.career.Career).map((key) => {
let job = this.state.career.Career[key];
return(<Job details={job} key={key}/>)})
}
</Section>
<Section title="Training">
{ this.state.training.map((training) => {return(<Training details={training} key={training.title}/>)}) }
</Section>
<Section title="Contact & Social">
<Col md={6} className="text-center">
<Contact to='mailto:nic@oll.is' icon='at' brand='false' />
<Contact to='http://twitter.com/nic_ollis' icon='twitter' brand='true'/>
<Contact to='https://www.kaggle.com/nicollis' icon='kaggle' brand='true'/>
<Contact to='https://medium.com/program-practical' icon='medium' brand='true'/>
<Contact to='https://www.youtube.com/c/programpracticaltv' icon='youtube' brand='true'/>
<Contact to='https://www.linkedin.com/in/nicollis' icon='linkedin' brand='true'/>
<Contact to='https://github.com/nicollis' icon='github' brand='true'/>
<Contact to='https://www.twitch.tv/programpractical' icon='twitch' brand='true'/>
</Col>
</Section>
</div>
<Footer />
</div>
);
}
}
export default App;
|
//--------------------------------------
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const {generarMensaje, generarMensajeGeolocalizado} = require('./utils/mensaje');
const {isRealString} = require('./utils/validation');
const {Users} = require('./utils/users');
const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
var users = new Users();
//--------------------------------------
app.use(express.static(publicPath));
//--------------------------------------
//Conectar lado servidor ------------
io.on('connection', (socket) => {
console.log('New user connected');
socket.on('join', (params, callback) => {//Un usuario se une!!!!!!!!!!
if(!isRealString(params.name) || !isRealString(params.room)){
callback('Nickname y Room son requeridos');
}
socket.join(params.room);//Se une a un room
users.removeUser(socket.id);//Lo borro para q no este en otro room
users.addUser(socket.id, params.name, params.room);//lo añado
io.to(params.room).emit('updateUserList', users.getUserList(params.room));
socket.emit('newMessage', generarMensaje('Admin', 'Bienvenido a la sala de chat')); //Mensaje solo a la conexion actual
//Mensaje de para todos de que hay un nuevo ususario, menos para la conexion actual--.-.-.-.-
socket.broadcast.to(params.room).emit('newMessage', generarMensaje('Admin', `${params.name} se ha unido`));
callback();
});
socket.on('createMessage', (mensaje, callback) => {//Recibir un callback Acknowledgement
//console.log('Msj del servidor al cliente', mensaje);
var user = users.getUser(socket.id);
if(user&& isRealString(mensaje.text)){
io.to(user.room).emit('newMessage', generarMensaje( user.name, mensaje.text));//Manda el msj a todas las conexiones
}
callback();
});
socket.on('createLocationMessage', (coords) => {
var user = users.getUser(socket.id);
if(user){
io.to(user.room).emit('newLocationMessage', generarMensajeGeolocalizado(user.name, coords.latitud, coords.longitud));
}
});
socket.on('disconnect', () => {//Un usuario se va !!!!!!!!!!
//console.log('User was disconnected');
var user = users.removeUser(socket.id);
if(user){
io.to(user.room).emit('updateUserList', users.getUserList(user.room));
io.to(user.room).emit('newMessage', generarMensaje('Admin', `${user.name} se ha retirado de la Sala.`));
}
});
});
//--------------------------------------
//Conectar lado servidor ------------
server.listen(port, () => {
console.log(`Server is up on ${port}`);
});
//-------------------------------------- |
import React, { useState, useContext } from 'react'
import { Link } from 'react-router-dom';
import usercontext from '../Context/User/usercontext';
import axios from 'axios'
import setAuthToken from '../utils/setAuthToken';
import NProgress from 'nprogress';
import './nprogress.css';
import { useToasts } from 'react-toast-notifications';
function Signup() {
const { addToast } = useToasts();
const context = useContext(usercontext)
const { setuser } = context;
const initialState = {
name: "",
email: "",
password: ""
}
const [formdata, setformdata] = useState(initialState)
const handlechange = (e) => {
setformdata({
...formdata,
[e.target.name]: e.target.value.trim(), //to clear any whitespaces before or after
})
}
// Load User
const loadUser = async () => {
setAuthToken(localStorage.token);
try {
const res = await axios.get('http://localhost:5000/api/auth/');
NProgress.done();
console.log("Signed In");
setuser(res.data);
addToast("Signed In Successfully", { appearance: 'success', autoDismiss: true });
} catch (err) {
console.log(err);
NProgress.done();
addToast({ err }, { appearance: 'error', autoDismiss: true });
}
};
const signupsubmit = async (e) => {
e.preventDefault();
if (formdata.email === "" | formdata.password === "" | formdata.name === "") {
addToast("All Field Are Required!", { appearance: 'error', autoDismiss: true });
return;
}
NProgress.start();
// Register User
const config = {
headers: {
'Content-Type': 'application/json'
}
};
try {
const res = await axios.post("http://localhost:5000/api/users/", JSON.stringify(formdata), config);
if (res.status === 400) {
addToast("User Already Exists", { appearance: 'error', autoDismiss: true });
} if (res.status === 500) {
addToast("Server Error", { appearance: 'error', autoDismiss: true });
}
localStorage.setItem('token', res.data.token);
addToast("User Created", { appearance: 'success', autoDismiss: true });
loadUser();
} catch (err) {
console.log(err);
NProgress.done();
if (formdata.password.length < 6) {
addToast("Weak Password Password!", { appearance: 'error', autoDismiss: true });
} else {
addToast("User Already Exists!", { appearance: 'error', autoDismiss: true });
}
}
}
return (
<>
<div className="d-flex">
<img src={process.env.PUBLIC_URL + "/loginimg.jpg"} alt="#" className="" width="1000" height="791" />
<form className="container mt-5 mx-2">
<h1 style={{ color: "#003152" }} className=" font-weight-normal text-capitalize font-weight-lighter">Stocks Tracker</h1>
<br />
<br />
<h3 className="font-weight-lighter">SignUP</h3>
<div className="form-group mt-4">
<label>Name</label>
<input type="text" className="form-control" name="name" placeholder="Name" onChange={handlechange} />
</div>
<div className="form-group">
<label>Email</label>
<input type="email" className="form-control" name="email" placeholder="Enter email" onChange={handlechange} />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" name="password" placeholder="Enter password" onChange={handlechange} />
</div>
<button type="submit" className="btn btn-dark btn-lg btn-block mt-4" onClick={signupsubmit}>Register</button>
<Link to="/login" className="btn btn-light btn-md btn-block">Already have an account</Link>
</form>
</div>
</>
);
}
export default Signup
|
export const pending = (type) => `${type}_PENDING`;
export const fulfilled = (type) => `${type}_FULFILLED`;
export const rejected = (type) => `${type}_REJECTED`;
export const ACTION = {
ADD_TODO: 'ADD_TODO',
TOGGLE_TODO: 'TOGGLE_TODO',
};
|
import { React } from "react";
import "./Index.css";
function PreloaderXXL() {
return (
<>
<div className="preloaderXXL">
<p className="preloaderXXL__text">
Loading
<span className="dots">...</span>
</p>
</div>
</>
);
}
export default PreloaderXXL;
|
//select elements
const tempElement = document.querySelector('.temperature.value p');
const descElement = document.querySelector('.temperature.description');
const locationElement = document.querySelector('.location p');
const notificationElement = document.querySelector('.notification');
//App data
const weather = {};
weather.temperature={
unit:'celsius'
};
//Const and Variables
const KELVIN = 273;
//API key
const key = 'a1485357b2de86d49abcf6f44cb0d44a';
//Check if browser supports Geolocation
if('geolocation' in navigator){
navigator.geolocation.getCurrentPosition(setPosition,showError);
}else{
notificationElement.style.display = 'block';
notificationElement.innerHTML = '<p> Browser doesnt support Geolocation';
}
//Set user position
function setPosition(position){
let latitude = position.coord.latitude;
let longitude = position.coord.longitude;
getWeather(latitude,longitude);
}
//Show error when there is a issue with geolocation service
function showError(error){
notificationElement.style.display = 'block';
notificationElement.innerHTML = '<p> ${error.message}';
}
//get weather from API Provider
function getWeather(latitude,longitude){
let api='http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}';
fetch(api)
.then(function(response){
let data = response.json();
return data;
})
.then (function(data){
weather.temperature.value=Math.floor(data.main.temp - KELVIN)
weather.description = data.weather[0].description;
weather.iconID = data.weather[0].icon;
weather.city=data.name;
weather.city=data.name;
weather.country = data.sys.country;
})
.then(function(){
displayWeather();
});
}
//DISPLAY WEATHER TO UI
function displayWeather() {
tempElement.innerHTML = '${weather.temperature.value} <span>C</span>'
descElement.innerHTML = weather.description;
locationElement.innerHTML = '${weather.city}, ${weather.country}';
} |
jQuery(document).ready(function($) {
$('.J_sub_heng').fadeOut();
(function(){
$('.icon-liebiao').click(function(event) {
$(this).addClass('active').parent().siblings().find('.iconfont').removeClass('active');
$('.J_sub_li').fadeIn();
$('.J_sub_heng').fadeOut();
});
$('.icon-liebiao1').click(function(event) {
$(this).addClass('active').parent().siblings().find('.iconfont').removeClass('active');
$('.J_sub_li').fadeOut();
$('.J_sub_heng').fadeIn();
});
})();
}); |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Konami Code</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
"use strict";
var keys = {
up: 38,
down: 40,
left: 37,
right: 39,
a: 65,
b: 66,
enter: 13
};
var sequence = [
keys.up,
keys.up,
keys.down,
keys.down,
keys.left,
keys.right,
keys.left,
keys.right,
keys.b,
keys.a,
keys.enter
];
var keyIndex = 0;
$("body").keydown(function(e) {
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode == sequence[keyIndex]) {
console.log("hit: " + charCode);
keyIndex++;
if (keyIndex == sequence.length) {
console.log("A Winner Is You!");
keyIndex = 0;
}
} else {
console.log("miss: " + charCode);
keyIndex = 0;
}
});
});
</script>
</head>
<body>
</body>
</html>
|
import React from 'react';
import PropTypes from 'prop-types';
function NewTweetForm(props){
let _name = null;
let _content = null;
function handleNewTweetFormSubmission(event) {
event.preventDefault();
console.log(_name.value);
console.log(_content.value);
props.onNewTweetCreation({name: _name.value, content: _content.value});
_name.value = '';
_content.value = '';
}
return (
<div>
<form onSubmit={handleNewTweetFormSubmission}>
<input
type='text'
id='name'
placeholder='User Name'
ref={(input) => {_name = input;}}/>
<textarea
type='text'
id='content'
placeholder='What do you want to say'
ref={(textarea) => {_content = textarea;}}/>
<button type='submit'>Shout!</button>
</form>
</div>
);
}
NewTweetForm.propTypes = {
onNewTweetCreation: PropTypes.func
};
export default NewTweetForm;
|
import React, { Component } from 'react'
import s from './Card.css'
class Card extends Component{
render(){
return(
<div className={`${s.wrapper}`}>
<div className={`${s.bg}`} style={{ backgroundImage: `url(${this.props.img})`}} ></div>
<div className={`${s.info}`}>
<div className={`${s.data}`} >{this.props.data}</div>
<div className={`${s.title}`}>{this.props.title}</div>
</div>
</div>
)
}
}
export default Card
|
var searchData=
[
['xm_5fdim_5ft',['xm_dim_t',['../structxm__dim__t.html',1,'']]]
];
|
import "./TheTitle.css";
function TheTitle(props) {
return (
<section className="titleStyle">
<h1>{props.name}</h1>
</section>
);
}
export default TheTitle;
|
var PhoneticSearch = (function(input, dictionary) {
return search;
function search(input, dictionary) {
var inputPhoneticArray = getPhoneticArray(input);
var dictPhoneticArray = getPhoneticArray(dictionary);
return inputPhoneticArray.map(function(inputItem) {
inputItem.similar = dictPhoneticArray.filter(function(dictItem) {
return inputItem.phonetic === dictItem.phonetic;
}).map(function(dictItem) {
return dictItem.word;
}).join(', ');
return inputItem;
});
};
function getPhoneticArray(arr) {
if (typeof arr !== 'object' && !Array.isArray(arr)) {
throw new Error('The object is not an array!');
}
return arr.map(function(item) {
var phonetic = item;
phonetic = removeNonAlphabeticChars(phonetic);
phonetic = decapitalize(phonetic);
phonetic = discardCharsAfterFirstChar(phonetic);
phonetic = changeEquivalents(phonetic);
phonetic = removeDuplicatedChars(phonetic);
return {
word: item,
phonetic: phonetic
};
});
}
function getPhoneticSimilarItems(inputArr, dictArr) {
inputArr.map(function(inputItem) {
inputItem.similar = dictArr.filter(function(dictItem) {
return inputItem.phonetic === dictItem.phonetic;
}).map(function(dictItem) {
return dictItem.word;
}).join(', ');
return inputItem;
});
}
function removeNonAlphabeticChars(str) {
var pattern = /[^a-z\s]/gi;
str = str.replace(pattern, '');
return str;
}
function decapitalize(str) {
str = str.toLowerCase();
return str;
}
function discardCharsAfterFirstChar(str) {
var pattern = /A|E|I|H|O|U|W|Y/gi;
var firstLetter = str.substring(0, 1);
str = str.substring(1).replace(pattern, '');
return firstLetter + str;
}
function changeEquivalents(str) {
str = str.replace(/A|E|I|O|U/gi, 'A');
str = str.replace(/C|G|J|K|Q|S|X|Y|Z/gi, 'C');
str = str.replace(/B|F|P|V|W/gi, 'B');
str = str.replace(/D|T/gi, 'D');
str = str.replace(/M|N/gi, 'M');
str = str.replace(/R/gi, 'R');
str = str.replace(/L/gi, 'L');
return str;
}
function removeDuplicatedChars(str) {
str = str.replace(/(.)(?=.*\1)/g, '');
return str;
}
})();
typeof module === 'undefined' ? window.PhoneticSearch = PhoneticSearch
: module.exports = PhoneticSearch; |
import React from 'react';
import { RouteHandler } from "react-router";
import {Grid} from 'react-bootstrap';
import AppActions from "../actions/AppActions";
import Navigation from "./partials/Navigation";
import GlobalModal from "./partials/GlobalModal";
class App extends React.Component {
constructor(props){
super(props);
}
componentDidMount(){
window.addEventListener('click', this.handleClick.bind(this));
}
handleClick(e){
AppActions.updateClicks(e);
}
render() {
return (
<div>
<Navigation/>
<Grid fluid>
<RouteHandler/>
</Grid>
<GlobalModal />
</div>
);
}
}
export default App; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.