text
stringlengths 7
3.69M
|
|---|
angular.module('boosted')
.controller('blogitem', function($scope, service , $stateParams) {
service.getOneBlog(parseInt($stateParams.blogid)).then(function(blog) {
$scope.blog = blog.data;
})
})
|
var searchData=
[
['main',['main',['../client_8c.html#a7be7b3f3b810d259483db57fef9b4c4c',1,'main(int args, char *argv[]): client.c'],['../server_8c.html#a7be7b3f3b810d259483db57fef9b4c4c',1,'main(int args, char *argv[]): server.c']]]
];
|
import 'es5-shim';
import 'es6-shim';
import 'array.prototype.fill'; // Array.prototype.fill
import 'es6-symbol/implement'; // Symbol.iterator
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';
import Immutable from 'immutable';
import 'rc-slider/dist/rc-slider.css?global';
import style from './style.scss';
// import sagaMonitor from './sagaMonitor';
import link from './linker';
import commonBundle from './common/index';
import sandboxBundle from './sandbox/index';
import playerBundle from './player/index';
import recorderBundle from './recorder/index';
import editorBundle from './editor/index';
const {store, scope, actionTypes, views, finalize, start} = link(function (bundle, deps) {
bundle.defineAction('init', 'System.Init');
bundle.addReducer('init', (_state, _action) =>
Immutable.Map({scope, actionTypes, views}));
bundle.include(commonBundle);
bundle.include(sandboxBundle);
bundle.include(playerBundle);
bundle.include(recorderBundle);
bundle.include(editorBundle);
if (process.env.NODE_ENV === 'development') {
bundle.addEarlyReducer(function (state, action) {
console.log('action', action);
return state;
});
}
}/*, {reduxSaga: {sagaMonitor}}*/);
finalize(scope, actionTypes);
function restart () {
if (Codecast.task) {
Codecast.task.cancel();
Codecast.task = null;
}
/* XXX Make a separate object for selectors in the linker? */
Codecast.task = start({
dispatch: store.dispatch,
globals: scope,
selectors: scope,
actionTypes,
views});
}
/* In-browser API */
const Codecast = window.Codecast = {store, scope, restart};
/*
options :: {
start: 'sandbox'|'player'|'recorder'|'editor',
baseUrl: url,
examplesUrl: url,
baseDataUrl: url,
user: {…},
platform: 'unix'|'arduino',
controls: {…},
showStepper: boolean,
showStack: boolean,
showViews: boolean,
showIO: boolean,
source: string,
input: string,
token: string
}
*/
Codecast.start = function (options) {
store.dispatch({type: scope.init, payload: {options}});
// XXX store.dispatch({type: scope.stepperConfigure, options: stepperOptions});
/* Run the sagas (must be done before calling autoLogin) */
restart();
let App;
switch (options.start) {
case 'recorder':
autoLogin();
store.dispatch({type: scope.recorderPrepare});
App = scope.RecorderApp;
break;
case 'player':
let audioUrl = options.audioUrl || `${options.baseDataUrl}.mp3`;
store.dispatch({
type: scope.playerPrepare,
payload: {
baseDataUrl: options.baseDataUrl,
audioUrl: audioUrl,
eventsUrl: `${options.baseDataUrl}.json`,
data: options.data
}
});
App = scope.PlayerApp;
break;
case 'editor':
autoLogin();
store.dispatch({
type: scope.editorPrepare,
payload: {
baseDataUrl: options.baseDataUrl
}
});
App = scope.EditorApp;
break;
case 'sandbox':
App = scope.SandboxApp;
break;
default:
App = () => <p>{"No such application: "}{options.start}</p>;
break;
}
const {AppErrorBoundary} = scope;
const container = document.getElementById('react-container');
ReactDOM.render(
<Provider store={store}>
<AppErrorBoundary>
<App/>
</AppErrorBoundary>
</Provider>, container);
};
function autoLogin () {
let user = null;
try {
user = JSON.parse(window.localStorage.user || 'null');
} catch (ex) {
return;
}
store.dispatch({type: scope.loginFeedback, payload: {user}});
}
|
const initialState = {
chapters: [],
loading: true,
error: null,
};
const chaptersReducer = (state = initialState, { type, payload }) => {
switch (type) {
case "chapters/success":
return { ...state, loading: false, chapters: payload };
case "chapters/loading":
return { ...state, loading: true, chapters: [] };
case "chapters/error":
return { ...state, loading: false, error: payload };
case "questions/update":
console.log(payload);
return {
...state,
chapters: state.chapters.map(ch =>
ch.id === payload.chapterID
? {
...ch,
questions: ch.questions.map((qu, qIndex) => ({
...qu,
completed: true,
correct:
qu.answer === payload.answers[qIndex],
chosenAnswer: payload.answers[qIndex],
})),
}
: ch
),
};
default:
return state;
}
};
export default chaptersReducer;
|
/***********************************************************************************
* ViewModel class.
* This class provides various types of demographic information for a given
* location/zoom level.
* @constructor
*/
function viewModel() {
// information sources available to views
this.sources = {
tapestry: new infoSource(this, "USA_Tapestry", "DOMTAP,TAPSEGNAM"),
populationBySex: new infoSource(this, "USA_Population_by_Sex", "TOTPOP_CY,PMALE_CY,PFEMALE_CY,MALES_CY,FEMALES_CY"),
age: new infoSource(this, "USA_Median_Age", "TOTPOP_CY,MEDAGE_CY,POP0_9,POP10_19,POP20_29,POP30_39,POP40_49,POP50_59,POP60_69,POP70_79,POP80_plus", "POP0_9,POP80_plus", "2012 Total Population Age "),
householdIncome: new infoSource(this, "USA_Median_Household_Income", "TOTPOP_CY,MEDHINC_CY,HINCBASECY,HINC50_CY,HINC75_CY,HINC100_CY,HINC150_CY,HINC200_CY,MEDHHINC_pct_USAvg,HINC0_25,HINC25_50", "HINC50_CY,HINC200_CY", "2012 Household Income "),
netWorth: new infoSource(this, "USA_Median_Net_Worth", "TOTPOP_CY,MEDVAL_I,MEDHINC_I,MEDNW_CY,MEDNW_I,NWBASE_CY,NW0_CY,NW15_CY,NW35_CY,NW50_CY,NW75_CY,NW100_CY,NW150_CY,NW250_CY,NW500_CY,MEDNETWORTH_pct_USAvg", "NW0_CY,NW500_CY", "2012 Net Worth "),
homeValue: new infoSource(this, "USA_Median_Home_Value", "TOTPOP_CY,MEDVAL_CY,MEDVAL_I,MEDHINC_I,MEDNW_I,VALBASE_CY,VAL0_CY,VAL50K_CY,VAL100K_CY,VAL150K_CY,VAL200K_CY,VAL250K_CY,VAL300K_CY,VAL400K_CY,VAL1M_CY,MEDHMVAL_pct_USAvg,VAL500_1M", "VAL0_CY,VAL1M_CY", "2012 Home Value ")
//daytimePopulation: new infoSource(this, "USA_Daytime_Population", "TOTPOP_CY,DNRATIO_CY"),
//populationDensity: new infoSource(this, "USA_Population_Density", "TOTPOP_CY,POPDENS_CY"),
//retailSpendingPotential: new infoSource(this, "USA_Retail_Spending_Potential", "TOTPOP_CY,MEDHINC_CY,X15001_A,X15001_I"),
//unemploymentRate: new infoSource(this, "USA_Unemployment_Rate", "TOTPOP_CY,MEDVAL_I_12,MEDHINC_I_12,MEDNW_I_12,UNEMP_CY_12,UNEMPRT_CY_12")
};
// add summary information
this.sources.age.shortList = [
new infoValue("POP0_9,POP10_19,POP20_29", "under 30"),
new infoValue("POP30_39,POP40_49,POP50_59", "30 to 59"),
new infoValue("POP60_69,POP70_79,POP80_plus", "60 and over")
];
this.sources.householdIncome.shortList = [
new infoValue("HINC50_CY", "under 75k"),
new infoValue("HINC75_CY,HINC100_CY", "75k to 150k"),
new infoValue("HINC150_CY,HINC200_CY", "100k and above")
];
this.sources.netWorth.shortList = [
new infoValue("NW0_CY,NW15_CY,NW35_CY", "under 50k"),
new infoValue("NW50_CY,NW75_CY,NW100_CY", "50k to 150k"),
new infoValue("NW150_CY,NW250_CY,NW500_CY", "150k and above")
];
this.sources.homeValue.shortList = [
new infoValue("VAL50K_CY,VAL100K_CY", "under 150k"),
new infoValue("VAL150K_CY,VAL200K_CY,VAL250K_CY,VAL300K_CY", "150k to 500k"),
new infoValue("VAL400K_CY,VAL1M_CY", "500k and above")
];
// initialize current location, extent
this.extent = new esri.geometry.Extent({
xmin: -10392864, ymin: 4444140,
xmax: -7423438, ymax: 5422534,
spatialReference: { wkid: 102100} });
// go get the data
this.locationName = "";
this.onGotData = null;
this.getData();
}
/**
* Updates the current extent.
*/
viewModel.prototype.setExtent = function (extent) {
if (this.extent != extent) {
var sameExtent =
extent.xmin == this.extent.xmin && extent.ymin == this.extent.ymin &&
extent.xmax == this.extent.xmax && extent.ymax == this.extent.ymax;
if (!sameExtent) {
this.extent = extent;
this.getData();
}
}
}
/**
* Get the current location (lat, lon, name).
*/
viewModel.prototype.getLocation = function () {
var ptm = this.extent.getCenter();
var ptg = esri.geometry.webMercatorToGeographic(ptm);
return {
lat: ptg.y,
lon: ptg.x,
name: this.locationName ? this.locationName : "Please select a location within the USA.",
isValid: this.locationName != null };
}
/**
* Get a description for an index (100: national average, 50 is half, 200 is double, etc)
*/
viewModel.prototype.getIndexDescription = function (index) {
var desc =
index < 50 ? "substantially lower" :
index < 80 ? "lower" :
index < 100 ? "slightly lower" :
index < 120 ? "slightly higher" :
index < 200 ? "higher" :
"substantially higher";
return desc + " than the national average";
}
/**
* Inform listeners that new data has arrived.
*/
viewModel.prototype.gotData = function () {
// get location name from age layer
this.locationName = this.sources.age.getLocationName();
// get dominant tapestry description
var domTap = this.sources.tapestry.values.DOMTAP.value;
this.domTapDescription = getTapestryDescription(domTap);
// notify listeners of the changes
if (this.onGotData) {
clearTimeout(this.dataTimer);
this.dataTimer = setTimeout(this.onGotData, 200);
};
}
/**
* Updates the information in all InfoValues that have subscribers attached to them
* based on the location defined by a given map extent.
*/
viewModel.prototype.getData = function () {
// update info scale
this.infoScale = 4; // state level
if (this.extent) {
if (this.extent.getWidth() < 2e7) {
this.infoScale = 3; // county level
}
if (this.extent.getWidth() < 2e6) {
this.infoScale = 2; // tract level
}
}
// update all infoValues
for (member in this.sources) {
var source = this.sources[member];
source.getData();
}
}
/***********************************************************************************
* infoSource class.
* The infoSource belongs to a ViewModel and provides information about a specific
* demographic for the parent ViewModel's current extent.
* @constructor
*/
function infoSource(model, shortUrl, keys, listKeys, trimName) {
this.model = model; // owner model
this.shortUrl = shortUrl; // url used to retrieve data/tiles
this.trimName = trimName; // remove this part from item names
this.values = {}; // object that contains the values
this.list = []; // list with range values
// get start/end list keys
var arr = listKeys != null ? listKeys.split(',') : null;
var startKey = arr != null ? arr[0] : null;
var endKey = arr != null ? arr[1] : null;
// keys used to query/store values
keys = "NAME,ST_ABBREV," + keys;
var arr = keys.split(',');
var addToList = false;
for (var i = 0; i < arr.length; i++) {
var key = arr[i];
// add to values object
var val = new infoValue(key);
this.values[key] = val;
// add to list
if (!addToList && key == startKey) {
addToList = true;
}
if (addToList) {
this.list.push(val);
}
if (addToList && key == endKey) {
addToList = false;
}
}
// use service to get key descriptions
var url = this.getSchemaUrl();
var self = this;
$.ajax({
url: url,
dataType: "jsonp",
success: function (data) {
if (data.layers) {
var result = data.layers[1].fields;
for (var i = 0; i < result.length; i++) {
var entry = result[i];
var iv = self.values[entry.name];
if (iv != null) {
var name = entry.alias;
if (name.indexOf(self.trimName) == 0) {
name = name.substring(self.trimName.length);
}
var pos = name.indexOf(" (Esri)");
if (pos > 0) {
name = name.substring(0, pos);
}
iv.name = name.trim();
}
}
}
}
});
}
/**
* Updates the information in this infoValue.
*/
infoSource.prototype.getData = function () {
// go update the values
if (this.model.extent) {
// build query/fields to retrieve
var query = new esri.tasks.Query();
query.geometry = this.model.extent.getCenter();
query.outFields = [];
for (var key in this.values) {
query.outFields.push(key);
}
// run query
var url = this.getQueryUrl();
var queryTask = new esri.tasks.QueryTask(url);
var self = this;
dojo.connect(queryTask, "onComplete", function (featureSet) { self.gotData(featureSet); });
queryTask.execute(query);
}
}
/**
* After getting values from ESRI service, store them in this infoSource.
*/
infoSource.prototype.gotData = function (featureSet) {
if (featureSet.features.length > 0) {
// get attributes
var atts = featureSet.features[0].attributes;
// update values in our data object
for (var key in this.values) {
var infoValue = this.values[key];
infoValue.value = atts[key];
}
// update summary info values
if (this.shortList != null) {
for (var i = 0; i < this.shortList.length; i++) {
var value = 0;
var keys = this.shortList[i].key.split(",");
for (var j = 0; j < keys.length; j++) {
var iv = this.values[keys[j]];
if (iv && iv.value) {
value += iv.value;
}
}
this.shortList[i].value = value;
}
}
} else {
// no data available: clear values
for (key in this.values) {
var infoValue = this.values[key];
infoValue.value = null;
}
}
// inform model that we got new data
this.model.gotData();
}
/**
* Get the location name for this info source.
*/
infoSource.prototype.getLocationName = function () {
return this.values.NAME.value
? this.values.NAME.value + ", " + this.values.ST_ABBREV.value
: null;
}
// format used to build service urls
infoSource.prototype.URL_FORMAT =
"http://services.arcgisonline.com:80/ArcGIS/rest/services/Demographics/SHORT_URL/MapServer";
// build url for getting the tiles for this infoSource
infoSource.prototype.getTileUrl = function () {
return this.URL_FORMAT.replace("SHORT_URL", this.shortUrl);
}
// build url for querying data for the current scale
infoSource.prototype.getQueryUrl = function () {
return this.getTileUrl() + "/" + this.model.infoScale;
}
// build url for querying data for the data schema
infoSource.prototype.getSchemaUrl = function () {
return this.getTileUrl() + "/layers?f=json";
}
/***********************************************************************************
* Initializes a new instance of a infoValue.
* infoValue objects have a key, a name, and a value.
* @constructor
*/
function infoValue(key, name) {
this.key = key;
this.name = name ? name : "";
this.value = 0;
}
/**************************************************************************************
* Tapestry segment descriptions from
* http://www.esri.com/library/brochures/pdfs/tapestry-segmentation.pdf
*/
function getTapestryDescription(index) {
var desc = [
"",
"Mature, married, highly educated, and wealthy.",
"Families who live in growing suburban neighborhoods.",
"Closer to retirement than child-rearing age, 30 percent are married couples with children living at home.",
"Busy, affluent young families",
"Older, established, affluent neighborhoods characteristic of US coastal metropolitan areas.",
"Cultured country life on the urban fringe: accept longer commutes to live near fewer neighbors.",
"Affluent lifestyle in open spaces beyond the urban fringe. Forty percent are empty nesters.",
"Enjoy single life in the big city: no home ownership or child-rearing responsibilities.",
"Professionals who live a sophisticated, exclusive lifestyle. More than half are married-couple families.",
"Prosperous domesticity, settled lives, especially middle-aged married couples.",
"Upscale neighborhoods in Pacific coastal cities: more than 75% are families.",
"A mix of Generation Xers and Baby Boomers, the youngest affluent family markets.",
"Live in the suburbs but prefer the city lifestyle. Mostly professional couples.",
"Enjoying the move from child-rearing to retirement.",
"More than 70 percent are aged 55 years or older. Most residents have retired from professional occupations.",
"Young, educated, working professionals, have a median age of 32.4 years.",
"Married couples, many are blue-collar Baby Boomers with children aged 6–17 years.",
"Middle-aged married couples who are comfortably settled in their single family homes in older neighborhoods.",
"Upscale, young, affluent married couples who are starting their families.",
"Diverse, dense neighborhoods situated primarily in the Northeast.",
"Multicultural enclaves of young families, unique to densely populated cities in “gateway” states, primarily California.",
"Prefer to live in older city neighborhoods. Approximately half of these households are singles.",
"Cutting edge of urban style: young, diverse, and mobile. More than half the households are singles.",
"A mix of household types similar to the US distribution. Approximately half of the households are composed of married-couple families.",
"Sixty-five percent are married couples with and without children. Twenty percent are singles.",
"The growing population of 12 million makes this the largest tapestry segment. Sixty-two percent of the households are married couple families; half of them have children.",
"Young, educated singles, just beginning their professional careers in some of the largest US cities.",
"Young, startup families, married couples with or without children, and single parents.",
"Married couples with no children or singles who live alone.",
"Mostly single seniors who live alone; a fourth is married couples with no children living at home.",
"Pastoral settings in rural non-farm areas throughout the United States.",
"Primarily a mix of married couple families, single parents, and singles who live alone.",
"Scattered in suburbs across the country, these neighborhoods are found more frequently in the South and Midwest.",
"Family is the cornerstone of life in these neighborhoods that are a mix of married couples, single parents, grandparents, and young and adult children.",
"Located primarily in cities in “gateway” states on both US coasts; developing urban markets with a rich blend of cultures and household types.",
"Either beginning their careers or retiring. They range in age from their 20s to 75 and older.",
"Small, family-owned farms in the Midwest dominate this stable market.",
"Family is central to this group; slightly more than half of the households have children.",
"Change is the constant for this group, an on-the-go population has a median age of 28.6 years.",
"Young, married, and beginning parenthood. Ninety-two percent of the householders are younger than 45 years. ",
"Growing communities in small towns in the South, Midwest, and West. Married couples and single parents are the primary household types in these areas.",
"Found primarily in the rural South, these households consist of married couples with and without children, 87% white.",
"Eighty percent of the householders are aged 65 years or older, 97% are white.",
"Recently settled immigrants: more than half of the population is foreign born.",
"Young, relatively diverse urban market; almost 80% are black.",
"Slightly older than average, with a median age of 42.6 years; 50 percent are older than 55.",
"The latest wave of western 'pioneers'. Nearly half were born outside the United States; 84 percent are Hispanic.",
"Young singles who live alone and married-couple families; the median age is 33.3 years.",
"Among the fastest growing in the nation (1.7% annually). Their median age is 53.6 years.",
"Settled and close-knit, with a median age of 42.8 years, half of them have already retired.",
"Married couples, single parents, and multi-generational families are the most common household types in these regions.",
"A microcosm of urban diversity; their population is represented primarily by white, black, and Hispanic cultures.",
"A mix of married-couple families, singles who live alone, and single-parent families. The median age for this group is 34.5 years.",
"The smallest of all Tapestry segments, still shrinking due to urban renewal programs. The median age is 33.6 years.",
"Most residents are aged between 18 and 34 years and live in single-person or shared households.",
"Half of the households consist of married-couple families, 15 percent are single-parent families.",
"With a median age of 41.3 years, this market is slightly older than the US median of 37 years.",
"Three-quarters of the population in this family-oriented segment is Hispanic.",
"These young families form the foundation of Hispanic life in the Southwest. Children are the center of these households.",
"Diversity in household type and ethnicity characterizes this segment. Most of these residents are young, with a median age of 29.2 years.",
"A diverse mix of race and ethnicity. More than half of the residents are Hispanic, mainly from Puerto Rico or the Dominican Republic.",
"Eighty-three percent of the residents in this segment are black. Single-person and single-parent household types are predominant.",
"Seventy-nine percent of the residents are enrolled in a college or university.",
"Single-parent families or singles who live alone comprise most of these very young households.",
"Four in ten householders are aged 65 years or older; the median age is 46.4 years. Most of them live alone. ",
"Unclassified (include areas such as parks, golf courses, open spaces, or other types of undeveloped land).",
];
return desc[index];
}
|
/* See license.txt for terms of usage */
// ********************************************************************************************* //
// Constants
var EXPORTED_SYMBOLS = ["FirebugLoader"];
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://firebug/fbtrace.js");
// ********************************************************************************************* //
function loadSubscript(src, win)
{
return Services.scriptloader.loadSubScript(src, win);
}
// ********************************************************************************************* //
var FirebugLoader =
{
bootstrapScopes: [],
registerBootstrapScope: function(e)
{
if (this.bootstrapScopes.indexOf(e) != -1)
return;
this.bootstrapScopes.push(e);
this.forEachWindow(function(win)
{
e.topWindowLoad(win);
if (!win.Firebug.isInitialized)
return;
e.firebugFrameLoad(win.Firebug);
});
},
unregisterBootstrapScope: function(e)
{
var i = this.bootstrapScopes.indexOf(e);
if (i >= 0)
this.bootstrapScopes.splice(i, 1);
if (e.topWindowUnload)
{
this.forEachWindow(function(win)
{
e.topWindowUnload(win);
});
}
if (e.firebugFrameUnload)
{
this.forEachWindow(function(win)
{
e.firebugFrameUnload(win.Firebug);
});
}
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
startup: function()
{
// allow already started bootstrapped firebug extensions to register themselves
// xxxHonza: The try-catch statement can be removed as soon as Firefox 30 (Fx30)
// is the minimum required version (see also issue 7208).
var XPIProviderBP;
try
{
XPIProviderBP = Cu.import("resource://gre/modules/addons/XPIProvider.jsm", {});
}
catch (err)
{
XPIProviderBP = Cu.import("resource://gre/modules/XPIProvider.jsm", {});
}
var bootstrapScopes = XPIProviderBP.XPIProvider.bootstrapScopes;
for (var id in bootstrapScopes)
{
var scope = bootstrapScopes[id];
try
{
if (scope.firebugStartup)
scope.firebugStartup(this);
}
catch(e)
{
Cu.reportError(e);
}
}
},
shutdown: function()
{
this.forEachWindow(function(win)
{
FirebugLoader.unloadFromWindow(win);
});
},
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
unloadFromWindow: function(win)
{
var fbug = win.Firebug;
this.dispatchToScopes("topWindowUnload", [win]);
if (fbug.shutdown)
{
fbug.closeFirebug();
fbug.shutdown();
}
function getRoots(el)
{
return Array.slice(el.querySelectorAll("[firebugRootNode]"));
}
[getRoots(win.document), getRoots(win.gNavToolbox.palette),
fbug.browserOverlay.nodesToRemove].forEach(function(list)
{
for (var i=0; i<list.length; i++)
{
var el = list[i];
if (el && el.parentNode)
el.parentNode.removeChild(el);
}
});
win.Firebug.browserOverlay.stopFirebug();
delete win.Firebug;
delete win.FBTrace;
delete win.FBL;
},
loadIntoWindow: function(win, reason)
{
// This is the place where the global Firebug object is created. This object represents
// the entire application and all consequently created namespaces and variables should be
// injected into it.
// In the future, there should *not* be any other globals except of the Firebug object.
// xxxHonza: properties from this object are copied into the new Firebug obect that is
// created within "firebug/firebug" module (a hack).
win.Firebug = {};
var requireScope = {};
Cu.import("resource://firebug/mini-require.js", requireScope);
var require = requireScope.require;
var config = {
baseUrl: "resource://",
paths: {"firebug": "chrome://firebug/content"}
};
require(config, [
"firebug/firefox/browserOverlay"
],
function(BrowserOverlay)
{
var overlay = win.Firebug.browserOverlay = new BrowserOverlay(win);
overlay.initialize(reason);
});
if (FBTrace.DBG_MODULES)
FBTrace.sysout("Basic loader dependencies: " + require.Loader.getDepDesc());
// Firebug extensions should initialize here.
this.dispatchToScopes("topWindowLoad", [win]);
},
dispatchToScopes: function(name, arguments)
{
for (var id in this.bootstrapScopes)
{
var e = this.bootstrapScopes[id];
try
{
if (name in e)
e[name].apply(e, arguments);
}
catch(e)
{
Cu.reportError(e);
}
}
},
forEachWindow: function(func)
{
var enumerator = Services.wm.getEnumerator("navigator:browser");
while (enumerator.hasMoreElements())
{
try
{
var win = enumerator.getNext();
if (win.Firebug)
func(win);
}
catch(e)
{
Cu.reportError(e);
}
}
}
};
// ********************************************************************************************* //
|
import React from 'react';
export default function Language() {
return (
<div className="topbar-menu-container">
<div className="title border">Language</div>
<div className="language-menu-container">
<div className="menu-column">
<div className="first">Global</div>
<div className="language">
<img src="/assets/images/country/English.png" alt="country" />
<span>English</span>
</div>
</div>
<div className="menu-column">
<div className="first">North & South America</div>
<div className="language">
<img src="/assets/images/country/Brazil.png" alt="country" />
<span>Brazil (Português)</span>
</div>
<div className="language">
<img src="/assets/images/country/Argentina.png" alt="country" />
<span>Argentina (Español)</span>
</div>
<div className="language">
<img src="/assets/images/country/Chile.png" alt="country" />
<span>Chile (Español)</span>
</div>
<div className="language">
<img src="/assets/images/country/Colombia.png" alt="country" />
<span>Colombia (Español)</span>
</div>
</div>
<div className="menu-column">
<div className="first">Euorope</div>
<div className="language">
<img src="/assets/images/country/France.png" alt="country" />
<span>France (Français)</span>
</div>
<div className="language">
<img src="/assets/images/country/Germany.png" alt="country" />
<span>Germany / Switzerland (Deutsch)</span>
</div>
<div className="language">
<img src="/assets/images/country/Italy.png" alt="country" />
<span>Italy (Italiano)</span>
</div>
<div className="language">
<img src="/assets/images/country/Spain.png" alt="country" />
<span>Spain (Español)</span>
</div>
<div className="language">
<img src="/assets/images/country/Russia.png" alt="country" />
<span>Russia (Русский)</span>
</div>
</div>
<div className="menu-column">
<div className="first">Asia & Australia</div>
<div className="language">
<img src="/assets/images/country/China.png" alt="country" />
<span>China (中文版)</span>
</div>
<div className="language">
<img src="/assets/images/country/Korea.png" alt="country" />
<span>Korea (한국어)</span>
</div>
<div className="language">
<img src="/assets/images/country/Japan.png" alt="country" />
<span>Japan (日本語)</span>
</div>
</div>
</div>
</div>
);
}
|
/* eslint-disable no-undef */
const chai = require('chai');
const chaiHttp = require('chai-http');
const mongoose = require('mongoose');
const { server } = require('../../index');
const { BASE_PATH } = require('../../config/env');
const { User } = require('../../models/user');
const { expect } = chai;
const should = chai.should();
chai.use(chaiHttp);
/**
* NB: The Get /users has been tested,
* some code repeated in some test cases, example: token variable
* later it will be refactored and cleaned up
*/
describe(`${BASE_PATH}/users`, () => {
after(async () => {
await mongoose.connection.dropDatabase();
await mongoose.connection.close();
});
describe('List all users ::: Get: /users', () => {
afterEach(async () => {
await User.deleteMany({});
});
beforeEach(async () => {
await User.deleteMany({});
});
// ***Test Summary for GET: /users***
// It should return 401
// - if not token provided
// - if token length is less than 10 characters
// it should return status of 200
// it should returns all users
// it should return 404 when user(s) does not exist
it('should return 401 if not token or if token is less than 10 characters', async () => {
const token = '';
const user = new User({
firstName: 'ezeh',
lastName: 'Livinus',
password: '123456',
email: 'ezeh@mail.com'
});
await user.save();
const res = await chai.request(server)
.get(`${BASE_PATH}/users`)
.set({ token });
expect(res.status).to.equal(401);
expect(res.body.status).to.equal(false);
expect(res.body).to.have.property('message');
});
it('should return status of 200', async () => {
const user = new User({
firstName: 'ezeh',
lastName: 'Livinus',
password: '123456',
email: 'ezeh@mail.com'
});
await user.save();
const token = user.generateAuthToken();
const res = await chai.request(server)
.get(`${BASE_PATH}/users`)
.set({ token });
expect(res.status).to.equal(200);
expect(res.body.status).to.equal(true);
});
it('should return all users', async () => {
const data = [
{
firstName: 'ezeh',
lastName: 'Livinus',
password: '123456',
email: 'ezeh@mail.com'
},
{
firstName: 'Mark',
lastName: 'John',
password: '123456',
email: 'mark@Gmail.com'
},
{
firstName: 'Steven',
lastName: 'McConnel',
password: '123456',
email: 's.connel@mail.com'
}
];
const users = await User.insertMany(data);
const token = users[0].generateAuthToken();
const res = await chai.request(server)
.get(`${BASE_PATH}/users`)
.set({ token });
res.body.should.be.an('object');
res.body.should.have.property('data');
res.body.data.should.be.an('array');
res.body.data.should.have.lengthOf(3);
expect(res.body).to.have.property('message');
expect(res.body.status).to.equal(true);
expect(res.body.data[0]).to.have.property('email');
});
it('should return 404 when user(s) does not exist', async () => {
const payload = {
_id: mongoose.Types.ObjectId().toHexString(),
email: 'test@email.com',
role: 'user'
};
const user = new User(payload);
const token = user.generateAuthToken();
const res = await chai.request(server)
.get(`${BASE_PATH}/users`)
.set({ token });
expect(res.status).to.equal(404);
res.body.should.be.a('object');
res.body.should.have.property('status');
expect(res.body.status).to.equal(false);
});
});
describe('Retrieve a user ::: Get: /users/:id', () => {
// same as above for Get: /users
// but now with user id and res.body.data of type object
});
describe('Create a user ::: Post: /users', () => {});
describe('Update a user ::: Update: /users/:id', () => {});
describe('Delete a user ::: Delete: /users/:id', () => {});
});
|
import {slider} from './modules/slider';
import {startActionTimer} from './modules/startActionTimer';
import {showTabs} from './modules/showTabs';
import {modal, showModalElement} from './modules/modal';
import {calculate} from './modules/caclulate';
import {getFetch} from './modules/service/fetFetch';
import {CreateMenuItem} from './modules/CreateMenuClass';
import forms from './modules/form';
document.addEventListener('DOMContentLoaded', ()=>{
showTabs('.tabheader__items', '.tabheader__item');
startActionTimer('2021-04-12', 'days', 'hours', 'minutes', 'seconds');
const timerModal = setTimeout(() => showModalElement('.modal', timerModal), 5000);
modal('.modal','.modal__close','.js-modal',timerModal);
calculate();
getFetch('http://localhost:3000/menu')
.then((data) => {
data.forEach(({img, altimg, title, descr, price}) => {new CreateMenuItem(img, altimg, title, descr, price,'.menu__field .container' ).render()})
});
forms('form');
slider({controlSelector:'.offer__slider-counter' , slElemsSelector: '.offer__slide', totalValueSelector: '#total', curentValueSelector: '#current', slWrapperSelector: '.offer__slider'});
// const tabs = document.querySelector('.tabheader__items');
// const tabElements = tabs.querySelectorAll('.tabheader__item');
// const tabContents = document.querySelectorAll('.tabcontent');
// const showTabContents = (index = 0) => {
// tabContents.forEach(item =>{
// item.classList.remove('show')
// })
// tabContents[index].classList.add('show');
// tabElements.forEach(item =>{
// item.classList.remove('tabheader__item_active')
// })
// tabElements[index].classList.add('tabheader__item_active');
// };
// showTabContents();
// tabs.addEventListener('click', (event) =>{
// const target = event.target;
// if (!target.matches('.tabheader__item')) return;
// tabElements.forEach((item, index)=>{
// if(target != item) return;
// showTabContents(index);
// })
// })
// Timer
// let dedline = '2021-04-12';
// function getActionTime(endtime){
// const totalSeconds = Math.floor((new Date(endtime)-new Date())/1000);
// const days = convertTime(Math.floor(totalSeconds/(3600*24)));
// const hours = convertTime(Math.floor((totalSeconds/3600)%24));
// const minutes = convertTime(Math.floor((totalSeconds/60)%60));
// const seconds = convertTime(Math.floor(totalSeconds%60));
// return {totalSeconds, days, hours, minutes, seconds};
// }
// function convertTime(time){
// return time>=10 ? `${time}` : `0${time}`;
// }
// function getArrayElementsByID(...arr){
// return arr.map(item =>{
// return document.getElementById(item)
// })
// }
// function setActionDate(){
// const [day, hour, minute, second] = getArrayElementsByID('days', 'hours', 'minutes', 'seconds');
// const {totalSeconds, days, hours, minutes, seconds} = getActionTime('2021-04-12');
// if (totalSeconds==0)return null;
// day.innerHTML=`${days}`;
// hour.innerHTML=`${hours}`;
// minute.innerHTML=`${minutes}`;
// second.innerHTML=`${seconds}`;
// }
// function startActionTimer () {
// setActionDate();
// let intervalID = setInterval(setActionDate, 1000);
// if(setActionDate()===null) {
// clearInterval(intervalID)
// }
// }
// //Modal
// const modalOpen = document.querySelectorAll('.js-modal');
// const modalWrapper = document.querySelector('.modal');
// const modalClose = document.querySelector('.modal__close');
// function showModalElement(){
// if(modalWrapper.classList.contains('show')) return;
// modalWrapper.classList.toggle('show');
// document.body.style.overflow='hidden';
// clearTimeout(timerModal);
// }
// function closModalElement(){
// if (!modalWrapper.classList.contains('show')) return;
// modalWrapper.classList.toggle('show');
// document.body.style.overflow='';
// }
// function showModalElementScroll(){
// if(document.documentElement.clientHeight + pageYOffset == document.documentElement.scrollHeight){
// showModalElement();
// window.removeEventListener('scroll', showModalElementScroll);
// }
// }
// window.addEventListener('keydown', (event)=>{
// if (event.key !== 'Escape') return;
// closModalElement();
// })
// window.addEventListener('scroll', showModalElementScroll);
// modalWrapper.addEventListener('click', (event)=>{
// const target = event.target;
// if (target !== modalClose && target !== modalWrapper) return;
// closModalElement();
// })
// modalOpen.forEach(item =>{
// item.addEventListener('click', showModalElement)
// })
// const timerModal = setTimeout(showModalElement, 5000);
//Class для конструирования меню
// async function getFetch(url){
// const response = await fetch(url);
// if (!response.ok){
// throw new Error(`При выполнении Вашего запроса произошла ошибка. Статутус ошибки: ${response.status}, URL ошибки: ${url}`);
// }
// return await response.json();
// }
// class CreateMenuItem{
// constructor(src, alt, title, description, prise, parentNode, transferCource = 27, ...classes){
// this.src = src;
// this.alt = alt;
// this.title = title;
// this.description = description;
// this.prise = prise*transferCource;
// this.classes = (classes.length===0) ? ["menu__item"] : classes;
// this.parentNode = document.querySelector(parentNode);
// }
// render(){
// const {src, alt , title, description, prise, parentNode, classes} = this;
// const div = document.createElement('div');
// classes.forEach(item => div.classList.add(item));
// div.innerHTML = `
// <img src=${src} alt=${alt} />
// <h3 class="menu__item-subtitle">${title}</h3>
// <div class="menu__item-descr">${description}</div>
// <div class="menu__item-divider"></div>
// <div class="menu__item-price">
// <div class="menu__item-cost">Цена:</div>
// <div class="menu__item-total"><span>${prise}</span> грн/день</div>
// </div>`
// parentNode.prepend(div);
// }
// }
//Form requare
// const modalDialog = document.querySelector('.modal .modal__dialog')
// const forms = document.querySelectorAll('form');
// forms.forEach(item => sendFormsData(item));
// const serviseMessage = {
// loading: ['Запрос обрабатывается', 'img/spinner.svg'],
// load: 'Данные успешно отправлены. Мы вам перезвоник в течение 30 минут',
// error: 'При отправке данных произошла ошибка. Проверьте правильность заполения формы и повторите отправку'
// }
// async function postFetch(url, data){
// const response = await fetch(url, {
// method: 'POST',
// headers: {
// 'Content-type': 'application/json',
// },
// body: data,
// });
// if (!response.ok){
// throw new Error(`При выполнении Вашего запроса произошла ошибка. Статутус ошибки: ${response.status}, URL ошибки: ${url}`)
// }
// return await response.json();
// }
// function sendFormsData(form){
// form.addEventListener('submit', (e) =>{
// e.preventDefault();
// showMessageModal(null, form, serviseMessage.loading)
// const formData = new FormData(form);
// const json = JSON.stringify(Object.fromEntries(formData.entries()));
// postFetch('http://localhost:3000/requests', json)
// .then(data =>{
// console.log(data);
// showMessageModal(data, form, serviseMessage.load)
// })
// .catch(() =>{
// showErrorModalMessage(form, serviseMessage.error)
// });
// })
// }
// function showErrorModalMessage(form, message){
// const modalMessage = document.querySelector('.modal__content');
// const messageModal = document.createElement('div');
// messageModal.classList.add('modal__content');
// showModalElement('.modal');
// modalMessage.style.display = "none";
// messageModal.innerHTML = `<div class="modal__title">${message}</div>`;
// modalDialog.append(messageModal);
// const timerReq = setTimeout(()=>{messageModal.remove(); form.reset(); modalMessage.style.display = ""; closModalElement('.modal');clearTimeout(timerReq)}, 4000)
// }
// function showMessageModal(data, form, message){
// const modalMessage = document.querySelector('.modal__content');
// const messageModal = document.createElement('div');
// messageModal.classList.add('modal__content');
// showModalElement('.modal');
// modalMessage.style.display = "none";
// if (data===null){
// messageModal.innerHTML = `<div class="modal__title">${message[0]}</div><img src = ${message[1]} width="38px" height="38px">`;
// return
// }
// messageModal.innerHTML = `<div class="modal__title">${message}</div>`;
// modalDialog.append(messageModal);
// const timerReq = setTimeout(()=>{messageModal.remove(); form.reset(); modalMessage.style.display = ""; closModalElement('.modal');clearTimeout(timerReq)}, 4000)
// }
//Slider
// const slider = document.querySelector('.offer__slider')
// const sliderControl = document.querySelector('.offer__slider-counter');
// const sliderElements = document.querySelectorAll('.offer__slide');
// const sliderTotalCauntElement = document.querySelector('#total');
// sliderTotalCauntElement.innerHTML = sliderElements.length>10 ? sliderElements.length : `0${sliderElements.length}`;
// const sliderCurentElem = document.querySelector('#current');
// showSlideElement(+sliderCurentElem.innerHTML);
// createDotSlider(slider, sliderElements.length);
// showActiveDot(+sliderCurentElem.innerHTML);
// sliderControl.addEventListener('click', (event)=>{
// let sliderCurent = +sliderCurentElem.innerHTML;
// let sliderTotal = +sliderTotalCauntElement.innerHTML;
// if(event.target.matches('.offer__slider-prev')){
// if(sliderCurent == 1){
// sliderCurent = sliderTotal;
// showSlideElement(sliderCurent);
// showActiveDot(sliderCurent)
// }else{
// sliderCurent--;
// showSlideElement(sliderCurent);
// showActiveDot(sliderCurent)
// }
// }else if (event.target.matches('.offer__slider-next')){
// if(sliderCurent == sliderTotal){
// sliderCurent=1;
// showSlideElement(sliderCurent);
// showActiveDot(sliderCurent)
// }else {
// sliderCurent++;
// showSlideElement(sliderCurent);
// showActiveDot(sliderCurent)
// }
// }
// sliderCurent = sliderCurent>10 ? sliderCurent : `0${sliderCurent}`;
// sliderCurentElem.innerHTML = sliderCurent;
// })
// function showSlideElement(index=1){
// sliderElements.forEach(element => {element.classList.remove('show'); element.classList.add('hide')})
// index--;
// sliderElements[index].classList.remove('hide');
// sliderElements[index].classList.add('show');
// }
// function createDotSlider(parentNode,count){
// const dotContainer = document.createElement('ol');
// dotContainer.style.cssText = `position: absolute;
// right: 0;
// bottom: 0;
// left: 0;
// z-index: 15;
// display: flex;
// justify-content: center;
// margin-right: 15%;
// margin-left: 15%;
// list-style: none;`;
// for (let i = 0; i<count; i++){
// let li = document.createElement('li')
// li.style.cssText= `box-sizing: content-box;
// flex: 0 1 auto;
// width: 30px;
// height: 6px;
// margin-right: 3px;
// margin-left: 3px;
// cursor: pointer;
// background-color: #fff;
// background-clip: padding-box;
// border-top: 10px solid transparent;
// border-bottom: 10px solid transparent;
// opacity: .5;
// transition: opacity .6s ease;`;
// dotContainer.append(li);
// }
// parentNode.append(dotContainer);
// }
// function showActiveDot(index){
// const dots = document.querySelectorAll('.offer__slider ol li');
// dots.forEach(element =>{
// element.style.opacity = 0.5;
// })
// index--
// dots[index].style.opacity = 1;
// }
// //Calculate
// let sex = 'female', height, weight, age, optionActivity = 1.2;
// function calculateCall(){
// let result = document.querySelector('.calculating__result span');
// if(!sex||!height||!weight||!age||!optionActivity){
// result.textContent = '____';
// return;
// }
// if (sex == 'female'){
// result.textContent = Math.round((655 + 9.5*weight + 1.8*height - 4.7*age) * optionActivity);;
// }else{
// result.textContent = Math.round((66 + 13.7*weight + 5*height - 6.76*age) * optionActivity);
// }
// }
// function getInputValue(){
// const calculateInputs = document.querySelector('.calculating__choose.calculating__choose_medium');
// calculateInputs.addEventListener('input', (event)=>{
// const target = event.target;
// if (!target.matches('.calculating__choose-item')) return;
// switch (target.id){
// case "height":
// height = +target.value;
// break;
// case "weight":
// weight = +target.value;
// break;
// case "age":
// age = +target.value;
// break;
// };
// calculateCall();
// })
// }
// function getCalculateValue(){
// const sexValue = document.getElementById('gender');
// const sexElements = sexValue.querySelectorAll('div');
// sexValue.addEventListener('click', (event)=>{
// let target = event.target;
// if (!target.matches('.calculating__choose-item'))return;
// sexElements.forEach(elem => elem.classList.remove('calculating__choose-item_active'));
// if (target.id == 'female'){
// sex = target.id;
// }else if (target.id == 'male'){
// sex = target.id;
// }
// target.classList.add('calculating__choose-item_active');
// calculateCall();
// })
// const optionElem = document.querySelector('.calculating__choose.calculating__choose_big');
// const optElements = optionElem.querySelectorAll('div');
// optionElem.addEventListener('click', (event)=>{
// let target = event.target;
// if (!target.matches('.calculating__choose-item'))return;
// optElements.forEach(elem => elem.classList.remove('calculating__choose-item_active'));
// switch (target.id){
// case "low":
// optionActivity = 1;
// break;
// case "small":
// optionActivityht = 1.2;
// break;
// case "medium":
// optionActivity = 1.3;
// break;
// case "high":
// optionActivity = 1.6;
// break;
// };
// target.classList.add('calculating__choose-item_active');
// calculateCall();
// })
// }
// getCalculateValue();
// getInputValue();
});
|
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import ApolloClient from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloProvider } from "react-apollo";
import { setContext } from "apollo-link-context";
import { I18nextProvider } from "react-i18next";
import { createUploadLink } from "apollo-upload-client";
import { WebSocketLink } from "apollo-link-ws";
import { getMainDefinition } from "apollo-utilities";
import { split } from "apollo-link";
import { onError } from "apollo-link-error";
import "bootstrap-css-only/css/bootstrap.min.css";
import "font-awesome/css/font-awesome.min.css";
import "semantic-ui-css/semantic.min.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "./index.scss";
import i18n from "./i18n";
const cache = new InMemoryCache({
dataIdFromObject: (o) => `${o.__typename}-${o.id}`,
});
const httpLink = new createUploadLink({
uri: process.env.REACT_APP_GRAPHQL_ENDPOINT,
});
console.log("QQQQQQQ", process.env.REACT_APP_GRAPHQL_WEBSOCKET);
const wsLink = new WebSocketLink({
uri: process.env.REACT_APP_GRAPHQL_WEBSOCKET,
options: {
reconnect: true,
connectionParams: {
authToken: localStorage.getItem("token"),
},
},
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) => {
if (
!message.includes(
"You do not have permission to perform this action"
) &&
!message.includes("could not convert string to float:") &&
!message.includes(
'Variable "$postId" of required type "ID!" was not provided.'
)
) {
// window.location.replace(SERVER_ERROR);
} else {
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
);
}
});
if (networkError) console.log(`[Network error]: ${networkError}`);
});
const authLink = setContext((_, { headers }) => {
let data = JSON.parse(localStorage.getItem("token"));
data = data && data.token === "token" ? "" : data;
return {
headers: {
...headers,
authorization: data ? `Bearer ${data.token}` : "",
},
};
});
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === "OperationDefinition" && operation === "subscription";
},
wsLink,
authLink.concat(httpLink)
);
const client = new ApolloClient({
link: link, //errorLink.concat(authLink.concat(httpLink)),
cache: cache.restore(window.__APOLLO_STATE__ || {}),
});
ReactDOM.render(
<ApolloProvider client={client}>
<BrowserRouter>
<I18nextProvider i18n={i18n}>
<App />
</I18nextProvider>
</BrowserRouter>
</ApolloProvider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
|
import Sequelize from "sequelize";
// const sequelize = new Sequelize(
// 'ambevapp', 'postgres', 'Wsi@@2021', {
// dialect: "postgres",
// define: {
// timestamps: false
// }
// }
// );
const sequelize = new Sequelize(
"postgres://postgres:Wsi@@2021@34.204.162.68/ambevapp",
{
dialect: "postgres",
define: {
timestamps: false
}
}
);
export default sequelize;
|
import React from 'react'
import Typography from '@material-ui/core/Typography'
class Fetching extends React.PureComponent {
render() {
return (
<Typography>
Loading record...
</Typography>
)
}
}
export default Fetching
|
import firebase from "firebase";
const firebaseConfig = {
apiKey: "AIzaSyBoxhAbjrkVNmrJTPJF7JxZcHB6WAv-p9I",
authDomain: "clone-ee23e.firebaseapp.com",
projectId: "clone-ee23e",
storageBucket: "clone-ee23e.appspot.com",
messagingSenderId: "875878599296",
appId: "1:875878599296:web:0ed97c57ead917c16c3465",
measurementId: "G-L57VJE6BST"
};
const firebaseApp = firebase.initializeApp(firebaseConfig)
const db = firebaseApp.firestore();
const auth = firebase.auth();
export {db, auth};
|
import axios from "axios";
import { TOGGLE_LIKE_SUCCESS } from "../ActionTypes/likeTypes";
/**
* Likes/Unlikes a post.
* @param {string} postId - Id of the post to toggle like.
*/
export const togglePostLike =
(postId = "") =>
async (dispatch) => {
try {
const { data } = await axios("/post-likes", {
method: "POST",
data: {
postId,
},
});
dispatch({
type: TOGGLE_LIKE_SUCCESS,
payload: {
data,
},
});
} catch (error) {
console.log(error);
}
};
|
$(function(){
//Kitap Bilgileri
//listelerim
$.getJSON("listPageControl.php", function(sonuc){
$.each(sonuc, function(i, sonuc){
var veri = '<tr><td><a onclick="getListDetail('+sonuc.listId+')"><i class="fa fa-book">'+ sonuc.listName +'</a></td><td>'+ conv(sonuc.startingDate) +'</td><td>'+ conv(sonuc.finishingDate) +'</td><td><span class="label label-success">işlem</span></td></tr>';
$("#listsInfo").append(veri);
});
});
//Kitap Bilgileri Bitiş
function conv(time){
var date = new Date(time*1000);
var month = new Array("Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık");
var day = new Array("Pz","Pzt","Sal","Çar","Per","Cum","Cmt");
var m =date.getMonth();
var y =date.getFullYear();
var d=date.getDate();
var h=date.getHours();
var min=date.getMinutes();
if(min<10){
return d+" "+ month[m]+" "+y+", "+h+":0"+min;
}
return d+" "+ month[m]+" "+y+", "+h+":"+min;
}
});
function getListDetail(listId) {
console.log('hikaye');
$.ajax({
type: 'POST',
url: 'listPageControlBooks.php',
data: 'listId=' + listId,
success: function(kitap){
$("#okuduklarim").empty();
var kitap = jQuery.parseJSON(kitap);
for (var i in kitap){
sonuc=kitap[i];
var veri = '<tr><td width="75" height="" rowspan="" align="center"><a href="bookpage.php?bId='+sonuc.bookId+'"><img src="'+sonuc.frontcoverphoto+'" height="75" width="75"></a></td><td><a href="bookpage.php?bId='+sonuc.bookId+'">'+ sonuc.bookName +'</a></td><td>'+ sonuc.bookPoint+'</td><td>'+ sonuc.size+'</td><td><span class="label label-success">işlem</span></td></tr>';
$("#okuduklarim").append(veri);
}
}
});
}
|
const { rem } = require('csx/lib')
module.exports = ({
colors = {},
height = rem(6.4)
} = {}) => {
return [
{
$debugName: 'FieldInput',
color: colors.default,
padding: '.9em .75em .2em',
width: '100%',
height,
border: 'none',
outline: 'none',
overflow: 'hidden',
transition: '.2s ease opacity',
backgroundColor: 'transparent',
opacity: 0,
'.active &, .valid &, .invalid &': {
opacity: 1
},
}
]
}
|
/**
*
*/
$(document).ready(function () {
$("[class*='animate-']").each(initAnimations);
});
function initAnimations() {
var $this = $(this);
var waypoint = new Waypoint({
element: $this.get(0),
// start when it appears at the bottom
offset: '95%',
handler: function () {
// get the class and animation name out of it
var animation = $this.attr("class").match(/animate-(\w+)\b/i)[1];
var toRemove = 'animate-' + animation;
var toAdd = 'animated ' + animation;
// update classes
$this.removeClass('animate-' + animation);
$this.addClass('animated ' + animation);
// stop firing again
this.disable();
}
})
}
|
import { ENGINE_API_KEY } from '../utils/constants'
const { ApolloServer, gql } = require('apollo-server-lambda')
const { RESTDataSource } = require('apollo-datasource-rest')
const casual = require('casual')
// -------------- Datasources ---------------
class RandomUserAPI extends RESTDataSource {
constructor() {
super()
this.baseURL = 'https://api.randomuser.me/'
}
async getPerson() {
const { results } = await this.get('')
return results
}
}
const dataSources = () => ({
randomUserAPI: new RandomUserAPI(),
})
// -------------- Schema ---------------
const typeDefs = gql`
"""
QUERIES
"""
type Query {
hello: String!
persons: [Person!]!
}
"""
TYPES
"""
type Person {
gender: String
email: String
phone: Int
}
`
const mocks = {
Person: () => ({
gender: 'man',
email: casual.email,
phone: casual.phone,
}),
}
const resolvers = {
Query: {
hello: () => 'hello',
persons: (_, __, { dataSources }) => {
return dataSources.randomUserAPI.getPerson()
},
},
}
const server = new ApolloServer({
engine: {
apiKey: ENGINE_API_KEY,
},
dataSources,
typeDefs,
resolvers,
mocks,
introspection: true,
playground: true,
mockEntireSchema: false,
})
exports.handler = server.createHandler()
|
//
// This application is a simple server that responds to POST requests.
// The request will contain a chunk of data and the server
// will reply with the same data in uppercase.
//
// Usage:
// nodejs Uppercase_Server.js port
//
//
var http = require("http");
var fs = require("fs");
// Some official documentation about http.createServer
//http.createServer([requestListener])#
//Returns a new web server object.
//The requestListener is a function which is automatically added to the 'request' event. - See below
//Event: 'request'
//function (request, response) { }
//request is an instance of http.IncomingMessage and response is an instance of http.ServerResponse.
var server = http.createServer(function(req, res){
var totalData = "";
if(req.method != "POST"){
res.end();
}
req.on("data", function(chunk){
totalData += chunk;
});
// We got all the data from the client.
// Send it back as uppercase.
req.on("end", function(){
totalData = totalData.toUpperCase();
res.writeHead(200, {"content-type":"text/plain"});
res.write(totalData);
res.end();
});
});
server.listen(process.argv[2]);
|
import React, {useState, useEffect} from 'react';
import {useParams} from 'react-router-dom';
import UserFolloweeCard from "./UserFolloweeCard"
function UserFolloweeList({currentUser}){
const emptyFriendshipHolder = [
{
id: 0,
follower_id: 0,
followee_id: 0
}
]
const params = useParams()
const [followeesArr, setFolloweesArr] = useState(emptyFriendshipHolder)
const [user, setUser] = useState({})
const API = "http://localhost:3001/"
useEffect(()=>{
fetch(`${API}users/find/${params.id}`)
.then(r => r.json())
.then(userObj=>{
setFolloweesArr(userObj.followed_users)
setUser(userObj)
})
}, [params.id])
const userFollowees = followeesArr.map((followee) => {
if (followee.id === 0){
return null
} else {
return (
<UserFolloweeCard
key={followee.id}
user={user}
currentUser={currentUser}
followee={followee}
removeFollowee={removeFollowee}
/>
)
}
})
function removeFollowee(id){
const newFolloweesArr = followeesArr.filter((followee) => {
return followee.id !== id
})
setFolloweesArr(newFolloweesArr)
}
return(
<div className="user-following-list-div">
<h2>User Following List</h2>
{userFollowees.length > 0
? userFollowees
: "You haven't followed anyone yet!"
}
</div>
)
}
export default UserFolloweeList;
|
var adjustWidth;
adjustWidth = function() {
return _($(".input-append")).each(function(el, idx) {
var $el, $input, addonWidth, inputWidth;
$el = $(el);
$input = $el.find("input");
inputWidth = parseInt($input.innerWidth());
addonWidth = parseInt($el.find(".add-on").innerWidth());
return $input.css('width', inputWidth - addonWidth - 6);
});
};
$(function() {
$(".event textarea").css('height', 184);
$("input[type='datetime-local']").mask("99.99.9999 99:99");
$("form").on('submit', function(ev) {
return $(ev.currentTarget).find("[type='submit']").button('loading');
});
return $("[rel='tooltip']").tooltip();
});
'use strict';
var Users, UsersView, usersTemplate,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
usersTemplate = _.template("<ul class=\"unstyled\">\n <% _(users).each(function(user) { %>\n <li>\n <%= user.first_name + ' ' + user.last_name %>\n <a href=\"#\" rel=\"tooltip\" title=\"Approve\" data-value='approve'><i class=\"icon-ok-sign\"></i></a>\n <a href=\"#\" rel=\"tooltip\" title=\"Decline\" data-value='decline'><i class=\"icon-remove-sign\"></i></a>\n </li>\n <% }) %>\n</ul>");
Users = (function(_super) {
__extends(Users, _super);
function Users() {
return Users.__super__.constructor.apply(this, arguments);
}
Users.prototype.model = Backbone.Model;
Users.prototype.url = '/events/participants/';
Users.prototype.parse = function(response) {
this.meta = response.meta;
return response.objects;
};
return Users;
})(Backbone.Collection);
UsersView = (function(_super) {
__extends(UsersView, _super);
function UsersView() {
return UsersView.__super__.constructor.apply(this, arguments);
}
UsersView.prototype.className = 'span5';
UsersView.prototype.template = usersTemplate;
UsersView.prototype.collection = new Users;
UsersView.prototype.events = {
"click a": "resolveParticipant"
};
UsersView.prototype.initialize = function(options) {
var _this = this;
console.log(options.el);
this.collection.on('reset', function() {
return _this.render();
});
return this.collection.fetch({
data: {
event: options.event
}
});
};
UsersView.prototype.render = function() {
this.$el.hide();
this.$el.html(this.template({
users: this.collection.toJSON()
}));
console.log(this.el);
this.$el.find("a[rel='tooltip']").tooltip();
this.$el.fadeIn();
return this.el;
};
UsersView.prototype.resolveParticipant = function(ev) {
ev.preventDefault();
return console.log($(ev.currentTarget).data('value'));
};
return UsersView;
})(Backbone.View);
'use strict';
var EventorRouter,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
EventorRouter = (function(_super) {
__extends(EventorRouter, _super);
function EventorRouter() {
return EventorRouter.__super__.constructor.apply(this, arguments);
}
EventorRouter.prototype.routes = {
"events/new": "nothing",
"events/:id": "showEvent",
"events/*action": "nothing"
};
EventorRouter.prototype.nothing = function(options) {
return console.log("EventorRouter#nothing", options);
};
EventorRouter.prototype.showEvent = function(eventId) {
var usersView;
return usersView = new UsersView({
event: eventId,
el: $(".participants")
});
};
return EventorRouter;
})(Backbone.Router);
$(function() {
var eventRouter;
eventRouter = new EventorRouter();
return Backbone.history.start({
pushState: true
});
});
|
import React, { Component } from 'react';
import ReactModal from 'react-modal';
import {Button,Panel} from 'react-bootstrap';
ReactModal.setAppElement('#root')
class CustomModal extends Component {
constructor () {
super();
this.state = {
showModal: false
};
this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
}
handleOpenModal () {
this.setState({ showModal: true });
}
handleCloseModal () {
this.setState({ showModal: false });
}
render () {
return (
<span>
<Button onClick={this.handleOpenModal} bsSize="large" bsStyle="info">Offer Room</Button>
<ReactModal
isOpen={this.state.showModal}
contentLabel="Minimal Modal Example"
style={customStyles} >
<Panel>
<Panel.Heading className="d-flex justify-content-end">
<Button onClick={this.handleCloseModal}> X </Button></Panel.Heading>
<Panel.Body>Some default panel content here.</Panel.Body>
<Panel.Body>Some more panel content here.</Panel.Body>
</Panel>
</ReactModal>
</span>
);
}
}
const customStyles = {
overlay: {
backgroundColor: '#50505077',
},
content:{
backgroundColor: '#50505000',
top: '25%',
left: '25%',
bottom: '25%',
right: '25%',
// width:'100%',
// margin:'0 auto',
// border: '0'
}
};
export default CustomModal;
/*
<div className="modal fade show" id="exampleModal" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
...
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
*/
|
define(['apps/base/base.directive'],
function (app) {
app.directive('userChoose', function () {
return {
restrict: 'EA',
template: '<button type="button" ng-click="openUserWindow()" class="btn btn-primary btn-square "><i class="icon-users "></i> {{text}}</button>',
scope: {
text: '@',
users: '=',
max: '=',
fixedUser: '='
},
controller: function ($scope, $rootScope, $uibModal) {
//var maxUserLength = $scope.max;
var parentScope = $scope;
$scope.openUserWindow = function () {
var modalInstance = $uibModal.open({
animation: false,
templateUrl: 'apps/base/view/select-user.html',
controller: function ($scope, $rootScope, $uibModalInstance, users) {
$scope.chooseUsers = users;
$scope.depts = $rootScope.department;
if ($scope.chooseUsers == undefined) {
$scope.chooseUsers = [];
}
angular.forEach($scope.depts, function (d) {
angular.forEach(d.users, function (u) {
if ($scope.chooseUsers.contains(function (_u) { return _u.ID == u.ID })) {
u.hide = true;
} else if (u.hide) {
u.hide = false;
}
})
})
// 已选择的用户从左边选择框内隐藏
angular.forEach($scope.chooseUsers, function (user) {
user.hide = true;
})
// 判断用户是否指定为只读
$scope.isFixed = function (user) {
if (parentScope.fixedUser) {
if (angular.isArray(parentScope.fixedUser)) {
return parentScope.fixedUser.contains(function (u) { return (u.ID ? u.ID : u) == user.ID })
} else {
return (parentScope.fixedUser.ID ? parentScope.fixedUser.ID : parentScope.fixedUser) == user.ID;
}
} else {
return false;
}
}
$scope.showUser = function (dept) {
dept.show = !dept.show;
$scope.userScroll.init();
}
$scope.chooseUser = function (user) {
if (!parentScope.max || $scope.chooseUsers.length < parentScope.max) {
$scope.chooseUsers.push(user);
user.hide = true;
}
}
$scope.removeUser = function (user) {
if (!$scope.isFixed(user)) {
user.hide = false;
$scope.chooseUsers.removeObj(user);
}
}
// 取消
$scope.cancel = function () {
angular.forEach($scope.chooseUsers, function (user) {
user.hide = false;
});
$scope.chooseUsers = [];
$uibModalInstance.close([]);
}
// 关闭
$scope.closeModal = function () {
$uibModalInstance.dismiss('cancel');
}
// 确定
$scope.ok = function () {
$uibModalInstance.close($scope.chooseUsers);
};
},
resolve: {
users: function () {
return $scope.users;
}
}
});
modalInstance.result.then(function (chooseUser) {
$scope.users = chooseUser;
}, function () {
//$scope.users = [];
});
}
},
link: function ($scope, element, attrs) {
}
};
});
});
|
controllers
.controller('SignupCtrl', function($scope, $ionicModal, $timeout, $firebaseArray, $location, backend) {
var firebaseRef = new Firebase("https://lover-position.firebaseio.com/");
$scope.signupData = {};
$scope.user = email;
// Perform the login action when the user submits the login form
$scope.doSignup = function() {
$scope.signup_error = '';
$scope.loading = true;
var ref = new Firebase("https://lover-position.firebaseio.com/");
try{
ref.createUser({
email: $scope.signupData.username,
password: $scope.signupData.password
}, function(error, userData) {
$scope.loading = false;
if (error) {
switch (error.code) {
case "EMAIL_TAKEN":
$scope.signup_error = "The new user account cannot be created because the email is already in use.";
break;
case "INVALID_EMAIL":
$scope.signup_error = "The specified email is not a valid email.";
break;
default:
$scope.signup_error = "Error creating user:" + error;
}
$scope.$apply();
} else {
email = $scope.signupData.username;
uid = userData.uid;
$scope.loading = false;
try{
ref.authWithPassword({
email : $scope.signupData.username,
password : $scope.signupData.password
}, function(error, authData) {
$scope.loading = false;
if (error) {
$scope.signup_error = error.message;
$scope.$apply();
} else {
email = $scope.signupData.username;
uid = authData.uid;
var usersRef = firebaseRef.child("users");
usersRef.child(uid).update({
email: email
}, function(error) {
if (error) {
$scope.signup_error = "Data could not be saved." + error;
} else {
backend.loadUser();
$location.path('/app/home');
$scope.$apply();
}
});
}
});
}catch(e){
$scope.loading = false;
$scope.signup_error = e.message;
}
}
});
}catch(e){
$scope.loading = false;
$scope.signup_error = e.message;
$scope.$apply();
}
};
$scope.reset = function(){
$scope.signup_error = '';
}
});
|
'use strict';
let { Map, List, Set, Seq, fromJS } = require('immutable');
const JSONsize = require('json-size');
let reddit_data = require('../spec/data/reddit_json');
let data_set = fromJS(reddit_data.concat(reddit_data)).toArray();
let data_size = JSONsize(data_set);
// Should value be used for intersect comparison:
const USE_VALUE = false;
// keyPaths(val: any, root: List, coerce: boolean)
// - Deeply maps iterable keypaths.
const keyPaths = (val, root = new Seq()) => {
if(typeof val !== 'object')
return [USE_VALUE ? root.concat(val) : root];
return new Seq(val).reduce((curr, value, key) => {
return curr.concat(keyPaths(value, root.concat(key)));
}, new Seq());
}
// intersect(target: Iterable, ...args: Iterable)
// - Returns target intersected on arg keypaths.
const intersect = (target, ...args) => {
let commonKeyPaths = keyPaths(target).toSet();
for(let i = 0; i < args.length; i++)
commonKeyPaths = commonKeyPaths.subtract(keyPaths(args[i]));
return commonKeyPaths.reduce((curr, keyPath) => {
return curr.deleteIn(keyPath);
}, target);
}
// let expected = new fromJS({ test: { again: 'yes' }, hmm: { another: 'same' } });
//
// let m1 = new fromJS({ test: { again: 'yes' }, hmm: { another: 'same' }, notMatching: 'heh' });
// let m2 = new fromJS({ test: { again: 'yes' }, hmm: { another: 'same' }, noMatch: 'nope' });
//
// let result = intersect(m1,m2);
//
// result.equals(expected);
let start = Date.now();
let result = intersect(...data_set);
let end = Date.now();
console.log(
'Parsed ' +
data_size/1000 +
'kb of data across ' +
data_set.length +
' objects in ' +
(end - start) +
'ms.'
);
// console.log(paths.size + ' keyPaths parsed from data.');
// console.log(JSON.stringify(result.toJS(), null, 2));
|
import React from "react";
import { Row, Col } from 'antd';
export default class Header extends React.Component{
render(){
return (
<div>
<Row>
<Col span={8}>col-8</Col>
<Col style={{backgroundColor: '#00a0e9'}} span={8} offset={8}>col-8</Col>
</Row>
</div>
)
}
}
|
import React,{useState} from 'react';
import Home from './Home';
import About from './About';
import Info from './Info';
import Service from './Service';
import Contact from './Contact';
import {BrowserRouter as Router, Link,} from 'react-router-dom';
const Navbar = () => {
const[active, setActive] =useState("start");
return (
<div>
<Router>
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<div className="container-fluid container">
<Link className="navbar-brand" href="#">Navbar</Link>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<Link className="nav-link" onClick={()=>setActive("start")}>Home</Link>
</li>
<li className="nav-item">
<Link className="nav-link" onClick={()=>setActive("about")}>About Us</Link>
</li>
<li className="nav-item">
<Link className="nav-link" onClick={()=>setActive("info")}>Service</Link>
</li>
<li className="nav-item">
<Link className="nav-link" onClick={()=>setActive("service")}>Info</Link>
</li>
<li className="nav-item">
<Link className="nav-link" onClick={()=>setActive("contact")}>Contact</Link>
</li>
</ul>
</div>
</div>
</nav>
</Router>
<div>
{active ==="start" && <Home props="Home page"/>}
{active ==="about" && <About props="About page"/>}
{active ==="info" && <Info props="Service page"/>}
{active ==="service" && <Service props="Info page"/>}
{active ==="contact" && <Contact props="Contact page"/>}
</div>
</div>
)
}
export default Navbar
|
import ExpoPixi, { PIXI } from 'expo-pixi';
export default async context => {
//http://pixijs.io/examples/#/basics/basic.js
const app = ExpoPixi.application({
context,
});
app.stage.interactive = true;
var container = new PIXI.Container();
app.stage.addChild(container);
var padding = 100;
var bounds = new PIXI.Rectangle(
-padding,
-padding,
app.renderer.width + padding * 2,
app.renderer.height + padding * 2
);
var maggots = [];
for (var i = 0; i < 20; i++) {
var maggot = await ExpoPixi.spriteAsync(require('../../assets/pixi/maggot.png'));
maggot.anchor.set(0.5);
container.addChild(maggot);
maggot.direction = Math.random() * Math.PI * 2;
maggot.speed = 1;
maggot.turnSpeed = Math.random() - 0.8;
maggot.x = Math.random() * bounds.width;
maggot.y = Math.random() * bounds.height;
maggot.scale.set(1 + Math.random() * 0.3);
maggot.original = new PIXI.Point();
maggot.original.copy(maggot.scale);
maggots.push(maggot);
}
var displacementSprite = await ExpoPixi.spriteAsync(require('../../assets/pixi/displace.png'));
var displacementFilter = new PIXI.filters.DisplacementFilter(displacementSprite);
app.stage.addChild(displacementSprite);
container.filters = [displacementFilter];
displacementFilter.scale.x = 110;
displacementFilter.scale.y = 110;
displacementSprite.anchor.set(0.5);
var ring = await ExpoPixi.spriteAsync(require('../../assets/pixi/ring.png'));
ring.anchor.set(0.5);
ring.visible = false;
app.stage.addChild(ring);
var bg = await ExpoPixi.spriteAsync(require('../../assets/pixi/bkg-grass.jpg'));
bg.width = app.renderer.width;
bg.height = app.renderer.height;
bg.alpha = 0.4;
container.addChild(bg);
app.stage.on('mousemove', onPointerMove).on('touchmove', onPointerMove);
function onPointerMove(eventData) {
ring.visible = true;
displacementSprite.position.set(eventData.data.global.x - 25, eventData.data.global.y);
ring.position.copy(displacementSprite.position);
}
var count = 0;
app.ticker.add(function() {
count += 0.05;
for (var i = 0; i < maggots.length; i++) {
var maggot = maggots[i];
maggot.direction += maggot.turnSpeed * 0.01;
maggot.x += Math.sin(maggot.direction) * maggot.speed;
maggot.y += Math.cos(maggot.direction) * maggot.speed;
maggot.rotation = -maggot.direction - Math.PI / 2;
maggot.scale.x = maggot.original.x + Math.sin(count) * 0.2;
// wrap the maggots around as the crawl
if (maggot.x < bounds.x) {
maggot.x += bounds.width;
} else if (maggot.x > bounds.x + bounds.width) {
maggot.x -= bounds.width;
}
if (maggot.y < bounds.y) {
maggot.y += bounds.height;
} else if (maggot.y > bounds.y + bounds.height) {
maggot.y -= bounds.height;
}
}
});
};
|
import { UserManager } from "oidc-client";
import userManagerConfig from './config/userManagerConfig';
export default class AuthService {
constructor() {
this.userManager = new UserManager(userManagerConfig);
this.userManager.events.addUserLoaded(this.updateToken);
this.userManager.events.addAccessTokenExpired(() => {
console.log("token expired");
this.userManager.signinSilent().then(this.updateToken);
});
}
updateToken(user) {
console.log('user', user);
// set token_id to cookies
}
signinRedirect = () => {
this.userManager.signinRedirect({});
};
signinRedirectCallback = () => {
this.userManager.signinRedirectCallback();
};
}
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import Navigation from "./presenter";
class Container extends Component {
constructor(props, context){
super(props, context)
this.state = {
visible: false,
fixedMenu: false,
calculations: {
direction: 'none',
height: 0,
width: 0,
topPassed: false,
bottomPassed: false,
pixelsPassed: 0,
percentagePassed: 0,
topVisible: false,
bottomVisible: false,
fits: false,
passing: false,
onScreen: false,
offScreen: false,
},
};
}
static propTypes = {
pathname: PropTypes.string.isRequired,
lang: PropTypes.string.isRequired,
}
static contextTypes = {
t: PropTypes.func.isRequired
};
componentDidMount() {
}
render() {
return (
<Navigation
visible={this.state.visible}
handleOnClickMenuItem={this._handleOnClickMenuItem}
children = {this.props.children}
fixedMenu = {this.state.fixedMenu}
pathname = {this.props.pathname}
lang={this.props.lang}
handlePusher={this._handlePusher}
handleToggle={this._handleToggle}
handleVisibilityUpdate={this._handleVisibilityUpdate}
/>
);
}
_handleVisibilityUpdate = (e, { calculations }) => {
this.setState({
calculations: calculations
})
if (calculations.topVisible === true) {
this.setState({
fixedMenu: false,
})
}
else if (calculations.direction === 'down') {
this.setState({
fixedMenu: false,
})
} else if (calculations.direction === 'up') {
this.setState({
fixedMenu: true,
})
}
}
_handlePusher = () => {
if (this.state.visible) {
this.setState({
visible: false
});
};
}
_handleToggle = () => {
this.setState({
visible: !this.state.visible
})
};
_handleOnClickMenuItem = (key) => {
switch (key) {
case 'music':
case 'model':
case 'story':
case 'video':
case 'gemshop':
case 'home':
break;
default :
break;
}
this.setState({
visible: false,
})
}
}
export default Container;
|
// js/controllers/app-navbar.controller
(function() {
"use strict";
angular.module("NoteWrangler")
.controller("appNavbarController", appNavbarController);
appNavbarController.$inject = ["$location"];
function appNavbarController($location) {
let vm = this;
vm.setActive = setActive;
function setActive(path) {
return $location.path().indexOf(path) !== -1;
}
}
})();
|
var pg = require('pg');
//var connectionString = "postgres://cc3201:notansegura@cc3201.dcc.uchile.cl:5408/cc3201";
var connectionString = "postgres://cc3201:notansegura@localhost:5432/cc3201";
var pgClient = new pg.Client(connectionString);
pgClient.connect();
var query = pgClient.query("SELECT product_id ,Shrt_Desc, Energ_Kcal from nutritional_data where Shrt_Desc like '%CHEESE%' limit 1;");
query.on("row", function(row,result){
//result.addRow(row);
console.log(row);
pgClient.end();
});
|
export const getCurrentUser = () => {
if (typeof window !== "undefined") {
const localStorage = window.localStorage;
const currentUser = localStorage.getItem("currentUser");
if (currentUser) {
return JSON.parse(currentUser);
}
return null;
}
};
export const removeCurrentUser = () => {
if (typeof window !== "undefined") {
const localStorage = window.localStorage;
localStorage.removeItem("currentUser");
}
};
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
// Import Search Bar Components
import {Input} from "../../atoms/input/Input.js";
import "./GooglePlacesAutoComplete.scss";
export class GooglePlacesAutoComplete extends React.Component {
constructor() {
super();
this.handlePlaceSelect = this.handlePlaceSelect.bind(this);
}
/**
* the Google Places API is instantiated here for the Google Places Autocomplete
*/
componentDidMount() {
const options = {types: ['address'], ComponentRestrictions:{country: ["us"]}};
/*global google*/
this.autocomplete = new google.maps.places.Autocomplete(document.getElementById('googlePlacesAutoComplete'), options);
this.autocomplete.addListener('place_changed', this.handlePlaceSelect);
}
/**
* handlePlaceSelect() is called when a user has selected an address
*/
handlePlaceSelect() {
const place = this.autocomplete.getPlace();
this.props.onPlaceSelected && this.props.onPlaceSelected(place);
}
shouldComponentUpdate() {
// this component is controlled by the Google Maps Places Autocomplete API, React should never update it
return false;
}
render() {
return (
<div className={classNames('google-places-auto-complete', this.props.className)}>
<Input id="googlePlacesAutoComplete"
name="googlePlacesAutoComplete"
placeholder={this.props.placeholder}
/>
</div>
);
}
}
GooglePlacesAutoComplete.propTypes = {
placeholder:PropTypes.string,
onPlaceSelected:PropTypes.func,
className:PropTypes.string,
value:PropTypes.string
};
|
var fs = require('fs');
var domjs = require('dom-js');
var config = require("../util/config.js").configData;
/**
* A module for maintaining an includable .html ssi page with a list of external links.
* Not meant to be scalable, this just works with a single file for the main menu.
*/
/**
* Data holder for a single link
* @constructor
*/
LinkModel = function(url, title, description, icon) {
this.url = url; // URL escaped
this.title = title; // unescaped text
this.description = description; // unescaped text
this.icon = icon; // URL escaped
};
/**
* Convert one model to an XHMTL snippet (not a doc, no wrapping element).
* @param model
*/
LinkModel.prototype.toXHTML = function(model) {
var m = model || this;
var href = '<a href="' + m.url + '" ';
if (m.description) {
href += 'title="' + domjs.escape(m.description) + '" ';
}
href += 'class="pw-link">';
if (m.icon) {
href += '<img src="' + m.icon + '" class="pw-link-icon"/>';
}
if (m.title) {
href += domjs.escape(m.title);
}
href += '</a><br/>';
return href;
};
/**
* Read an XHTML string and create an array of LinkModels
* @param xmlString
* @param cb callback when done
*/
LinkModel.unmarshall = function(xmlString, cb) {
var docBuilder = new domjs.DomJS();
docBuilder.parse(xmlString, function(err, dom) {
if (err) {
cb(err);
return;
}
var all = [];
for(var i = 0 ; i < dom.children.length ; i++) {
if (typeof dom.children[i].text == 'string') {
continue;
}
if (dom.children[i].name == 'br') {
continue;
}
var linkElem = dom.children[i];
var linkModel = new LinkModel();
linkModel.url = linkElem.attributes['href'];
linkModel.description = linkElem.attributes['title'];
var fc = linkElem.firstChild();
//console.log(fc);
if (fc && fc.name && fc.name == 'img') {
linkModel.icon = fc.attributes['src'];
if (linkElem.children.length > 1) {
linkModel.title = linkElem.children[1].text;
}
}
else {
if ( ! linkElem.children[0].text ) {
console.log('Missing data in the XHTML');
continue;
}
linkModel.title = linkElem.children[0].text;
}
all.push(linkModel);
}
cb(false, all);
});
};
/**
* convert an array of LinkModels to an XHMTL string.
* @param all
* @returns {String}
*/
LinkModel.marshall = function(all) {
var sb = '<div id="pw-links">\n';
for ( var i = 0; i < all.length; i++) {
if ( all[i] != null) {
var obj = all[i];
sb += obj.toXHTML();
sb += '\n';
}
}
sb += '</div>\n';
return sb;
};
/**
* Construct a LinkModel from a JSON object with the correct attributes
* @param json
* @returns {LinkModel}
*/
factory = function(json) {
return new LinkModel(json.url, json.title, json.description, json.icon);
};
/**
* Save the data (overwrite)
*/
persist = function(fileName, all, cb) {
// TODO atomic createfile
fs.writeFile(fileName + '.tmp', LinkModel.marshall(all), function(err) {
if ( ! err ) {
fs.rename(fileName + '.tmp', fileName, cb);
}
else {
cb(err);
}
});
};
materialize = function(fileName, cb) {
fs.readFile(fileName, 'utf-8', function(err, data) {
if ( ! err ) {
LinkModel.unmarshall(data, cb);
}
else {
cb(err);
};
});
};
/**
* Get the data in JSON form for the edit form.
* @param request
* @param response
* @param url
*/
function doGet(request, response, url) {
var linksFile = config.appjsdir + "/main-links.html";
materialize(linksFile, function(err, existingData) {
if ( ! err ) {
var json = JSON.stringify(existingData);
response.writeHead(200, "OK");
response.write(json);
response.end();
return;
}
else if ( err.errno == 2 ) {
response.writeHead(200, "OK", { "Content-Length" : "2" });
response.write("[]");
response.end();
return;
}{
console.log(err);
response.writeHead(500, "SERVER ERROR");
response.end();
return;
}
});
};
function doPost(request, response, url) {
var buffer = '';
// load from POST request
request.on('data', function(data) {
buffer += data;
});
// when all loaded
request.on('end', function() {
// load the existing links
var linksFile = config.appjsdir + "/main-links.html";
materialize(linksFile, function(err, existingData) {
if ( err.errno == 2) { // file not found
console.log(linksFile + ' not found');
existingData = [];
}
else if (err) {
console.log("Error loading data : " + url + " " + err);
response.writeHead(400, "BAD REQUEST");
response.end();
return;
}
var togo = null;
if (url.query && url.query.del) {
togo = url.query.del;
}
try {
if (togo != null) { // deleting
for ( var i = 0; i < existingData.length; i++) {
if (existingData[i].url == togo) {
existingData[i] = null;
}
}
}
else { // adding
// check we got something
if (buffer.length == 0) {
console.log("Error saving links : "+ url + " " + err);
response.writeHead(400, "BAD REQUEST");
response.end();
return;
}
// sync can throw
var json = JSON.parse(buffer);
// validation
if ( ! json.url ) {
throw new Error("url required in JSON object");
}
if ( json.url.indexOf("http") != 0 ) {
throw new Error('url should start "http"');
}
if (typeof json.title == 'undefined' &&
typeof json.icon == 'undefined' ) {
throw new Error('need and icon or a title');
}
// create and add a model
var model = factory(json);
existingData.push(model);
}
// save changes
persist(linksFile, existingData, function(err) {
if ( ! err) {
var ok = '{"ok": true}';
response.writeHead(200, "OK", { "Content-Length" : "" + ok.length });
response.write(ok);
response.end();
return;
}
});
} catch (err) {
console.log("Bad JSON : " + url + " " + err);
response.writeHead(400, "BAD REQUEST");
response.end();
return;
}
});
});
};
// for nodeunit
module.exports.factory = factory;
module.exports.materialize = materialize;
module.exports.persist = persist;
// for web
module.exports.doGet = doGet;
module.exports.doPost = doPost;
|
require('dotenv').config();
require('./config/database');
// require('./config/passport');
const Prop = require('./models/prop');
let prop = new Prop({title: 'First Prop', dependencies: 'None'});
prop.save()
.then(function(){
process.exit();
})
|
/***************************
** Initialize our database *
***************************/
//Import the mongoose module
const mongoose = require('mongoose');
const envConfig = require('../config/env');
const Users = require('../models/users');
const Message = require('../models/message');
//Set up default mongoose connection
const mongoDB = envConfig.db;
console.log('mongoDB :---------------------------------', mongoDB);
mongoose.connect(mongoDB, {
useNewUrlParser: true,
connectTimeoutMS: 10000,
socketTimeoutMS: 45000,
reconnectInterval: 500,
poolSize: 10,
});
//Get the default connection
const db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', function() {
// we're connected!
if (process.env.NODE_ENV === 'test') {
function clearDB(done) {
const promises = [
Users.deleteMany().exec(),
Message.deleteMany().exec(),
];
Promise.all(promises)
.then(function() {
done();
})
}
before(function(done) {
return clearDB(done);
});
after(function(done) {
return clearDB(done);
});
}
console.log("Database connected!!")
});
|
import React from 'react'
import { TabBoxStyle } from './style'
const TabBoxComponent = () => (WrappedComponent) => function TabBox (props) {
const { tab, selectTab } = props
function HandleTapAction () {
console.log('代理组件抽离点击事件')
}
return (
<TabBoxStyle>
<div className="tab-header">
<div className="tab-menu">
<span className={ tab === 0 ? 'active' : '' } onClick={ () => selectTab(0) }>卡片</span>
<span className={ tab === 1 ? 'active' : '' } onClick={ () => selectTab(1) }>列表</span>
</div>
</div>
<div className="tab-body">
<WrappedComponent { ...props } HandleTapAction={ HandleTapAction }/>
</div>
</TabBoxStyle>
)
}
export default TabBoxComponent
|
// Import libraries
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
// Event listener when a user connected to the server.
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// Event listener when a user sends a message in the chat.
client.on('message', msg => {
// We check the message content and looks for the word "ping", so we can have the bot respond "pong"
if (msg.content === 'ping') {
msg.reply('pong');
}
});
// Initialize bot by connecting to the server
client.login(auth.token);
|
// author: catomatic
// website: https://github.com/catomatic
// source: personal projects library
// Sieve of Eratosthenes
var removeMultiples = function(e, list, p) {
if ((list[e] != p) && (list[e] % p == 0)) {
var eIndex = list.indexOf(list[e]);
list.splice(eIndex, 1);
}
}
var primeNumbers = function(num) {
var primeList = [];
for (i = 2; i < (num + 1); i++) {
primeList.push(i);
}
var p = 2;
for (i = 0; i <= num; i++) {
removeMultiples(i, primeList, p);
if (primeList[i] > p) {
var p = primeList[i];
}
for (j = 0; j <= primeList.length; j++) {
removeMultiples(j, primeList, p);
}
}
return primeList;
}
console.log(primeNumbers(100));
|
luckApp.controller('lk.vote.voteController',['$scope','$state','$stateParams','lk.wechartFactory','lk.vote.voteFactory',
function($scope,$state,$stateParams,wx,fac){
console.log("vote");
}]);
luckApp.factory('lk.vote.voteFactory', ['$http',function($http){
return {
getvote:function(callback){
$http({
method: 'POST',
data:{},
url: '/vote'
}).success(function(data, header, config, status) {
return callback && callback(data);
});
}
};
}]);
|
// let app;
const jsforce = require('jsforce');
const secrets = require("../../secrets/secrets.js");
let fs = require("fs");
let salesforce = require("./module_salesforce");
function init(pass_express) {
// singleObject(pass_express);
allObject(pass_express);
newRegistrations(pass_express);
}
function allObject(app) {
app.get('/registrations', function(req, resMain) {
console.log("Received GET for Registrations - Multiple");
console.log("PROTOCOL: " + req.protocol + '://' + req.get('host') + req.originalUrl + "\n");
let date = req.params.fromDate || 'LAST_WEEK';
// Query all registrations
let query = "SELECT AA_has_been_processed__c,AA_have_sent_SMS__c,app_version__c,CreatedDate," +
"home_community_custom__c,home_community__c,name__c,surname__c,usertype__c,uuid_timestamp__c " +
"FROM " +
"Ablb_Registration__c ";
// Query excluding test registrations
let query2 = "SELECT AA_assigned_abalobi_id__c,AA_assigned_username__c,AA_has_been_processed__c," +
"AA_have_sent_SMS__c,app_version__c,CreatedDate " +
"FROM " +
"Ablb_Registration__c " +
"WHERE (NOT home_community__c LIKE '%demo%') " +
"AND (NOT name__c LIKE '%test%') " +
"AND (NOT name__c LIKE '%Test%') " +
"ORDER BY CreatedDate DESC NULLS FIRST";
console.log(query2);
salesforce.createQuery(query2, function(res) {
let sendMeBack = {};
sendMeBack['registrations'] = res.records;
// fs.writeFileSync("datafiles/sf_output.json", JSON.stringify(sendMeBack, null, 4));
resMain.send(sendMeBack);
}, function(error){
});
});
}
function newRegistrations(app) {
app.get('/registrations_new', function(req, resMain) {
console.log("Received GET for Registrations - Multiple");
console.log("PROTOCOL: " + req.protocol + '://' + req.get('host') + req.originalUrl + "\n");
let date = req.params.fromDate || 'LAST_WEEK';
// Query only new registrations that are valid registrations
let query = "SELECT AA_assigned_abalobi_id__c," +
"AA_assigned_username__c," +
"AA_has_been_processed__c," +
"name__c," +
"surname__c," +
"home_community__c," +
"usertype__c," +
"Id," +
"cell_num_personal__c," +
"AA_have_sent_SMS__c,app_version__c,CreatedDate " +
"FROM " +
"Ablb_Registration__c " +
"WHERE (NOT home_community__c LIKE '%demo%') " +
"AND home_community__c != null " +
"AND (NOT name__c LIKE '%test%') " +
"AND (NOT name__c LIKE '%Test%') " +
"AND AA_has_been_processed__c LIKE 'Not yet' " +
"ORDER BY CreatedDate DESC NULLS FIRST";
// console.log(query);
salesforce.createQuery(query, function(res) {
let sendMeBack = {};
sendMeBack['registrations'] = res.records;
// fs.writeFileSync("datafiles/sf_output.json", JSON.stringify(sendMeBack, null, 4));
resMain.send(sendMeBack);
}, function(error){
});
});
}
module.exports = {
init: init
};
|
import Head from 'next/head'
import {AppBar, Toolbar, Typography} from '@material-ui/core';
const Header = () => {
return(
<div>
<Head>
<title>AeroSeeker</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width"
/>
</Head>
<AppBar position="static">
<Toolbar>
<Typography variant="h6">
AeroSeeker
</Typography>
</Toolbar>
</AppBar>
</div>
)
}
export default Header
|
/**
* @file : www.js
* @description : 启动项目入口
* @author : YanXianPing
* @creatTime : 2020/10/29 20:43
*/
const http = require('http');
const app = require('../app');
http.createServer(app).listen(4000);
|
import React from 'react';
import { connect } from 'react-redux';
import { ListGroup, ListGroupItem, Badge, Button } from 'reactstrap';
import PaypalButton from '../PaypalButton';
const Cart = props => {
const { total, items } = props;
return (
<span>
<ListGroup>
{items.map((item, index) => (
<ListGroupItem className="justify-content-between" key={index}>
<Badge pill> {item.qty}</Badge> {item.name} ${item.price}
</ListGroupItem>
))}
<ListGroupItem active tag="a" action>
Total: {total}
</ListGroupItem>
<ListGroupItem active tag="a" action>
{total > 0 ? <PaypalButton total={total} items={items} /> : null}
</ListGroupItem>
</ListGroup>
</span>
);
};
const mapStateToProps = store => ({
total: store.cart.total,
items: store.cart.items,
cart: store.cart
});
export default connect(
mapStateToProps,
{}
)(Cart);
|
import React from 'react'
import { Link } from 'react-router-dom'
import { TOKEN_POST, USER_GET } from '../../api'
import useForm from '../../Hooks/useForm'
import Button from '../forms/Button'
import Input from '../forms/Input'
function LoginForm() {
const username = useForm();
const password = useForm();
React.useState(()=> {
const token = window.localStorage.getItem('token')
if(token){
getUser(token)
}
},[])
async function getUser(token){
const{url, options} = USER_GET(token)
const response = await fetch(url, options)
const json = await response.json();
console.log(json)
}
async function handleSubmit(event){
event.preventDefault()
if(username.validate && password.validate){
const {url, options} = TOKEN_POST({
username: username.value,
password:password.value
})
const response = await fetch(url, options)
const json = await response.json();
window.localStorage.setItem('token',json.token);
getUser(json.token);
}
}
return (
<section className="container">
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<Input type="text" name="username" label="Name" {...username}/>
<Input type="password" name="password" label="Senha" {...password}/>
<Button children="Entrar"/>
</form>
<Link to="/login/criar">Cadastro</Link>
</section>
)
}
export default LoginForm
|
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener("deviceready", this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent("deviceready");
app.addMenuItemToCustomContext();
bb.init({
actionBarDark: true,
controlsDark: true,
listsDark: false,
onscreenready: function (element, id, params){},
ondomready : function (element, id){}
});
bb.pushScreen("main.html", "mainScreen");
},
// Update DOM on a Received Event
receivedEvent: function(id) {
},
//Adding Items to the Context Menu
addMenuItemToCustomContext: function (){
var myContext = ["myContext"];
var myItem = {actionId: "1", label: "Compartir", icon:'local:///img/icoShare.png'};
var myItemCancel = {actionId: blackberry.ui.contextmenu.ACTION_CANCEL, label: "Cancelar Selección", icon:'local:///img/icoCancel.png'};
blackberry.ui.contextmenu.addItem(myContext, myItem, app.findAppsToShare);
blackberry.ui.contextmenu.overrideItem(myItemCancel, app.cancelListItemSelection);
},
//Success Callback - Invokation Framework
onInvokeSuccess: function () {
alert("Invocation successful!");
},
//Error Callback - Invokation Framework
onInvokeError: function (error) {
alert("Invocation failed, error: " + error);
},
//Cancel List Item Selection
cancelListItemSelection: function(){
alert("Plaform menu item cancel selection successfully overridden");
},
//Invokation Framework
findAppsToShare: function(id) {
var selectedItem = document.getElementById(id);
//alert("El twitter de "+selectedItem.title+" es "+selectedItem.description);
var request = {
action : "bb.action.SHARE",
mime : "text/plain",
data : "El twitter de "+selectedItem.title+" es "+selectedItem.description+"",
target_type: ["VIEWER", "CARD"]
};
blackberry.invoke.card.invokeTargetPicker(request, "Shared data", app.onInvokeSuccess, app.onInvokeError);
}
};
|
import React from 'react'
const Prefooter = ()=> {
return (
<div className="prefooter">
<p>Who will you share your PreFare with? <a href='/signup'><button className="shareButton">JOIN US TODAY</button></a></p>
</div>
)
}
export default Prefooter
|
(function(){
'use strict';
angular.module('app.pertratante', [
'app.pertratante.controller',
'app.pertratante.services',
'app.pertratante.router',
'app.pertratante.directivas'
]);
})();
|
import React from 'react';
import { View, Text, Button , StyleSheet} from 'react-native';
import { createAppContainer, createStackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
render (){
return (
<View style = {{flex : 1 , alignitems: 'center' , justifyContent : 'center' , backgroundColor: 'hsla(300, 100%, 50%, 0.2)' }}>
<Text style = {{flex : 1 , textAlign: 'center' , fontWeight: 'bold', fontSize: 35}}> HOME SCREEN </Text>
<Button title = "GO TO DETAILS" onPress = {() => this.props.navigation .navigate ('Details')} />
</View>
);
}
}
class Details extends React.Component {
render (){
return (
<View style = {{flex : 1 , alignitems: 'center' , justifyContent : 'center' , backgroundColor: 'hsla(120, 100%, 50%, 0.2)' }}>
<Text style = {{flex : 1 , textAlign: 'center' , fontWeight: 'bold', fontSize: 35}}> DETAILS PAGE</Text>
<Button title = "GO BACK TO HOME" onPress = {() => this.props.navigation.navigate('Home')}/>
<Button title = "CONTACT US" onPress ={() => this.props.navigation.navigate('Contact')} />
</View>
);
}
}
class ContactUs extends React.Component {
render() {
return (
<View style = {{flex : 1 , alignitems: 'center' , justifyContent : 'center' , backgroundColor: 'hsla(0, 100%, 50%, 0.2)' }}>
<Text style = {{flex : 1 , textAlign: 'center' , fontWeight: 'bold', fontSize: 35}}> CONTACT US</Text>
<Button title = "GO BACK TO MAIN PAGE" onPress = {() => this.props.navigation.navigate('Home')}/>
</View>
);
}
}
const RootStack = createStackNavigator (
{
Home : HomeScreen ,
Details : Details ,
Contact : ContactUs ,
},
{
initialRouteName : 'Home' ,
}
);
const Wow = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <Wow/>;
}
}
|
var fs = require('fs');
module.exports = function(inFilename, inDefaultJson, inTab) {
fs.writeFileSync(
inFilename,
JSON.stringify(inDefaultJson, null, inTab || 2)
);
};
|
import {
createStore,
combineReducers,
applyMiddleware,
compose } from 'redux';
import thunk from 'redux-thunk';
import prayerReducer from '../reducers/prayerReducer';
const middleware = applyMiddleware(thunk)
const reduxDevTools = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
const store = createStore(
combineReducers({
prayers: prayerReducer
}),
compose(
middleware,
reduxDevTools
)
)
export default store;
|
import React from 'react';
import PropTypes from 'prop-types';
import {
View,
ImageBackground,
SafeAreaView,
Platform,
StatusBar,
} from 'react-native';
import styles from './styles';
import NrmSpinner from '../NrmSpinner';
const NrmContainer = ({
children,
imageSource,
tintColor,
style,
centered,
blurRadius,
androidPadStatusBar,
barStyle,
}) => {
let containerStyle = {
...styles.container,
justifyContent:
centered == 'all' || centered == 'vertical' ? 'center' : undefined,
alignItems:
centered == 'all' || centered == 'horizontal' ? 'center' : undefined,
paddingTop:
androidPadStatusBar && Platform.OS == 'android'
? StatusBar.currentHeight / 2
: undefined,
...style,
};
if (imageSource) {
return (
<ImageBackground
resizeMode="cover"
blurRadius={blurRadius}
source={imageSource}
style={containerStyle}>
<SafeAreaView
style={{
...containerStyle,
width: '100%',
backgroundColor: tintColor,
}}>
<StatusBar barStyle={barStyle} />
{children}
</SafeAreaView>
</ImageBackground>
);
}
return (
<SafeAreaView style={containerStyle}>
<StatusBar barStyle={barStyle} />
{children}
<NrmSpinner />
</SafeAreaView>
);
};
NrmContainer.propTypes = {
tintColor: PropTypes.number,
blurRadius: PropTypes.number,
style: PropTypes.object,
centered: PropTypes.oneOf(['horizontal', 'vertical', 'all']),
androidPadStatusBar: PropTypes.bool,
};
NrmContainer.defaultProps = {
blurRadius: 0,
backgroundColor: 'transparent',
};
export default NrmContainer;
|
var gulp = require('gulp'),
clean = require('gulp-clean'),
eslint = require('gulp-eslint'),
mocha = require('gulp-mocha');
require('gulp-release-tasks')(gulp);
var paths = {
scripts: ['index.js'],
tests: ['test/**/*.js']
};
gulp.task('lint', function() {
return gulp.src(paths.scripts)
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
gulp.task('test', function () {
return gulp.src(paths.tests, {read: false})
.pipe(mocha({reporter: 'nyan'}));
});
gulp.task('default', ['lint', 'test']);
|
module.exports = function (state, index) {
var devices =
[ { label: 'hostname (localhost)', icon: 'laptop' }
, { label: 'remotehost (163.45.72.5)', icon: 'server' }
, { label: 'remotehost2 (42.64.133.122)', icon: 'server' } ];
return h('.DeviceList',
[ h('.Frame_Header',
[ $.lib.icon('database.fa-2x')
, h('strong', 'Device List' )
, h('.Frame_Close', { onclick: close }, '×')
])
, devices.map(device)
]);
function close () {}
function add () {}
}
function device (data) {
return h('.Frame_Section.Device',
[ $.lib.icon(data.icon + '.fa-2x')
, data.label ]);
}
|
(function() {
var DEBUG, xx,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
DEBUG = true;
xx = function(t) {
return DEBUG && console.log(t);
};
/*
------------------------------------------------------------------------------
jQuery extend
------------------------------------------------------------------------------
*/
$.fn.extend({
changeClass: function(a, b) {
var target;
target = $(this);
return target.removeClass(a).addClass(b);
},
fixedX: function() {
var left, target;
target = $(this);
left = parseInt(target.css('left'));
return $(window).scroll(function() {
return target.css({
'left': $(this).scrollLeft() + left
});
});
},
gallerize: function(d) {
window.leave = false;
return this.each(function(i, t) {
var children, current, duration, go, length, target;
target = $(t);
children = target.children('img');
if (!children.length) {
children = target.children('li');
}
length = children.length;
current = 0;
duration = d || 1000;
children.eq(current).addClass('active');
go = function() {
if (window.leave) {
return;
}
children.removeClass('active');
current = current < length - 1 ? current + 1 : 0;
children.eq(current).addClass('active');
return setTimeout(go, duration);
};
return setTimeout(go, duration);
});
}
});
/*
------------------------------------------------------------------------------
Site
------------------------------------------------------------------------------
*/
window.Site = (function() {
function Site() {
this.leave = __bind(this.leave, this);
this.startLoadingImage = __bind(this.startLoadingImage, this);
this.loadContent = __bind(this.loadContent, this);
this.popState = __bind(this.popState, this);
this.firstPop = __bind(this.firstPop, this);
this.resize = __bind(this.resize, this);
this.changeLang = __bind(this.changeLang, this);
this.playVideo = __bind(this.playVideo, this);
this.disableHover = __bind(this.disableHover, this);
this.checkCountry = __bind(this.checkCountry, this);
}
Site.prototype.constuctor = function() {};
Site.prototype.setup = function() {
this.checkCountry();
this.prepare();
this.observe();
if (!(window.history && history.pushState)) {
return this.init();
} else {
return this.firstPop();
}
};
Site.prototype.prepare = function() {
this.window = $(window);
this.document = $(document);
this.html = $('html');
this.body = $('body');
this.main = this.body.find('main');
this.menu = this.body.find('#main-menu');
this.lang = this.body.find('#toggle-lang');
this.header = this.body.find('header');
this.loadedItem = this.body.find('#loaded-item');
this.totalItem = this.body.find('#total-item');
this.popped = 'state' in window.history && (window.history.state != null);
this.initialURL = location.href;
return this.introViewed = false;
};
Site.prototype.checkCountry = function() {
var _this = this;
return $.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
return _this.is_china = data.address.country === 'China';
});
};
Site.prototype.observe = function() {
this.lang.on('click', 'a', this.changeLang);
this.window.on({
'resize': this.resize,
'scroll': this.disableHover
});
if (!!(window.history && history.pushState)) {
window.onpopstate = this.popState;
this.body.on("click", "a:not('.download, .link, .video-link')", this.leave);
}
this.body.on('mouseover', '[rel="external"]', this.linkTo);
return this.body.on('click', '.video-link', this.playVideo);
};
Site.prototype.disableHover = function() {
var _this = this;
this.body.toggleClass('scrolled', this.window.scrollTop() > 50);
if (this.timer != null) {
clearTimeout(this.timer);
this.timer = null;
}
this.body.addClass('disable-hover');
return this.timer = setTimeout(function() {
return _this.body.removeClass('disable-hover');
}, 500);
};
Site.prototype.linkTo = function(e) {
return $(e.currentTarget).attr('target', '_blank');
};
Site.prototype.playVideo = function(e) {
var $link;
$link = $(e.currentTarget);
if (this.is_china) {
return;
}
e.preventDefault();
return new Player($link);
};
Site.prototype.changeLang = function(event) {
var lang, target;
target = $(event.currentTarget);
lang = target.data('lang');
this.lang.removeClass('unselected');
this.lang.find('a').removeClass('current');
target.addClass('current');
switch (lang) {
case "en":
this.html.removeClass('lang-ch');
break;
case "ch":
this.html.addClass('lang-ch');
}
return false;
};
Site.prototype.init = function() {
if (this.is_home) {
this["new"]("home");
}
if (this.is_panoramic) {
this["new"]("panoramic");
}
if (this.is_panel) {
this["new"]("panel");
}
if (this.is_gallery) {
return this["new"]("gallery");
}
};
Site.prototype.save_dimension = function() {
this.width = this.window.width();
return this.height = this.window.height();
};
Site.prototype.resize = function() {
return this.save_dimension();
};
/*
------------------------------------------------------------------------------
AJAX
------------------------------------------------------------------------------
*/
Site.prototype.firstPop = function() {
this.initialPop = !this.popped && location.href === this.initialURL;
if (!this.initialPop) {
return;
}
this.html.addClass('loading');
this.checkPage();
return this.startLoadingImage();
};
Site.prototype.popState = function() {
this.initialPop = !this.popped && location.href === this.initialURL;
this.popped = true;
if (this.initialPop) {
return;
}
return this.loadContent(location.pathname);
};
Site.prototype.loadContent = function(href) {
var _this = this;
this.loadedItem.add(this.totalItem).text('');
return $.ajax({
url: href
}).fail(function() {
return xx('fail');
}).done(function(data) {
var ah, article, main, menu, wh;
data = $(data);
main = data.find('main');
_this.main.replaceWith(main);
_this.main = main;
menu = data.find('#main-menu');
_this.menu.replaceWith(menu);
_this.menu = menu;
_this.body.attr('class', 'page-' + _this.main.attr('data-slug'));
_this.checkPage();
if (_this.is_video) {
article = _this.main.find('article');
wh = $(window).height();
ah = article.height();
if (wh > ah) {
article.css('top', (wh - ah) / 2);
}
_this.scrollToMiddle();
}
return _this.startLoadingImage();
});
};
Site.prototype.checkPage = function() {
this.is_home = this.main.hasClass('home');
this.is_aboutEM = this.main.hasClass('about-emptied-memories');
this.is_panel = this.main.hasClass('about-panel');
this.is_panoramic = this.main.hasClass('about-panoramic');
this.is_artist = this.main.hasClass('artist');
this.is_gallery = this.main.hasClass('work-gallery');
this.is_video = this.main.hasClass('work-video');
this.is_echo = this.main.hasClass('echo');
this.is_contact = this.main.hasClass('contact');
return this.is_book = this.main.hasClass('book');
};
Site.prototype.startLoadingImage = function() {
this.init();
this.html.removeClass('loading').addClass('loaded');
};
Site.prototype.leave = function(event) {
var href, t,
_this = this;
t = $(event.currentTarget);
href = t.attr('href');
window.leave = true;
if (this.is_home) {
this.home.leave();
}
this.scrollToOrigin(function() {
_this.loadContent(href);
return history.pushState('', 'New URL: ' + href, href);
});
return event.preventDefault();
};
Site.prototype.scrollToOrigin = function(callback) {
var distance, duration;
distance = dist(this.body.scrollTop(), this.body.scrollLeft(), 0, 0);
duration = 100000 / distance;
if (duration > 1000) {
duration = 1000;
}
if (distance === 0) {
duration = 0;
}
return this.body.animate({
scrollTop: 0,
scrollLeft: 0
}, duration, callback);
};
Site.prototype.scrollToMiddle = function() {
return this.body.animate({
scrollTop: (this.body.height() - this.window.height()) / 2,
scrollLeft: 0
}, 500);
};
Site.prototype["new"] = function(slug) {
var ns;
ns = slug.charAt(0).toUpperCase() + slug.slice(1);
return this[slug] = new window[ns]();
};
return Site;
})();
window.site = new Site();
site.setup();
}).call(this);
|
'use strict';
const person_1 = {
name: 'Wer',
family: 'Ber',
age: 84,
sayHey () {
console.log(`Hey i am ${this.name} ${this.family} ${this.age}`);
},
goToHome () {
console.log('i go to home');
}
}
const person_2 = 'Pasha Pupkin';
const person_3 = {
name: 'Zara',
family: 'Mara',
age: 23,
sayHey () {
console.log(`Hey i am ${this.name} ${this.family} ${this.age}`);
},
goToHome () {
console.log('i go to home');
}
}
person_1.sayHey();
person_3.sayHey();
|
import React from 'react'
import styled from 'styled-components'
import { NavLink } from 'react-router-dom'
const Main = styled.div`
display: flex;
flex-direction: column;
padding-bottom: 2rem;
justify-content: center;
align-items: center;
padding-top: 2rem;
box-sizing: border-box;
width: 100%;
height: 70%;
font-size: 1rem;`
const Second = styled.div`
display: flex;
width: 70%;
height: 80%;
box-sizing: border-box;
padding-right: 15rem;
justify-content: space-between;
align-items: center;
span {
letter-spacing: 0.25rem;
text-transform: uppercase;
color: whitesmoke;
box-sizing: border-box;
}
ul {
display: flex;
flex-direction: column;
list-style-type: none;
margin: 0;
box-sizing: border-box;
padding: 1rem;
list-style-type: none;
justify-content: space-between;
a.navlink:hover {
color: whitesmoke;
letter-spacing: 1px;
transition: all 0.4s ease 0s;
box-shadow: 0px 5px 40px -10px rgba(0,0,0,0.57);
}
li {
margin-bottom: 1rem;
a {
color: currentColor;
text-decoration: none;
}
a:hover {
color: whitesmoke;
letter-spacing: 1px;
transition: all 0.4s ease 0s;
box-shadow: 0px 5px 40px -10px rgba(0,0,0,0.57);
}
}
}`
const Third = styled.div`
display: flex;
width: 70%;
height: 20%;
border-top: 0.08rem solid currentColor;
justify-content: space-between;
align-items: flex-end;
box-sizing: border-box;
div {
display: flex;
box-sizing: border-box;
width: 40%;
ul {
display: flex;
width: 100%;
margin: 0;
box-sizing: border-box;
padding: 0;
list-style-type: none;
justify-content: space-between;
align-self: flex-end;
a {
text-decoration: none;
color: white;
}
a:hover {
color: whitesmoke;
letter-spacing: 1px;
transition: all 0.4s ease 0s;
box-shadow: 0px 5px 40px -10px rgba(0,0,0,0.57);
}
}
}`
const FooterDiv = () => {
return (
<Main>
<Second>
<div>
<span>Say Hi!</span>
<ul>
<li><a href="mailto:oguejioforalexander@gmail.com">oguejioforalexander@gmail.com</a></li>
<li></li>
</ul>
</div>
<ul>
<NavLink to = {'/projects'} className='navlink' style={{ textDecoration: 'none', color: 'white' }}><li>Projects</li></NavLink>
<li><a href='https://res.cloudinary.com/pureretail/image/upload/v1578061198/private/Alexander_Oguejiofor_-_FS_nce7x3.pdf' rel="noopener noreferrer" target="_blank" >Resume</a></li>
</ul>
</Second>
<Third>
<span>© Alexander Oguejiofor 2019</span>
<div>
<ul>
<li><a href='https://www.linkedin.com/in/alexanderoguejiofor/' rel="noopener noreferrer" target="_blank" >LinkedIn</a></li>
<li><a href='https://www.goodreads.com/user/show/26479310-pokerface' rel="noopener noreferrer" target="_blank" >Goodreads</a></li>
<li><a href='https://twitter.com/master_elodin' rel="noopener noreferrer" target="_blank" >Twitter</a></li>
<li><a href='https://github.com/kip-guile' rel="noopener noreferrer" target="_blank" >Github</a></li>
</ul>
</div>
</Third>
</Main>
)
}
export default FooterDiv
|
'use strict';
const FAST = require('./lib/FAST');
module.exports.FAST = FAST;
module.exports.contracts = [ FAST ];
|
var servicesModule = angular.module('errorService', []);
servicesModule.factory('ErrorService', function() {
return {
errorMessage: null,
setError: function(msg) {
this.errorMessage = msg;
},
clear: function() {
this.errorMessage = null;
}
};
});
// register the interceptor as a service
// intercepts ALL angular ajax HTTP calls
servicesModule.factory('errorHttpInterceptor',
function ($q, $location, ErrorService, $rootScope) {
return function (promise) {
return promise.then(
function (response) {
return response;
},
function (response) {
if (response.status === 401) {
$rootScope.$broadcast('event:loginRequired');
} else if (response.status >= 400 && response.status < 500) {
ErrorService.setError('Server was unable to find' +
' what you were looking for... Sorry!!');
}
return $q.reject(response);
}
);
};
}
);
// Add the error service as an interceptor.
servicesModule.config(
function ($httpProvider) {
$httpProvider.responseInterceptors.push('errorHttpInterceptor');
}
);
|
/* global ODSA */
(function ($) {
"use strict";
// AV variables
var initialArray,
tree,
treeSize = 25,
// Load the configurations created by odsaAV.js
config = ODSA.UTILS.loadConfig({av_container: "jsavcontainer"}),
interpret = config.interpreter,
code = config.code,
codeOptions = {after: {element: $(".instructions")}, visible: true},
// Create a JSAV instance
av = new JSAV($("#jsavcontainer"));
av.recorded(); // we are not recording an AV with an algorithm
av.code(code, codeOptions);
function initialize() {
initialArray = generateValues(treeSize, 10, 100); //No duplicates!
//clear old binary tree
if (tree) {
tree.clear();
}
//create binary tree
tree = av.ds.rbtree({center: true, visible: true, nodegap: 5});
for (var i = 0; i < treeSize; i++) {
//find emptynode where the value will be inserted
var node = tree.insert(initialArray[i]);
// fix the tree by recoloring nodes and performing rotations
node.repair();
}
colorTreeRed(tree.root());
tree.layout();
tree.click(function () {
this.toggleColor();
});
return tree;
}
function modelSolution(jsav) {
var modelTree = jsav.ds.rbtree({center: true, visible: true, nodegap: 5});
jsav._undo = [];
for (var i = 0; i < treeSize; i++) {
//find emptynode where the value will be inserted
var node = modelTree.insert(initialArray[i]);
// fix the tree by recoloring nodes and performing rotations
node.repair();
modelTree.layout();
}
jsav.stepOption("grade", true);
jsav.step();
jsav.umsg(interpret("av_ms_example"));
jsav.displayInit();
return modelTree;
}
//generate values without duplicates
function generateValues(n, min, max) {
var arr = [];
var val;
for (var i = 0; i < n; i++) {
do {
val = Math.floor(min + Math.random() * (max - min));
} while ($.inArray(val, arr) !== -1);
arr.push(val);
}
return arr;
}
function colorTreeRed(node) {
if (!node) {
return;
}
node.colorRed();
colorTreeRed(node.left());
colorTreeRed(node.right());
}
function blackNodesBetweenRootAndLeaves(root) {
if (!root) {
return 0;
}
var left = blackNodesBetweenRootAndLeaves(root.left());
var right = blackNodesBetweenRootAndLeaves(root.right());
if (left === right && left !== -1) {
return left + (root.hasClass("blacknode") ? 1 : 0);
} else {
return -1;
}
}
function redHaveOnlyBlackChildren(root) {
if (!root) {
return true;
}
if (!redHaveOnlyBlackChildren(root.left())) {
return false;
}
if (!redHaveOnlyBlackChildren(root.right())) {
return false;
}
if (root.isRed() &&
(
(root.left() && root.left().isRed()) ||
(root.right() && root.right().isRed())
)
) {
return false;
}
return true;
}
JSAV._types.Exercise.prototype.grade = function () {
var score = 0;
//black root
score += tree.root().hasClass("blacknode") ? 1 : 0;
//paths from the leaves to the roots have an equal amount of black nodes
score += blackNodesBetweenRootAndLeaves(tree.root()) > 0 ? 1 : 0;
//red nodes only have black children
score += redHaveOnlyBlackChildren(tree.root()) ? 1 : 0;
score = score === 3 ? 1 : 0;
this.score = {
correct: score,
fix: 0,
student: score,
total: 1,
undo: 0
};
return this.score;
};
var exercise = av.exercise(modelSolution, initialize, {
compare: { css: "background-color" },
modelDialog: { minWidth: "700px" },
feedback: "atend"
});
exercise.reset();
}(jQuery));
|
import axios from "axios";
module.exports = async (req, res) => {
try {
const result = await axios.get(
"http://apims.doe.gov.my/data/public/CAQM/last24hours.json"
);
res.status(200).json(result.data);
} catch (error) {
console.log("error fetching api: ", error);
return res.status(404).json(error);
}
};
|
import { hotelsEffects } from "../features/hotels/hotelsEffect";
import { all } from "redux-saga/effects";
export default function* effects() {
yield all([
hotelsEffects(),
]);
}
|
import React from 'react';
import Note from './Note';
import { useSelector } from 'react-redux';
const NoteGrid = () => {
const notes = useSelector((state) => state.notes);
return notes.map((note) => (
<Note
key={note.id}
id={note.id}
title={note.title}
content={note.content}
/>
));
};
export default NoteGrid;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ReportCreate {
constructor(model) {
if (!model)
return;
this.name = model.name;
}
}
Object.seal(ReportCreate);
exports.default = ReportCreate;
|
import AsyncWatch from 'async-watch';
// INIT Game STATE //
const truth = {
winning: true,
turn_user: false,
power_on: false,
seq_length: 0,
seq_position: 0,
computer_seq: [],
user_seq: [],
panels: {
red: document.querySelector('.red'),
green: document.querySelector('.green'),
blue: document.querySelector('.blue'),
yellow: document.querySelector('.yellow'),
all: document.querySelectorAll('.panel'),
},
user_controls: {
power_switch: document.querySelector('.power-switch'),
start_reset: document.querySelector('.start_reset'),
strict: document.querySelector('.strict'),
},
};
// Create NEW Instance of GAME state //
let game = Object.assign({}, truth);
// Observe Object via ES6 proxy //
const handler = {
set(target, key, value) {},
};
const stateShift = new Proxy(game, handler);
// Create sequence functions //
const randomNumber = () => Math.floor(Math.random() * 4);
const convertToColor = num => ['R', 'B', 'Y', 'G'][num];
const genSeq = () => {
let sequence = [];
for (let i = 0; i < 20; i++) {
const segment = [convertToColor(randomNumber())];
sequence =
i % 2 === 0 ? [...sequence, ...segment] : [...segment, ...sequence];
}
return sequence;
};
const updateState = (update, state = game) => {
game = Object.assign({}, state, ...update);
console.log(game);
};
// Panel event handler //
const all = game.panels.all,
red = game.panels.red,
blue = game.panels.blue,
green = game.panels.green,
yellow = game.panels.yellow,
simon = document.querySelector('.simon'),
soundHandler = (target) => {
target.play();
},
panelHandler = (e) => {
if (NodeList.prototype.isPrototypeOf(e) || e[1]) {
// check for nodelist
sequencePlayer([...e, ...e, ...e], 200);
}
e = e.target ? e.target : e;
e.classList.add('active');
soundHandler(document.getElementById(`panel-tone-${e.classList[1]}`));
setTimeout(() => {
e.classList.remove('active');
}, 500);
};
// TURN ON //
const on_off = document.getElementById('on-off');
const slider = document.querySelector('.switch');
on_off.addEventListener('click', () => {
slider.classList.toggle('on');
on_off.innerHTML = on_off.innerHTML === 'ON' ? 'OFF' : 'ON';
panelHandler(all);
});
simon.addEventListener('mousedown', panelHandler);
const sequencePlayer = (seq, int = 750) => {
let db = { R: red, G: green, B: blue, Y: yellow },
index = 0;
window.interval = setInterval(() => {
if (index < seq.length) {
const current = seq[index];
panelHandler(db[current]);
index++;
} else {
clearInterval(window.interval);
}
}, int);
};
document.querySelector('.start-reset').addEventListener('click', () => {
updateState({
winning: true,
seq_length: 1,
computer_seq: genSec(),
});
});
// sequencePlayer(['R', 'G', 'B', 'Y', 'R', 'G', 'B', 'Y', 'R', 'G', 'B', 'Y'], 12)
/*
Change START STOP to Start/Reset
Only 1 handler for both start and reset functions
on start reset event - set user counter to 0, and step to 1,
create handler for user input stage:
1) counts down from the current seq length to 0
1b)display countdown in steps display as both user and computer progress
through their sequences
2) at each press, check accuracy against computer seq.
3) wrong press should blink all colors 3 times, while counting down
3..., 2..., 1... - then playback the same sequence that prompted the
user error.
4) reset button changed to STRICT mode - generate random sequence, at a
random length, allow only one try to properly complete seq - BOTH win
and loss should trigger next random sequence
*/
|
const bingo = (function () {
const bingos = [
'Everybody (except Vojta) trying to stay the heck away from the start arrow at the fireplace.',
'"Waiting for Vojta to start!"',
'Vojta says he will go first',
'"I’m fine. Next."',
'"That’s the perfect channel name!"',
'Someone asking "What did I miss" in regards to our channel name.',
'Someone has a bad case of FOMO because they missed 2 minutes of a meeting',
'Someone calls the unit wholesome.',
'Divorce rate is mentioned.',
'Someone is corrected that we don’t have "awkward" but "comfortable" silence.',
'Coffee is mentioned.',
'The lack of coffee is mentioned.',
'Some confusion is happening about type / version / configuration and what’s an integration anyways?',
'Unprompted long silence.',
'There are _possible_ squirrels!',
'People posting how they are emotionally stunted because there are no blob cat emojis in zoom.',
'"LET ME IINNNNNN" in slack.',
'"I’m happy to see you all!"',
"Mural gets more check-in circle decorations then yellow notes.",
"Suddenly we talk about books and half of us get sci-fi FOMO.",
"More communication happens in the zoom chat than in the actual call.",
"There's a mention of good skin.",
"Peter has written a blog post about something.",
"Implementation ended in tragedy.",
'"Good meeting"',
'We about that we are the most awesome unit.',
'We about why we are the most awesome unit.',
'_Someone_ is showing of dolphins they saw that morning.',
'"Do you think we annoy others by always mentioning how we are the most awesome unit?"',
]
const winner = [
[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,13,14,15],
[0,5,10,15],
[3, 6, 9, 12],
[0,4,8,12],
[1,5,9,13],
[2,6,10,14],
[3,7,11,15],
[0,4,8,12],
[1,5,9,13],
[2,6,10,14],
[3,7,11,15],
]
const hitBingos = [];
function shuffle(list) {
const listToReorder = [...list]
for (let i = listToReorder.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = listToReorder[i];
listToReorder[i] = listToReorder[j];
listToReorder[j] = temp;
}
return listToReorder
}
function addContentToCells(cells) {
const randomBingos = shuffle(bingos)
for (let i = 0; i < cells.length; i++) {
cells[i].setAttribute('data-cell-id', i)
cells[i].innerHTML = randomBingos[i]
}
}
function toggleClass(cell) {
if(cell.classList.contains('bingod')) {
cell.classList.remove("bingod")
} else {
cell.classList.add("bingod")
}
}
function updateBingoList(cellId) {
const index = hitBingos.indexOf(cellId)
if(index >= 0) {
hitBingos.splice(index, 1);
} else {
hitBingos.push(cellId)
}
}
function checkHits(hitsNeeded, currentHits) {
return hitsNeeded.every( entry => {
return currentHits.includes(entry)
})
}
function checkForBingo() {
if(hitBingos.length < 4) return
const weHaveAWinner = winner.some( winnerList => {
const list = winnerList.map( entry => entry.toString())
return checkHits(list, hitBingos)
})
if(weHaveAWinner) {
showOverlay()
}
}
function registerEventListeners() {
addEventListener('click', function(event) {
const cellId = event.target.getAttribute('data-cell-id')
if(!cellId) return
toggleClass(event.target)
updateBingoList(cellId)
checkForBingo()
});
}
function showOverlay() {
document.querySelector('.overlay--hidden').classList.remove('overlay--hidden')
}
return {
start: function() {
const cells = document.querySelectorAll('[data-cell-id="0"]')
addContentToCells(cells)
registerEventListeners()
},
restart: function() {
location.reload();
}
};
})();
|
/** @jsx element */
import {element} from 'deku';
let render=({props,children})=>{
let checkbox_id='hojicha--tab-nav--item--radio--'+props.group+'--'+props.name;
return (
<div class="hojicha--tab-nav--item">
<input name={`hojicha--tab-nav--item--group--${props.group}`} type="radio" checked={props.default} class="hojicha--tab-nav--item--radio" id={checkbox_id} onClick={props.onClick}/>
<label class="hojicha--tab-nav--item--label" for={checkbox_id} onClick={props.onClick}>{children}</label>
</div>
);
};
export default render;
|
/*
-编写一个hello.js文件,这个hello.js文件就是一个模块,
模块的名字就是文件名(去掉.js后缀),所以hello.js文件就是名为hello的模块
-在模块中定义的函数可用module.exports = 函数名 作为模块的输出暴露出去
ie. module.exports = greet; //greet() 是hello.js里的一个函数
在其他模块里使用: var sth = require("./hello); //要有path
-一个模块想要对外暴露变量(函数也是变量),可以用module.exports = variable;,
一个模块要引用其他模块暴露的变量,用var ref = require('module_name');就拿到了
引用模块的变量。
module.exports = {
foo: function () { return 'foo'; }
};
或者:
module.exports = function () { return 'foo'; };
*/
|
sliderSettings = () => {
$('#slider').slick({
infinite: true,
autoplay: true,
autoplaySpeed: 2000,
arrows: false,
dots: true,
fade: true,
draggable: false
});
};
popupSwitcher = (element, className) => {
element.classList.toggle(className)
document.body.classList.toggle('nonscroll');
}
popupSwitchHandler = () => {
const sumonButton = document.querySelectorAll('button.button-request');
const shadow = document.querySelector('.shadow');
const modal = document.querySelector('.modal');
sumonButton.forEach(button => {
button.addEventListener('click', () => {
popupSwitcher(modal, 'open')
});
});
shadow.addEventListener('click', () => {
popupSwitcher(modal, 'open')
});
}
headerMenuSwitcherHandler = () => {
const header = document.querySelector('header');
console.log(header)
const burger = header.querySelector('.burger')
burger.addEventListener('click', () => {
popupSwitcher(header, 'menu-expandet');
})
}
formValidationHandler = () => {
const form = document.querySelector('.request-demo');
const message = form.querySelector('.request-demo__message');
const inputs = form.querySelectorAll('.require');
const reEmail = /\S+@\S+\.\S+/;
const reWeb = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
// require fields
form.addEventListener('submit', (event) => {
event.preventDefault()
form.querySelectorAll('.error').forEach(input => input.classList.remove('error'));
let flag = true;
for (const input of inputs) {
const inputValue = input.value;
if (
(!inputValue || inputValue.trim() == '')
|| (input.classList.contains('request-demo__email') && !reEmail.test(inputValue))
|| (input.classList.contains('request-demo__web') && !reWeb.test(inputValue))
) {
input.classList.add('error');
flag = false;
break
}
}
if (!flag) return
form.submit()
});
// message limitation
message.oninput = () => {
if (message.value.length >= 180) {
message.classList.add('error')
} else message.classList.remove('error')
}
}
document.addEventListener("DOMContentLoaded", function() {
headerMenuSwitcherHandler();
formValidationHandler();
popupSwitchHandler();
sliderSettings();
});
|
window._UXK_Components.PROGRESSVIEW = {
props: function (dom) {
return {
progress: $(dom).attr('progress') ? Math.max(0.0, Math.min(1.0, parseFloat($(dom).attr('progress')))) : 0.5,
tintColor: $(dom).attr('tintColor') || "#209b53",
}
},
setProps: function (dom, props) {
var progressViewProps = window._UXK_Components.PROGRESSVIEW.props(dom);
var width = dom.frame != undefined ? dom.frame.width : 0.0;
if (width == 0.0) {
dom.setAttribute("hidden", 'true');
return;
}
else {
dom.setAttribute("hidden", 'false');
}
dom.querySelector("[vKey='trackView']").setAttribute("backgroundColor", progressViewProps.tintColor);
dom.querySelector("[vKey='trackView']").setAttribute("frame", '0,0,' + ((width - 0) * progressViewProps.progress) + ',2');
dom.querySelector("[vKey='blurView']").setAttribute("frame", '0,0,' + (width - 0) + ',2');
},
onLoad: function (dom) {
$(dom).onLayout(function (frame) {
dom.frame = frame;
$(dom).update();
})
$(dom).value('frame', function (frame) {
dom.frame = frame;
$(dom).update();
})
},
}
$.createIMP('setProgress', 'PROGRESSVIEW', function (progress, animated) {
if (animated === undefined) {
animated = true;
}
$(this).attr('progress', progress);
if (animated === true) {
$(this).animate();
}
else {
$(this).update();
}
})
|
/**
* The Index of Routes
*/
module.exports = function(app) {
// The boner route
app.use('/users', require('./routes/users'));
// The boner route
app.use('/alerts', require('./routes/alerts'));
// The signup route
app.use('/signup', require('./routes/signup'));
// The event route
app.use('/events', require('./routes/events'));
}
|
// SELECTING ALL TEXT ELEMENTS
var id = document.forms['myform']['id'];
var pw1 = document.forms['myform']['pw1'];
var pw2 = document.forms['myform']['pw2'];
var username = document.forms['myform']['name'];
var genderCheck = document.forms['myform']['gender'];
var birthCheck = document.forms['myform']['birth'];
var emailCheck = document.forms['myform']['email'];
// SELECTING ALL ERROR DISPLAY ELEMENTS
var id_error = document.getElementById('iderr');
var pw1_error = document.getElementById('pw1err');
var pw2_error = document.getElementById('pw2err');
var name_error = document.getElementById('nameerr');
var gender_error = document.getElementById('gendererr');
var birth_error = document.getElementById('birtherr');
var email_error = document.getElementById('emailerr');
// SETTING ALL EVENT LISTENERS
id.addEventListener('blur', idVerify, true);
pw1.addEventListener('blur', pw1Verify, true);
pw2.addEventListener('blur', pw2Verify, true);
username.addEventListener('blur', nameVerify, true);
genderCheck.addEventListener('blur', genderVerify, true);
birthCheck.addEventListener('blur', birthVerify, true);
emailCheck.addEventListener('blur', emailVerify, true);
// validation function
function Validate() {
// validate id
if (id.value == "") {
document.getElementById('id_div').style.color = "#ff5159";
id_error.textContent = "아이디를 입력해주세요.";
id.focus();
return false;
}
// validate id
if (id.value.length > 6) {
document.getElementById('id_div').style.color = "#ff5159";
id_error.textContent = "최대6글자로 입력해주세요.";
id.focus();
return false;
}
// validate pw1
if (pw1.value == "") {
document.getElementById('pw1_div').style.color = "#ff5159";
pw1_error.textContent = "비밀번호를 입력해주세요.";
pw1.focus();
return false;
}
// validate pw1
if (pw1.value.length <= 7) {
document.getElementById('id_div').style.color = "#ff5159";
pw1_error.textContent = "최소8자이상 입력해주세요.";
pw1.focus();
return false;
}
// check if the two passwords match
if (pw1.value != pw2.value) {
document.getElementById('pw2_div').style.color = "#ff5159";
pw2_error.innerHTML = "비밀번호가 동일하지 않습니다.";
return false;
}
// validate name
if (username.value == "") {
document.getElementById('name_div').style.color = "#ff5159";
name_error.textContent = "이름을 입력해주세요";
username.focus();
return false;
}
// validate name
if (username.value.length < 2) {
document.getElementById('name_div').style.color = "#ff5159";
name_error.textContent = "이름을 확인해주세요";
username.focus();
return false;
}
// validate gender
for(var i = 0; i<=genderCheck.length-1; i++){
genderCheck[i].addEventListener('blur', genderVerify, true);}
if (genderCheck[0].checked==false && genderCheck[1].checked==false){
document.getElementById('gender_div').style.color = "#ff5159";
gender_error.textContent = "성별을 입력해주세요";
gender_error.focus();
return false;
}
// validate birth
if (birthCheck.value == ""){
document.getElementById('birth_div').style.color = "#ff5159";
birth_error.textContent = "생년월일을 입력해주세요";
birth_error.focus();
return false;
}
// validate email
if (emailCheck.value == "") {
document.getElementById('email_div').style.color = "#ff5159";
email_error.textContent = "이메일을 입력해주세요";
emailCheck.focus();
return false;
}
}
// event handler functions
function idVerify() {
if (id.value != "") {
id_error.innerHTML = "";
return true;
}
}
function pw1Verify() {
if (pw1.value != "") {
pw1_error.innerHTML = "";
return true;
}
}
function pw2Verify() {
if (pw1.value === pw2.value) {
pw2_error.innerHTML = "";
return true;
}
}
function nameVerify() {
if (username.value != "") {
name_error.innerHTML = "";
return true;
}
}
function genderVerify() {
if(genderCheck[0].checked == true || genderCheck[1].checked == true){
gender_error.innerHTML = "";
return true;
}
}
var selectValue = birthCheck.options[birthCheck.selectedIndex].value;
function birthVerify() {
if (birthCheck.value !== "" && selectValue !== ""){
document.getElementById('birth_div').style.color = "#ff5159";
birth_error.innerHTML = " ";
return true;
}
}
function emailVerify() {
if (emailCheck.value !== ""){
document.getElementById('email_div').style.color = "#ff5159";
email_error.innerHTML = " ";
return true;
}
}
|
'use strict';
(function () {
define([
'require',
'angular',
'app'
], function (require, angular, app) {
config.$inject = ['$locationProvider', '$routeProvider'];
function config($locationProvider, $routeProvider) {
$routeProvider.when('/', {
templateUrl: './application/base/views/index.html',
controller: 'BaseIndexCtrl',
resolve: {
load: function ($q) {
var deferred = $q.defer();
require(['./application/base/loader'], function () {
deferred.resolve();
});
return deferred.promise;
}
}
});
$routeProvider.when('/list', {
templateUrl: './application/book/views/list.html',
controller: 'BookListCtrl',
resolve: {
load: function ($q) {
var deferred = $q.defer();
require(['./application/book/loader'], function () {
deferred.resolve();
});
return deferred.promise;
}
}
});
$routeProvider.when('/view', {
templateUrl: './application/book/views/view.html',
controller: 'BookViewCtrl',
resolve: {
load: function ($q) {
var deferred = $q.defer();
require(['./application/book/loader'], function () {
deferred.resolve();
});
return deferred.promise;
}
}
});
$routeProvider.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}
return app.config(config);
});
})();
|
import Ember from 'ember';
import NewOrEdit from 'ui/mixins/new-or-edit';
import ModalBase from 'lacsso/components/modal-base';
export default ModalBase.extend(NewOrEdit, {
classNames: ['lacsso', 'modal-container', 'large-modal'],
originalModel: Ember.computed.alias('modalService.modalOpts'),
editing: true,
isService: false,
isSidekick: false,
loading: true,
model: null,
primaryResource: Ember.computed.alias('model.instance'),
launchConfig: Ember.computed.alias('model.instance'),
portsArray: null,
linksArray: null,
actions: {
setPorts(ports) {
this.set('portsArray', ports);
},
setLinks(links) {
this.set('linksArray', links);
},
save() {
this._super(...arguments);
this.send('cancel');
}
},
didInsertElement: function() {
Ember.run.next(this, 'loadDependencies');
},
loadDependencies: function() {
var instance = this.get('originalModel');
return Ember.RSVP.all([
instance.followLink('ports'),
instance.followLink('instanceLinks'),
this.get('store').findAll('host'), // Need inactive ones in case a link points to an inactive host
]).then((results) => {
var model = Ember.Object.create({
instance: instance.clone(),
ports: results[0],
instanceLinks: results[1],
allHosts: results[2],
});
this.setProperties({
originalModel: instance,
model: model,
loading: false,
});
});
},
didSave: function() {
return Ember.RSVP.all([
this.savePorts(),
this.saveLinks(),
]);
},
savePorts: function() {
var promises = [];
this.get('portsArray').forEach(function(port) {
var neu = parseInt(port.public,10);
if ( isNaN(neu) )
{
neu = null;
}
var obj = port.obj;
if ( neu !== Ember.get(obj,'publicPort') )
{
//console.log('Changing port',obj.serialize(),'to',neu);
obj.set('publicPort', neu);
promises.push(obj.save());
}
});
return Ember.RSVP.all(promises);
},
saveLinks: function() {
var promises = [];
this.get('linksArray').forEach(function(link) {
var neu = link.targetInstanceId;
var obj = link.obj;
if ( neu !== Ember.get(obj,'targetInstanceId') )
{
//console.log('Changing link',obj.serialize(),'to',neu);
obj.set('targetInstanceId', neu);
promises.push(obj.save());
}
});
return Ember.RSVP.all(promises);
},
doneSaving: function() {
this.sendAction('dismiss');
},
});
|
import React from 'react';
import { Scene, Router, Actions } from 'react-native-router-flux';
import LoginForm from './components/LoginForm';
import EventList from './components/EventList';
import MyEventList from './components/MyEventList';
const RouterComponent = () => {
return (
<Router sceneStyle={{ paddingTop: 65 }}>
<Scene key="auth">
<Scene
key="login"
component={LoginForm}
title="Please Login"
/>
</Scene>
<Scene key="main">
<Scene
onRight={() => Actions.myEvents()}
rightTitle="My Events"
key="eventList"
component={EventList}
title="Events"
style={{ flex: 1 }}
initial
/>
<Scene
key="myEvents"
component={MyEventList}
title="My Events"
/>
</Scene>
</Router>
);
};
export default RouterComponent;
|
var DS_DonVi, DS_PO, DS_PO_TD, DS_PO_Loc;
var DS_VatTu, DS_SoHD, DS_TenVT, DS_MaTD, HopDong_ID;
var PO_ID_Sua;
var PO_HD_ID;
var BienChiTietPO, Bien_ChiTiet_VatTu;
var VatTu_ID_PO;
var Path, Path_Sua;
var VatTu_ID, MaDVT;
var DS_VatTu_PO;
var Path_PO, Path_PO_DC;
var GiaTriHopDong_ConLai;
var PO_ChiTiet_ID;
var DS_VT_DayNhay;
var DS_TamUng, DS_PO_Con;
$(document).ready(function () {
//document.oncontextmenu = function () { return false; }
$("#main-menu-toggle").click();
//$("#main-menu-min").click();
$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#tb_BoLoc").show() : $("#tb_BoLoc").hide();
//#region Upload
$('#files_upload').kendoUpload({
async: {
autoUpload: false,
saveUrl: 'UploadFileVB.aspx'
},
error: function (e) {
this.wrapper.closest('.row').siblings().eq(1).find('span').text('Upload không thành công!');
this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-success').toggleClass('text-danger');
},
localization: {
dropFilesHere: 'Kéo thả file vào đây để upload',
headerStatusUploaded: 'Đã upload xong',
headerStatusUploading: 'Đang upload',
select: 'Chọn file...',
statusFailed: 'Upload không thành công',
statusUploaded: 'Đã upload xong',
statusUploading: 'Đang upload',
uploadSelectedFiles: 'Upload'
},
multiple: false,
success: function (e) {
Path = e.response.FilePath;
this.wrapper.closest('.row').siblings().eq(1).find('input').val(e.response.FilePath);
this.wrapper.closest('.row').siblings().eq(1).find('span').text('Đã upload!');
this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-danger').toggleClass('text-success');
},
upload: function (e) {
e.data = { LoaiFile: 'VBPO_Lon' };
},
select: function (e) {
var ext = e.files[0].extension.toLowerCase();
if (ext !== ".pdf" && ext !== ".doc" && ext !== ".docx") {
e.preventDefault();
//alert('Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>');
$("#notification").data("kendoNotification").show({
title: "Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>",
message: "Hãy upload lại!"
}, "error");
return;
}
if (e.files[0].size > 10485760) {
e.preventDefault();
//alert('Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!');
$("#notification").data("kendoNotification").show({
title: "Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!",
message: "Hãy upload lại!"
}, "error");
return;
}
}
});
$('#files_upload_sua').kendoUpload({
async: {
autoUpload: false,
saveUrl: 'UploadFileVB.aspx'
},
error: function (e) {
this.wrapper.closest('.row').siblings().eq(1).find('span').text('Upload không thành công!');
this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-success').toggleClass('text-danger');
},
localization: {
dropFilesHere: 'Kéo thả file vào đây để upload',
headerStatusUploaded: 'Đã upload xong',
headerStatusUploading: 'Đang upload',
select: 'Chọn file...',
statusFailed: 'Upload không thành công',
statusUploaded: 'Đã upload xong',
statusUploading: 'Đang upload',
uploadSelectedFiles: 'Upload'
},
multiple: false,
success: function (e) {
Path_Sua = e.response.FilePath;
this.wrapper.closest('.row').siblings().eq(1).find('input').val(e.response.FilePath);
this.wrapper.closest('.row').siblings().eq(1).find('span').text('Đã upload!');
this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-danger').toggleClass('text-success');
},
upload: function (e) {
e.data = { LoaiFile: 'VBPO_Lon' };
},
select: function (e) {
var ext = e.files[0].extension.toLowerCase();
if (ext !== ".pdf" && ext !== ".doc" && ext !== ".docx") {
e.preventDefault();
//alert('Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>');
$("#notification").data("kendoNotification").show({
title: "Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>",
message: "Hãy upload lại!"
}, "error");
return;
}
if (e.files[0].size > 10485760) {
e.preventDefault();
//alert('Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!');
$("#notification").data("kendoNotification").show({
title: "Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!",
message: "Hãy upload lại!"
}, "error");
return;
}
}
});
$('#btn_sua_upload').click(function () {
$("#tr_download").hide();
$("#tr_upload").show();
Path_Sua = "";
});
$('#fileUpload_PO').kendoUpload({
async: {
autoUpload: false,
saveUrl: 'UploadFileVB.aspx'
},
error: function (e) {
this.wrapper.closest('.row').siblings().eq(1).find('span').text('Upload không thành công!');
this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-success').toggleClass('text-danger');
},
localization: {
dropFilesHere: 'Kéo thả file vào đây để upload',
headerStatusUploaded: 'Đã upload xong',
headerStatusUploading: 'Đang upload',
select: 'Chọn file...',
statusFailed: 'Upload không thành công',
statusUploaded: 'Đã upload xong',
statusUploading: 'Đang upload',
uploadSelectedFiles: 'Upload'
},
multiple: false,
success: function (e) {
Path_PO = e.response.FilePath;
this.wrapper.closest('.row').siblings().eq(1).find('input').val(e.response.FilePath);
this.wrapper.closest('.row').siblings().eq(1).find('span').text('Đã upload!');
this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-danger').toggleClass('text-success');
},
upload: function (e) {
var c = confirm('Vui lòng xác nhận file đã chọn là chính xác');
if (!c) {
e.preventDefault();
return;
}
var ext = e.files[0].extension.toLowerCase();
if (ext !== ".pdf" && ext !== ".doc" && ext !== ".docx") {
e.preventDefault();
//alert('Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>');
$("#notification").data("kendoNotification").show({
title: "Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>",
message: "Hãy upload lại!"
}, "error");
return;
}
e.data = { LoaiFile: 'VBPO_Con' };
}
});
$('#fileUpload_PO_DC').kendoUpload({
async: {
autoUpload: false,
saveUrl: 'UploadFileVB.aspx'
},
error: function (e) {
this.wrapper.closest('.row').siblings().eq(1).find('span').text('Upload không thành công!');
this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-success').toggleClass('text-danger');
},
localization: {
dropFilesHere: 'Kéo thả file vào đây để upload',
headerStatusUploaded: 'Đã upload xong',
headerStatusUploading: 'Đang upload',
select: 'Chọn file...',
statusFailed: 'Upload không thành công',
statusUploaded: 'Đã upload xong',
statusUploading: 'Đang upload',
uploadSelectedFiles: 'Upload'
},
multiple: false,
success: function (e) {
Path_PO_DC = e.response.FilePath;
this.wrapper.closest('.row').siblings().eq(1).find('input').val(e.response.FilePath);
this.wrapper.closest('.row').siblings().eq(1).find('span').text('Đã upload!');
this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-danger').toggleClass('text-success');
},
upload: function (e) {
var c = confirm('Vui lòng xác nhận file đã chọn là chính xác');
if (!c) {
e.preventDefault();
return;
}
var ext = e.files[0].extension.toLowerCase();
if (ext !== ".pdf" && ext !== ".doc" && ext !== ".docx") {
e.preventDefault();
//alert('Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>');
$("#notification").data("kendoNotification").show({
title: "Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>",
message: "Hãy upload lại!"
}, "error");
return;
}
e.data = { LoaiFile: 'VBPO_DC' };
}
});
//#endregion
//#region DataSource
DS_VT_DayNhay = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_DM_VT_DayNhay.aspx",
data: {
cmd: 'LayDanhSach_DayNhay'
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 3
});
DS_MaTD = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_HopDong_CT.aspx",
data: {
cmd: 'HopDong_CT_SelectAll_MaTD'
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
});
//DS_TenVT = new kendo.data.DataSource({
// transport: {
// read: function (options) {
// $.ajax({
// type: "POST",
// url: "assets/ajax/Ajax_HopDong_CT.aspx",
// data: {
// cmd: 'HopDong_CT_SelectAll_TenVT'
// },
// dataType: 'json',
// success: function (result) {
// options.success(result);
// }
// });
// }
// }
//});
DS_SoHD = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_HopDong_CT.aspx",
data: {
cmd: 'HopDong_CT_SelectAll_MaHD'
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
});
DS_DonVi = new kendo.data.DataSource({
sort: { field: "ID", dir: "asc" },
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_DanhMuc.aspx",
data: {
cmd: 'DS_DonVi'
},
dataType: 'json',
success: function (result) {
//options.success(result);
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
});
//DS_VatTu = new kendo.data.DataSource({
// transport: {
// read: function (options) {
// $.ajax({
// type: "POST",
// url: "assets/ajax/Ajax_HopDong_CT.aspx",
// data: {
// cmd: 'HopDong_CT_SelectAll'
// },
// dataType: 'json',
// success: function (result) {
// options.success(result);
// }
// });
// }
// },
// pageSize: 5
//});
//DS_VatTu = new kendo.data.DataSource({
// requestEnd: function (e) {
// e.response.d = JSON.parse(e.response.d);
// },
// schema: {
// data: 'd.Data',
// total: 'd.Total[0].Total'
// },
// pageSize: 5,
// serverPaging: true,
// serverSorting: true,
// sort: {
// field: 'PO_ID',
// dir: 'desc'
// },
// transport: {
// read: {
// contentType: "application/json; charset=utf-8",
// dataType: 'json',
// type: 'POST',
// url: "assets/ajax/Ajax_HopDong_CT.aspx/HopDong_CT_SelectAll"
// },
// parameterMap: function (options, operation) {
// return kendo.stringify(options);
// }
// }
//});
DS_VatTu = new kendo.data.DataSource({
data:[]
});
DS_PO = new kendo.data.DataSource({
requestEnd: function (e) {
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO"
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
DS_PO_TD = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'Lay_DS_PO_TD'
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
},
pageSize: 7
});
//#endregion
//#region Control
var notification = $("#notification").kendoNotification({
position: {
pinned: true,
top: 50,
right: 450
},
autoHideAfter: 2000,
stacking: "down",
templates: [
{
type: "error",
template: $("#errorTemplate").html()
},
{
type: "upload-success",
template: $("#successTemplate").html()
}
],
show: function (e) {
e.element.parent().css('z-index', 22222);
}
}).data("kendoNotification");
$("#grid_thanhvien").kendoGrid({
pageable: {
messages: {
display: "Tổng số {2} thành viên",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
editable: true,
navigatable: true,
//edit: function (e) {
// var input = e.container.find(".k-input");
// input.val("");
//},
columns:
[
{
title: "Thành viên",
headerAttributes: {
class: "header_css"
},
field: "Ten_ThanhVien",
editor: function nonEditor(container, options) {
container.text(options.model[options.field]);
},
attributes: {
class: "row_css",
style: "font-weight:bold;"
},
width: 200
},
{
title: "Giá trị đề nghị",
headerAttributes: {
class: "header_css"
},
field: "GiaTri_DeNghi",
template: "#= GiaTri_DeNghi== null ? 0 : OnChangeFormat(GiaTri_DeNghi) #",
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoNumericTextBox({
format: '#',
decimals: 0,
min: 0
});
},
attributes: {
class: "row_css",
style: "font-weight:bold;color:red;background-color:lightyellow;"
},
width: 200
},
{
title: "Số VB đề nghị",
headerAttributes: {
class: "header_css"
},
field: "SoVB_DeNghi",
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 200
},
{
title: "Ngày VB đề nghị",
headerAttributes: {
class: "header_css"
},
field: "NgayVB_DeNghi",
template: "#= NgayVB_DeNghi == null || NgayVB_DeNghi == '' ? '' : kendo.toString(kendo.parseDate(NgayVB_DeNghi, 'dd/MM/yyyy'), 'dd/MM/yyyy') #",
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoDatePicker({
format: "dd/MM/yyyy"
});
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 150
},
{
title: "Tài khoản thụ hưởng",
headerAttributes: {
class: "header_css"
},
field: "TaiKhoanThuHuong",
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 200
},
{
title: "Tại ngân hàng",
headerAttributes: {
class: "header_css"
},
field: "TaiNganHang",
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 200
},
{
title: "Số VB bão lãnh",
headerAttributes: {
class: "header_css"
},
field: "SoVB_BaoLanh",
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 200
},
{
title: "Ngày VB bão lãnh",
headerAttributes: {
class: "header_css"
},
field: "NgayVB_BaoLanh",
template: "#= NgayVB_BaoLanh == null || NgayVB_BaoLanh == '' ? '' : kendo.toString(kendo.parseDate(NgayVB_BaoLanh, 'dd/MM/yyyy'), 'dd/MM/yyyy') #",
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoDatePicker({
format: "dd/MM/yyyy"
});
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 150
},
{
title: "Ngân hàng phát hành",
headerAttributes: {
class: "header_css"
},
field: "NganHang_PhatHanh",
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 200
},
{
title: "Ngày hiệu lực bảo lãnh",
headerAttributes: {
class: "header_css"
},
field: "NgayHieuLuc_BaoLanh",
template: "#= NgayHieuLuc_BaoLanh == null || NgayHieuLuc_BaoLanh == '' ? '' : kendo.toString(kendo.parseDate(NgayHieuLuc_BaoLanh, 'dd/MM/yyyy'), 'dd/MM/yyyy') #",
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoDatePicker({
format: "dd/MM/yyyy"
});
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 150
},
{
title: "Số VB chuyển HS đề nghị",
headerAttributes: {
class: "header_css"
},
field: "SoVB_ChuyenHS_DeNghi",
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 200
},
{
title: "Ngày VB chuyển HS đề nghị",
headerAttributes: {
class: "header_css"
},
field: "NgayVB_ChuyenHS_DeNghi",
template: "#= NgayVB_ChuyenHS_DeNghi == null || NgayVB_ChuyenHS_DeNghi == '' ? '' : kendo.toString(kendo.parseDate(NgayVB_ChuyenHS_DeNghi, 'dd/MM/yyyy'), 'dd/MM/yyyy') #",
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoDatePicker({
format: "dd/MM/yyyy"
});
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: 200
}
]
});
$("#grid_thanhvien").data("kendoGrid").table.bind("keypress", function (e) {
if (e.which !== 0 && e.charCode !== 0 && !e.ctrlKey && !e.metaKey && !e.altKey) {
//get currently navigated cell, this id follows user's navigation
var activeCell = $("#grid_active_cell");
//don't do anything if already editing cell
if (activeCell.hasClass("k-edit-cell")) return;
grid.editCell(activeCell);
var input = activeCell.find("input");
//number datatype editor loses key press character when entering edit
if (input.last().attr('data-type') === 'number') {
input.val(String.fromCharCode(e.keyCode | e.charCode));
} else {
input.val("");
}
}
});
//Kendo "Enter" key input is captured through this binding
$("#grid_thanhvien table").on("keydown", "tr", function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //If key is ENTER
//find index of the td element
var tdIndex = $(e.target).closest('td').index();
//get the next row's cell
var nextRow = $(e.target).closest('tr').next();
var nextRowCell = $(nextRow).find('td:eq(' + tdIndex + ')');
//focus the next cell on a different context
setTimeout(function () {
var grid = $("#grid_thanhvien").data("kendoGrid");
grid.current(nextRowCell);
}, 0);
}
});
$("#grid_daynhay_po").kendoGrid({
pageable: {
messages: {
display: "Tổng số {2} vật tư của PO",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
editable: true,
edit: function (e) {
var input = e.container.find(".k-input");
input.val("");
},
toolbar: kendo.template($("#Templ_VTDN_PO").html()),
columns:
[
{
title: "Vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
attributes: {
class: "row_css",
style: "font-weight:bold;"
},
template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>",
width: "20%"
},
{
title: "Số lượng khả dụng",
headerAttributes: {
class: "header_css"
},
field: "SoLuongKhaDung_DayNhay",
template: "#= OnChangeFormat(SoLuongKhaDung_DayNhay) #",
attributes: {
class: "row_css",
style: "font-weight:bold;color:green;"
}
},
{
title: "Số lượng PO",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_PO",
template: function (data) {
if (data.SoLuong_PO == 0) {
return data.SoLuong_PO;
} else {
return '<b style="color:blue;">' + OnChangeFormat(data.SoLuong_PO) + '</b>';
}
},
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoNumericTextBox({
//format: 'n3',
//decimals: 3
format: '#',
decimals: 0,
min: 0
})
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia_DayNhay",
template: "#= OnChangeFormat(DonGia_DayNhay) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "DonViTinh_Ten",
attributes: {
class: "row_css"
}
},
{
title: "Số HĐ",
headerAttributes: {
class: "header_css"
},
field: "MaHD",
attributes: {
class: "row_css",
style: "font-weight:bold;"
}
},
{
title: "Nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "NhaThau_Ten",
attributes: {
class: "row_css"
}
}
]
});
$("#grid_daynhay_po_hd").kendoGrid({
pageable: {
messages: {
display: "Tổng số {2} vật tư của PO",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
editable: true,
edit: function (e) {
var input = e.container.find(".k-input");
input.val("");
},
toolbar: kendo.template($("#Templ_VTDN_PO_hd").html()),
columns:
[
{
title: "Vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
attributes: {
class: "row_css",
style: "font-weight:bold;"
},
template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>",
width: "20%"
},
{
title: "Số lượng khả dụng",
headerAttributes: {
class: "header_css"
},
field: "SoLuongKhaDung_DayNhay",
template: "#= OnChangeFormat(SoLuongKhaDung_DayNhay) #",
attributes: {
class: "row_css",
style: "font-weight:bold;color:green;"
}
},
{
title: "Số lượng PO",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_PO",
template: function (data) {
if (data.SoLuong_PO == 0) {
return data.SoLuong_PO;
} else {
return '<b style="color:blue;">' + OnChangeFormat(data.SoLuong_PO) + '</b>';
}
},
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoNumericTextBox({
//format: 'n3',
//decimals: 3
format: '#',
decimals: 0,
min: 0
})
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia_DayNhay",
template: "#= OnChangeFormat(DonGia_DayNhay) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "DonViTinh_Ten",
attributes: {
class: "row_css"
}
},
{
title: "Số HĐ",
headerAttributes: {
class: "header_css"
},
field: "MaHD",
attributes: {
class: "row_css",
style: "font-weight:bold;"
}
},
{
title: "Nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "NhaThau_Ten",
attributes: {
class: "row_css"
}
}
]
});
$("#txt_search_sohd_daynhay").kendoComboBox({
dataTextField: "MaHD",
dataValueField: "HopDong_ID",
filter: "contains",
//dataSource: new kendo.data.DataSource({
// transport: {
// read: function (options) {
// $.ajax({
// type: "POST",
// url: "assets/ajax/Ajax_HopDong.aspx",
// data: {
// cmd: 'Lay_DS_HopDong'
// },
// dataType: 'json',
// success: function (result) {
// options.success(result);
// }
// });
// }
// }
//})
}).data("kendoComboBox");
$("#txt_search_sohd_daynhay_hd").kendoComboBox({
dataTextField: "MaHD",
dataValueField: "HopDong_ID",
filter: "contains",
//dataSource: new kendo.data.DataSource({
// transport: {
// read: function (options) {
// $.ajax({
// type: "POST",
// url: "assets/ajax/Ajax_HopDong.aspx",
// data: {
// cmd: 'Lay_DS_HopDong'
// },
// dataType: 'json',
// success: function (result) {
// options.success(result);
// }
// });
// }
// }
//})
}).data("kendoComboBox");
$("#wd_TamUng").kendoWindow({
draggable: false,
height: "auto",
width: "95%",
//actions: false,
modal: true,
resizable: false,
title: "Cập nhật thông tin tạm ứng",
visible: false
}).data("kendoWindow");
$("#wd_TaoMoi_VT_DayNhay").kendoWindow({
draggable: false,
height: "auto",
width: "100%",
//actions: false,
modal: true,
resizable: false,
title: "Tạo mới vật tư dây nhảy PO lớn",
visible: false
}).data("kendoWindow");
$("#wd_ChonVatTuDayNhay_Vuot").kendoWindow({
draggable: false,
height: "auto",
width: "100%",
//actions: false,
modal: true,
resizable: false,
title: "Tạo mới vật tư dây nhảy PO lớn",
visible: false
}).data("kendoWindow");
$("#wd_dieuchinh").kendoWindow({
draggable: false,
height: "auto",
width: "60%",
modal: true,
resizable: false,
title: "Điều chỉnh số lượng PO",
visible: false,
actions: false
}).data("kendoWindow");
$("#wd_DatHang").kendoWindow({
draggable: false,
modal: true,
resizable: false,
title: "Xuất đơn hàng",
visible: false,
actions: false
}).data("kendoWindow");
$("#wd_VatTu_PO").kendoWindow({
draggable: false,
height: "auto",
width: "auto",
actions: false,
modal: true,
resizable: false,
title: "Tạo mới vật tư thường PO lớn",
visible: false
}).data("kendoWindow");
$("#wd_ChonVatTu_Vuot").kendoWindow({
draggable: false,
height: "70%",
width: "90%",
actions: false,
modal: true,
resizable: false,
title: "Tạo mới vật tư thường PO lớn",
visible: false
}).data("kendoWindow");
$("#wd_VatTu_PO_Sua").kendoWindow({
draggable: false,
height: "auto",
width: "auto",
actions: false,
modal: true,
resizable: false,
title: "Sửa vật tư PO lớn",
visible: false
}).data("kendoWindow");
$("#wd_Show_VatTu").kendoWindow({
draggable: false,
height: "100%",
width: "100%",
//actions: false,
modal: true,
resizable: false,
title: "Tìm vật tư",
visible: false
}).data("kendoWindow");
$("#wd_PO_them").kendoWindow({
draggable: false,
height: "100%",
width: "90%",
actions: false,
modal: true,
resizable: false,
title: "Tạo mới PO",
visible: false
}).data("kendoWindow");
$("#wd_Khoa_TamUng").kendoWindow({
draggable: false,
height: "20%",
width: "40%",
modal: true,
resizable: false,
title: "Khóa tạm ứng",
visible: false,
actions: ["Close"]
}).data("kendoWindow");
$("#wd_PhanRa").kendoWindow({
draggable: false,
height: "60%",
width: "40%",
actions: false,
modal: true,
resizable: false,
title: "Phân rã PO",
visible: false
}).data("kendoWindow");
$("#wd_PO_Sua").kendoWindow({
draggable: false,
height: "auto",
width: "auto",
actions: false,
modal: true,
resizable: false,
title: "Sửa PO",
visible: false
}).data("kendoWindow");
$("#wd_List_Option").kendoWindow({
draggable: false,
modal: true,
resizable: false,
title: "Tạo mới vật tư thường theo:",
visible: false,
height: "20%",
width: "30%",
actions: false
}).data("kendoWindow");
$("#wd_List_Option_DayNhay").kendoWindow({
draggable: false,
modal: true,
resizable: false,
title: "Tạo mới vật tư dây nhảy theo:",
visible: false,
height: "20%",
width: "30%",
actions: false
}).data("kendoWindow");
$("#txt_TyLe_TamUng").kendoNumericTextBox({
format: 'n3',
//decimals: 3,
min: 0,
max: 100,
change: function () {
var TyLe = parseFloat(this.value()) / 100;
var TienTamUng = ReplaceComma($("#lb_TamUng_GT_PO").text()) * TyLe;
//$("#txt_GT_TamUng").val(OnChangeFormat(TienTamUng.toFixed(3)));
$("#txt_GT_TamUng").val(OnChangeFormat(TienTamUng));
}
});
$("#txt_NgayVB_XN_PO").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_NgayChuyen_KT").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_NgayVB_BaoLanh").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_NgayVB").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_NgayBatDau").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_NgayKy").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_NgayGiaoHang").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#Ngay_GH").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#Ngay_KHGH").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_NgayKy_Sua").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_NgayGiaoHang_Sua").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#Ngay_GH_Sua").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#Ngay_KHGH_Sua").kendoDatePicker({
format: "dd/MM/yyyy"
});
//$(".k-input").prop('disabled', true);
$("#txt_SoNgayTH").kendoNumericTextBox({
format: "# ngày",
min: "0"
});
$("#txt_SoNgayGH").kendoNumericTextBox({
format: "# ngày",
min: "0"
});
$("#txt_SoNgayGH_Sua").kendoNumericTextBox({
format: "# ngày",
min: "0"
});
$("#txt_SoLuong_PO").kendoNumericTextBox({
format: 'n3',
decimals: 3
});
$("#txt_SoLuong_PO_Sua").kendoNumericTextBox({
//format: "#.###",
//format: "#.0000"
format: 'n3',
decimals: 3,
min: "0"
});
$("#txt_sl_dc").kendoNumericTextBox({
format: 'n3',
decimals: 3,
min: "0"
});
$("#grid_DieuChinh").kendoGrid({
pageable: {
messages: {
display: "Tổng số {2} lịch sử cập nhật",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
columns:
[
{
title: "Lần điều chỉnh",
headerAttributes: {
class: "header_css"
},
field: "Lan_DC",
attributes: {
class: "row_css"
}
},
{
title: "Số lượng cũ",
headerAttributes: {
class: "header_css"
},
//field: "SoLuong_Cu",
template: "#= OnChangeFormat(SoLuong_Cu) #",
attributes: {
class: "row_css"
}
},
{
title: "Ngày điều chỉnh",
headerAttributes: {
class: "header_css"
},
field: "Ngay_DC",
attributes: {
class: "row_css"
}
},
{
title: "Người điều chỉnh",
headerAttributes: {
class: "header_css"
},
field: "Nguoi_DC",
attributes: {
class: "row_css"
}
},
{
title: "Văn bản điều chỉnh",
headerAttributes: {
class: "header_css"
},
field: "FileVB",
template: function (data) {
if (data.FileVB_DC == "" || data.FileVB_DC == null) {
return '';
} else {
return '<center><a href= "' + data.FileVB_DC + '" target="_blank" class="btn btn-inverse" ><i class="fa fa-download"></i> Tải</a></center>';
}
}
}
]
});
var grid_daynhay = $("#grid_daynhay").kendoGrid({
selectable: "multiple",
toolbar: kendo.template($("#Templ_grid_daynhay").html()),
pageable: {
messages: {
display: "Tổng số {2} vật tư dây nhảy",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
sortable: true,
columns: [
{ title: "Mã Vật Tư", field: "MaVatTu_TD", width: 150, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'TenVT', title: 'Tên Vật Tư', width: 350, headerAttributes: { class: "header_css" }, attributes: { class: "row_css", style: "font-weight: bold !important;" } },
{
field: 'NgungSuDung', title: 'Không còn sử dụng', width: 120, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" },
template: function (data) {
if (data.NgungSuDung == 0) {
return '<input type="checkbox" disabled />'
} else {
return '<input type="checkbox" disabled checked />'
}
}
},
{ field: 'LoaiVT_Ten', title: 'Loại Vật Tư', width: 250, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'DonViTinh_Ten', title: 'Đơn Vị tính', width: 100, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'SoMet', title: 'Số mét', width: 100, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{
field: 'LoaiDay', title: 'Loại Dây', width: 120, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" },
template: function (data) {
if (data.LoaiDay == 1) {
return 'Dây nối'
} else {
return 'Dây nhảy'
}
}
},
{
field: 'TinhChat', title: 'Tính chất', width: 120, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" },
template: function (data) {
if (data.TinhChat == 1) {
return 'Đơn'
} else {
return 'Đôi'
}
}
},
{ field: 'GhiChu', title: 'Ghi Chú', width: 200, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }
],
detailTemplate: kendo.template($("#Templ_CT_DayNhay").html()),
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
detailInit: function (e) {
var detailRow = e.detailRow;
detailRow.find("#tabstrip_daynhay").kendoTabStrip({
animation: {
open: { effects: "fadeIn" }
}
});
detailRow.find("#tab_CT_DayNhay").empty();
detailRow.find("#tab_CT_DayNhay").kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_DM_VT_DayNhay.aspx",
data: {
cmd: 'LayDanhSach_VT_DayNhay_CT',
VatTu_ID: e.data.VatTu_ID
},
dataType: 'json',
success: function (result) {
options.success(result);
}
});
}
}
}),
columns: [
{ title: "Nguyên Liệu", field: "NguyenLieu", width: 150, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{
field: 'NgungSuDung', title: 'Không còn sử dụng', width: 120, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" },
template: function (data) {
if (data.NgungSuDung == 0) {
return '<input type="checkbox" disabled />'
} else {
return '<input type="checkbox" disabled checked />'
}
}
},
{ title: "Mã Vật Tư", field: "MaVatTu_TD", width: 150, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'TenVT', title: 'Tên Vật Tư', width: 350, headerAttributes: { class: "header_css" }, attributes: { class: "row_css", style: "font-weight: bold !important;" } },
{ field: 'LoaiVT_Ten', title: 'Loại Vật Tư', width: 250, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'DonViTinh_Ten', title: 'Đơn Vị tính', width: 100, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'GhiChu', title: 'Ghi Chú', width: 200, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }
]
});
}
}).data("kendoGrid");
$("#txt_tim").kendoAutoComplete({
dataTextField: "MaVatTu_TD",
dataSource: DS_VT_DayNhay,
select: function (e) {
var dataItem = this.dataItem(e.item.index());
var value = dataItem.VatTu_ID;
if (value) {
grid_daynhay.dataSource.filter({
field: "VatTu_ID",
operator: "eq",
value: parseInt(value)
});
}
else {
grid_daynhay.dataSource.filter({});
}
},
change: function () {
$("#txt_tim").val('');
}
});
$("#btn_clear_tim").click(function (e) {
e.preventDefault();
$("#txt_tim").val('');
grid_daynhay.dataSource.filter({});
});
/////////////////////////
var grid_daynhay_hd = $("#grid_daynhay_hd").kendoGrid({
selectable: "multiple",
toolbar: kendo.template($("#Templ_grid_daynhay_hd").html()),
pageable: {
messages: {
display: "Tổng số {2} vật tư dây nhảy",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
sortable: true,
columns: [
{ title: "Mã Vật Tư", field: "MaVatTu_TD", width: 150, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'TenVT', title: 'Tên Vật Tư', width: 350, headerAttributes: { class: "header_css" }, attributes: { class: "row_css", style: "font-weight: bold !important;" } },
{
field: 'NgungSuDung', title: 'Không còn sử dụng', width: 120, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" },
template: function (data) {
if (data.NgungSuDung == 0) {
return '<input type="checkbox" disabled />'
} else {
return '<input type="checkbox" disabled checked />'
}
}
},
{ field: 'LoaiVT_Ten', title: 'Loại Vật Tư', width: 250, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'DonViTinh_Ten', title: 'Đơn Vị tính', width: 100, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'SoMet', title: 'Số mét', width: 100, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{
field: 'LoaiDay', title: 'Loại Dây', width: 120, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" },
template: function (data) {
if (data.LoaiDay == 1) {
return 'Dây nối'
} else {
return 'Dây nhảy'
}
}
},
{
field: 'TinhChat', title: 'Tính chất', width: 120, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" },
template: function (data) {
if (data.TinhChat == 1) {
return 'Đơn'
} else {
return 'Đôi'
}
}
},
{ field: 'GhiChu', title: 'Ghi Chú', width: 200, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }
],
detailTemplate: kendo.template($("#Templ_CT_DayNhay").html()),
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
detailInit: function (e) {
var detailRow = e.detailRow;
detailRow.find("#tabstrip_daynhay").kendoTabStrip({
animation: {
open: { effects: "fadeIn" }
}
});
detailRow.find("#tab_CT_DayNhay").empty();
detailRow.find("#tab_CT_DayNhay").kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_DM_VT_DayNhay.aspx",
data: {
cmd: 'LayDanhSach_VT_DayNhay_CT',
VatTu_ID: e.data.VatTu_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
}),
columns: [
{ title: "Nguyên Liệu", field: "NguyenLieu", width: 150, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{
field: 'NgungSuDung', title: 'Không còn sử dụng', width: 120, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" },
template: function (data) {
if (data.NgungSuDung == 0) {
return '<input type="checkbox" disabled />'
} else {
return '<input type="checkbox" disabled checked />'
}
}
},
{ title: "Mã Vật Tư", field: "MaVatTu_TD", width: 150, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'TenVT', title: 'Tên Vật Tư', width: 350, headerAttributes: { class: "header_css" }, attributes: { class: "row_css", style: "font-weight: bold !important;" } },
{ field: 'LoaiVT_Ten', title: 'Loại Vật Tư', width: 250, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'DonViTinh_Ten', title: 'Đơn Vị tính', width: 100, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
{ field: 'GhiChu', title: 'Ghi Chú', width: 200, headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }
]
});
}
}).data("kendoGrid");
$("#txt_tim_hd").kendoAutoComplete({
dataTextField: "MaVatTu_TD",
dataSource: DS_VT_DayNhay,
select: function (e) {
var dataItem = this.dataItem(e.item.index());
var value = dataItem.VatTu_ID;
if (value) {
grid_daynhay_hd.dataSource.filter({
field: "VatTu_ID",
operator: "eq",
value: parseInt(value)
});
}
else {
grid_daynhay.dataSource.filter({});
}
},
change: function () {
$("#txt_tim_hd").val('');
}
});
$("#btn_clear_tim_hd").click(function (e) {
e.preventDefault();
$("#txt_tim_hd").val('');
grid_daynhay_hd.dataSource.filter({});
});
//#endregion
//#region Load danh sách đơn vị tạo PO
$("#grid_DonVi_Sua").empty();
$("#grid_DonVi_Sua").kendoGrid({
dataSource: DS_DonVi,
scrollable: true,
columns:
[
{ field: "ID", hidden: true },
{
field: "select_dv",
title: "Chọn",
headerAttributes: {
class: "header_css"
},
template: '<center><input type=\'checkbox\' /></center>',
sortable: false,
width: 80,
attributes: {
style: "background-color:lightyellow;"
}
},
{
title: "Mã đơn vị",
headerAttributes: {
class: "header_css"
},
field: "DonVi_ID",
attributes: {
class: "row_css"
}
},
{
title: "Tên đơn vị",
headerAttributes: {
class: "header_css"
},
field: "TenDonVi",
attributes: {
class: "row_css"
}
}
]
});
///////// Load danh sách đơn vị\\\\\\\\\\\
$("#grid_DonVi").empty();
var grid_donvi = $("#grid_DonVi").kendoGrid({
dataSource: DS_DonVi,
toolbar: kendo.template($("#Templ_DonVi").html()),
columns:
[
{ field: "ID", hidden: true },
{
field: "select_dv",
title: "<input id='chk_all' type='checkbox' />",
headerAttributes: {
class: "header_css"
},
template: '<center><input type=\'checkbox\' /></center>',
sortable: false,
width: 80,
},
{
title: "Mã đơn vị",
headerAttributes: {
class: "header_css"
},
field: "DonVi_ID",
attributes: {
class: "row_css"
}
},
{
title: "Tên đơn vị",
headerAttributes: {
class: "header_css"
},
field: "TenDonVi",
attributes: {
class: "row_css"
}
}
]
});
var dropDown = grid_donvi.find("#dl_KhuVuc").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
optionLabel: "--Tất cả--",
dataSource: [
{ text: "VNPT khu vực phía Bắc", value: "B" },
{ text: "VNPT khu vực phía Nam", value: "N" }
],
change: function () {
var value = this.value();
if (value) {
grid_donvi.data("kendoGrid").dataSource.filter({ field: "KhuVuc", operator: "eq", value: value });
document.getElementById('chk_all').checked = false;
} else {
grid_donvi.data("kendoGrid").dataSource.filter({});
}
}
});
$("#chk_all").click(function () {
if (document.getElementById('chk_all').checked) {
for (var j = 1; j < $("#grid_DonVi tr").length; j++) {
$("#grid_DonVi tr")[j].cells[1].childNodes[0].childNodes[0].checked = true;
}
}
else {
for (var j = 1; j < $("#grid_DonVi tr").length; j++) {
$("#grid_DonVi tr")[j].cells[1].childNodes[0].childNodes[0].checked = false;
}
}
});
//#endregion
//#region Load Danh sach PO
$("#grid_PO").empty();
var gvData = $("#grid_PO").kendoGrid({
toolbar: $("[id$=_hf_quyen_capnhat]").val() == "true" ? kendo.template($("#Templ_PO").html()) : kendo.template($("#Templ_PO_TD").html()),
detailTemplate: kendo.template($("#Templ_ChiTiet_PO").html()),
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
pageable: {
messages: {
display: "Tổng số {2} PO",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
detailInit: Ham_ChiTiet_PO,
sortable: true,
columns:
[
{
title: "Khóa PO",
headerAttributes: {
class: "header_css"
},
template: function (data) {
if ($("[id$=_hf_quyen_KhoaPO]").val() == "true") {
if (data.TinhTrang == '0') {
return '<center><input type="button" class="button_mokhoa" onclick="Ham_DongKhoa(\'' + data.PO_ID + '\');"/></center>';
}
else {
return '<center><input type="button" class="button_khoa" onclick="Ham_MoKhoa(\'' + data.PO_ID + '\');"/></center>';
}
}
else {
if (data.TinhTrang == '0') {
return '<center><input type="button" style="cursor: text;" class="button_mokhoa" /></center>';
}
else {
return '<center><input type="button" style="cursor: text;" class="button_khoa" /></center>';
}
}
},
width: "7%"
},
{
template: function (data) {
if (data.Check_PO == '0') {
return '<center><span class="label label-success">Chưa xuất</span></center>';
}
else {
return '<center><span class="label label-important">Đã xuất</span></center>';
}
},
width: "8%"
},
{
title: "Số PO",
headerAttributes: {
class: "header_css"
},
field: "SoPO",
attributes: {
class: "row_css"
}
},
{
title: "Ngày ký PO",
headerAttributes: {
class: "header_css"
},
field: "NgayKyPO",
attributes: {
class: "row_css"
},
template: "#= NgayKyPO_f #"
//format: '{0:dd/MM/yyyy}'
},
{
title: "Số văn bản",
headerAttributes: {
class: "header_css"
},
field: "SoVanBan",
attributes: {
class: "row_css"
}
},
{
title: "Người lập PO",
headerAttributes: {
class: "header_css"
},
field: "NguoiTaoPO",
attributes: {
class: "row_css"
}
},
{
title: "File văn bản",
headerAttributes: {
class: "header_css"
},
field: "FileVB",
template: function (data) {
if (data.FileVB == "" || data.FileVB == null) {
return '';
} else {
//return '<center><a href= "' + value + '" class="k-button" target="_blank" style="font-size: 0.85em !important;min-width:8px !important;" ><span class="k-icon k-i-seek-s"></span></a></center>';
return '<center><a href= "' + data.FileVB + '" target="_blank" class="btn btn-inverse" ><i class="fa fa-download"></i> Tải</a></center>';
}
},
width: "9%"
},
{
template: function (data) {
if ($("[id$=_hf_quyen_capnhat]").val() == 'true') {
if (data.TinhTrang == '0') {
//return '<center><a onclick="func_SuaPO(' + model.PO_ID + ');" class="k-button" style="font-size: 0.85em !important;min-width:8px !important;"><span class="k-icon k-i-pencil"></span></a></center>'
return '<center><a class="btn btn-info" onclick="Ham_SuaPO(' + data.PO_ID + ');" ><i class="fa fa-edit "></i> Sửa</a></center>'
} else {
return '';
}
}
else {
return '';
}
},
width: "9%"
},
{
template: function Ham_HienThi_Xoa_PO(data) {
if ($("[id$=_hf_quyen_capnhat]").val() == 'true') {
if (data.TinhTrang == '0') {
//return '<center><a onclick="func_XoaPO(' + model.PO_ID + ');" class="k-button" style="font-size: 0.85em !important;min-width:8px !important;" ><span class="k-icon k-i-close"></span></a></center>'
return '<center><a class="btn btn-danger" onclick="Ham_XoaPO(' + data.PO_ID + ');"><i class="fa fa-trash-o "></i> Xóa</a></center>'
} else {
return '';
}
}
else {
return '';
}
},
width: "8%"
}
]
});
$("#txt_search_soPO").kendoAutoComplete({
dataTextField: "SoPO",
filter: "contains",
dataSource: {
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'Lay_DS_SoPO'
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
}
});
$('#txt_search_soPO').keydown(function (e) {
if (e.which === 13)
filterPO();
});
$('#btn_tim_soPO').click(function (e) {
e.preventDefault();
filterPO();
});
$('#btn_clear_soPO').click(function (e) {
e.preventDefault();
$('#txt_search_soPO').val('');
filterPO();
});
//$("#txt_search_soPO").kendoAutoComplete({
// dataTextField: "SoPO",
// dataSource: DS_PO,
// filter: "contains",
// select: function (e) {
// var dataItem = this.dataItem(e.item.index());
// var value = dataItem.SoPO;
// if (value) {
// $("#grid_PO").data("kendoGrid").dataSource.filter({ field: "SoPO", operator: "eq", value: value });
// }
// else {
// $("#grid_PO").data("kendoGrid").dataSource.filter({});
// }
// },
// change: function () {
// $("#txt_search_soPO").val('');
// }
//});
//$("#btn_clear_soPO").click(function (e) {
// e.preventDefault();
// $("#txt_search_soPO").val('');
// $("#grid_PO").data("kendoGrid").dataSource.filter({});
//});
////////Excel\\\\\\\\\
//$("#grid_PO_ex").empty();
//var grid = $("#grid_PO_ex").kendoGrid({
// excel: {
// allPages: true
// },
// excelExport: function (e) {
// e.preventDefault();
// var workbook = e.workbook;
// detailExportPromises = [];
// var masterData = e.data;
// for (var rowIndex = 0; rowIndex < masterData.length; rowIndex++) {
// exportChiTiet_PO(masterData[rowIndex].PO_ID, rowIndex);
// }
// $.when.apply(null, detailExportPromises)
// .then(function () {
// // get the export results
// var detailExports = $.makeArray(arguments);
// // sort by masterRowIndex
// detailExports.sort(function (a, b) {
// return a.masterRowIndex - b.masterRowIndex;
// });
// // add an empty column
// workbook.sheets[0].columns.unshift({
// width: 30
// });
// // prepend an empty cell to each row
// for (var i = 0; i < workbook.sheets[0].rows.length; i++) {
// workbook.sheets[0].rows[i].cells.unshift({});
// }
// // merge the detail export sheet rows with the master sheet rows
// // loop backwards so the masterRowIndex doesn't need to be updated
// for (var i = detailExports.length - 1; i >= 0; i--) {
// var masterRowIndex = detailExports[i].masterRowIndex + 1; // compensate for the header row
// var sheet = detailExports[i].sheet;
// // prepend an empty cell to each row
// for (var ci = 0; ci < sheet.rows.length; ci++) {
// if (sheet.rows[ci].cells[0].value) {
// sheet.rows[ci].cells.unshift({});
// }
// }
// // insert the detail sheet rows after the master row
// [].splice.apply(workbook.sheets[0].rows, [masterRowIndex + 1, 0].concat(sheet.rows));
// }
// // save the workbook
// kendo.saveAs({
// dataURI: new kendo.ooxml.Workbook(workbook).toDataURL(),
// fileName: "Export.xlsx"
// });
// });
// },
// columns:
// [
// { title: "Số PO", field: "SoPO", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
// { title: "Ngày kí PO", field: "NgayKyPO", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
// { title: "Số văn bản", field: "SoVanBan", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
// { title: "Người tạo PO", field: "NguoiTaoPO", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } },
// { title: "Tổng giá trị PO", field: "TongTienPO", template: "#= OnChangeFormat(TongTienPO) #", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }
// ]
//});
//#endregion
//#region Hiển thị danh sách Vật tư
$("#grid_VatTu").empty();
var grid_vattu = $("#grid_VatTu").kendoGrid({
dataSource: DS_VatTu,
pageable: true,
pageable: {
messages: {
display: "Tổng số {2} vật tư",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
sortable: true,
dataBound: function (e) {
var view = this.dataSource.view();
for (var i = 0; i < view.length; i++) {
if (ItemChecked[view[i].uid]) {
this.tbody.find("tr[data-uid='" + view[i].uid + "']")
.addClass("k-state-selected")
.find(".checkbox")
.attr("checked", "checked");
}
}
},
toolbar: kendo.template($("#Templ_VatuTu").html()),
columns:
[
{
field: "select",
title: "Chọn",
headerAttributes: {
class: "header_css"
},
template: '<center><input type=\'checkbox\' class=\'checkbox\' /></center>',
sortable: false,
width: 80,
attributes: {
style: "background-color:lightyellow;"
}
},
{
title: "Vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
attributes: {
class: "row_css",
style: "font-weight:bold;"
}
},
{
title: "Mã vật tư tập đoàn",
headerAttributes: {
class: "header_css"
},
field: "MaVatTu_TD",
attributes: {
class: "row_css",
style: "font-weight:bold;"
}
},
{
title: "Số lượng khả dụng",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_KhaDung",
type: "number",
template: "#= OnChangeFormat(SoLuong_KhaDung) #",
attributes: {
class: "row_css",
style: "font-weight:bold;color:green;"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
},
{
title: "Số HĐ",
headerAttributes: {
class: "header_css"
},
field: "MaHD",
attributes: {
class: "row_css",
style: "font-weight:bold;"
}
},
{
title: "Nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "NhaThau_Ten",
attributes: {
class: "row_css"
}
}
]
}).data("kendoGrid");
//bind click event to the checkbox
grid_vattu.table.on("click", ".checkbox", selectRow);
var cboSearchBy_VT_Thuong = $('#cboSearchBy_VT_Thuong').kendoDropDownList({
dataSource: {
data: ['Số hợp đồng', 'Tên vật tư', 'Mã vật tư']
}
}).data('kendoDropDownList');
$('#btn_loc_vt_VT_Thuong').click(function (e) {
e.preventDefault();
filterVatTuHopDong();
});
$('#btn_clear_VT_Thuong').click(function (e) {
e.preventDefault();
$('#txtSearchValue_VT_Thuong').val('');
filterVatTuHopDong();
});
//$("#txt_search_sohd").kendoAutoComplete({
// dataTextField: "MaHD",
// dataSource: DS_SoHD,
// select: function (e) {
// var dataItem = this.dataItem(e.item.index());
// var value = dataItem.MaHD;
// if (value) {
// grid_vattu.dataSource.filter({ field: "MaHD", operator: "eq", value: value });
// }
// else {
// grid_vattu.dataSource.filter({});
// }
// },
// change: function () {
// $("#txt_search_sohd").val('');
// }
//});
//$("#txt_search_tenvt").kendoAutoComplete({
// dataTextField: "VatTu_Ten",
// dataSource: DS_TenVT,
// select: function (e) {
// var dataItem = this.dataItem(e.item.index());
// var value = dataItem.VatTu_Ten;
// if (value) {
// grid_vattu.dataSource.filter({ field: "VatTu_Ten", operator: "eq", value: value });
// }
// else {
// grid_vattu.dataSource.filter({});
// }
// },
// change: function () {
// $("#txt_search_tenvt").val('');
// }
//});
//$("#txt_search_mavttd").kendoAutoComplete({
// dataTextField: "MaVatTu_TD",
// dataSource: DS_MaTD,
// select: function (e) {
// var dataItem = this.dataItem(e.item.index());
// var value = dataItem.MaVatTu_TD;
// if (value) {
// grid_vattu.dataSource.filter({ field: "MaVatTu_TD", operator: "eq", value: value });
// }
// else {
// grid_vattu.dataSource.filter({});
// }
// },
// change: function () {
// $("#txt_search_mavttd").val('');
// }
//});
//$("#btn_clear").click(function (e) {
// e.preventDefault();
// $("#txt_search_sohd").val('');
// $("#txt_search_tenvt").val('');
// $("#txt_search_mavttd").val('');
// grid_vattu.dataSource.filter({});
//});
//#endregion
//#region bộ lọc
$("#Tr_Loc_TinhTrang").hide();
$("#Tr_Loc_Loai_PO").hide();
$("#Tr_Loc_NgayKi_PO_1").hide();
$("#Tr_Loc_NgayKi_PO_2").hide();
$("#Tr_Loc_NhaThau_1").hide();
$("#Tr_Loc_NhaThau_2").hide();
$("#Tr_Loc_SoHD_1").hide();
$("#Tr_Loc_SoHD_2").hide();
$("#cmb_BoLoc").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "Tình trạng PO", value: "1" },
{ text: "Loại PO", value: "2" },
{ text: "Ngày kí PO", value: "3" },
{ text: "Nhà thầu", value: "4" },
{ text: "Số hợp đồng", value: "5" }
],
optionLabel: "--Tất cả--",
select: function (e) {
var dataItem = this.dataItem(e.item.index());
var value = dataItem.value;
switch (value) {
case "1":
$("#grid_PO").data("kendoGrid").dataSource.filter({});
//$("#grid_PO_ex").data("kendoGrid").dataSource.filter({});
$("#Tr_Loc_TinhTrang").show();
$("#Tr_Loc_Loai_PO").hide();
$("#Tr_Loc_NgayKi_PO_1").hide();
$("#Tr_Loc_NgayKi_PO_2").hide();
$("#Tr_Loc_NhaThau_1").hide();
$("#Tr_Loc_NhaThau_2").hide();
$("#Tr_Loc_SoHD_1").hide();
$("#Tr_Loc_SoHD_2").hide();
break;
case "2":
$("#grid_PO").data("kendoGrid").dataSource.filter({});
//$("#grid_PO_ex").data("kendoGrid").dataSource.filter({});
$("#Tr_Loc_TinhTrang").hide();
$("#Tr_Loc_Loai_PO").show();
$("#Tr_Loc_NgayKi_PO_1").hide();
$("#Tr_Loc_NgayKi_PO_2").hide();
$("#Tr_Loc_NhaThau_1").hide();
$("#Tr_Loc_NhaThau_2").hide();
$("#Tr_Loc_SoHD_1").hide();
$("#Tr_Loc_SoHD_2").hide();
break;
case "3":
$("#txt_TuNgay").val("");
$("#txt_DenNgay").val("");
$("#Tr_Loc_TinhTrang").hide();
$("#Tr_Loc_Loai_PO").hide();
$("#Tr_Loc_NgayKi_PO_1").show();
$("#Tr_Loc_NgayKi_PO_2").show();
$("#Tr_Loc_NhaThau_1").hide();
$("#Tr_Loc_NhaThau_2").hide();
$("#Tr_Loc_SoHD_1").hide();
$("#Tr_Loc_SoHD_2").hide();
break;
case "4":
$("#grid_PO").data("kendoGrid").dataSource.filter({});
//$("#grid_PO_ex").data("kendoGrid").dataSource.filter({});
$("#Tr_Loc_TinhTrang").hide();
$("#Tr_Loc_Loai_PO").hide();
$("#Tr_Loc_NgayKi_PO_1").hide();
$("#Tr_Loc_NgayKi_PO_2").hide();
$("#Tr_Loc_NhaThau_1").show();
$("#Tr_Loc_NhaThau_2").show();
$("#Tr_Loc_SoHD_1").hide();
$("#Tr_Loc_SoHD_2").hide();
break;
case "5":
$("#grid_PO").data("kendoGrid").dataSource.filter({});
//$("#grid_PO_ex").data("kendoGrid").dataSource.filter({});
$("#Tr_Loc_TinhTrang").hide();
$("#Tr_Loc_Loai_PO").hide();
$("#Tr_Loc_NgayKi_PO_1").hide();
$("#Tr_Loc_NgayKi_PO_2").hide();
$("#Tr_Loc_NhaThau_1").hide();
$("#Tr_Loc_NhaThau_2").hide();
$("#Tr_Loc_SoHD_1").show();
$("#Tr_Loc_SoHD_2").show();
break;
default:
$("#Tr_Loc_TinhTrang").hide();
$("#Tr_Loc_Loai_PO").hide();
$("#Tr_Loc_NgayKi_PO_1").hide();
$("#Tr_Loc_NgayKi_PO_2").hide();
$("#Tr_Loc_NhaThau_1").hide();
$("#Tr_Loc_NhaThau_2").hide();
$("#Tr_Loc_SoHD_1").hide();
$("#Tr_Loc_SoHD_2").hide();
}
}
});
////Lọc tình trang/////////////
$("#cmb_Loc_TinhTrang").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "Chưa xuất PO lớn", value: "0" },
{ text: "Đã xuất PO lớn", value: "1" }
],
optionLabel: "--Tất cả--",
select: function (e) {
var dataItem = this.dataItem(e.item.index());
var value = dataItem.value;
//if (value == "") {
// $("#grid_PO").data("kendoGrid").dataSource.filter({});
// $("#grid_PO_ex").data("kendoGrid").dataSource.filter({});
//}
//else {
// $("#grid_PO").data("kendoGrid").dataSource.filter({ field: "Check_PO", operator: "eq", value: parseInt(value) });
// $("#grid_PO_ex").data("kendoGrid").dataSource.filter({ field: "Check_PO", operator: "eq", value: parseInt(value) });
//}
var ds;
if (value == "") {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO"
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
else {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type)
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_byTinhTrang",
data: {
TinhTrang: parseInt(value)
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(ds) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD);
//$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(ds) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD);
}
});
///////////////Lọc loại PO////////////////
$("#cmb_Loc_Loai_PO").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: "PO VTTP", value: "0" },
{ text: "PO Tập đoàn", value: "1" }
],
optionLabel: "--Tất cả--",
select: function (e) {
var dataItem = this.dataItem(e.item.index());
var value = dataItem.value;
//if (value == "") {
// $("#grid_PO").data("kendoGrid").dataSource.filter({});
// $("#grid_PO_ex").data("kendoGrid").dataSource.filter({});
//}
//else {
// $("#grid_PO").data("kendoGrid").dataSource.filter({ field: "Check_PO_TapDoan", operator: "eq", value: parseInt(value) });
// $("#grid_PO_ex").data("kendoGrid").dataSource.filter({ field: "Check_PO_TapDoan", operator: "eq", value: parseInt(value) });
//}
var ds;
if (value == "") {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO"
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
else {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type)
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_byLoaiPO",
data: {
LoaiPO: parseInt(value)
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(ds) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD);
//$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(ds) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD);
}
});
////////////Lọc ngày kí//////////////
$("#txt_TuNgay").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#txt_DenNgay").kendoDatePicker({
format: "dd/MM/yyyy"
});
$("#btn_huy_loc_ngay").click(function () {
$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD);
//$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD);
});
$("#btn_loc_ngay").click(function () {
DS_PO_Loc = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'Lay_DS_PO_Ngay',
TuNgay: $("#txt_TuNgay").val(),
DenNgay: $("#txt_DenNgay").val()
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 7
});
$("#grid_PO").data("kendoGrid").setDataSource(DS_PO_Loc);
//$("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_Loc);
});
///////////////Lọc theo nhà thầu///////////////////////////////
$("#cmb_Loc_NhaThau").kendoDropDownList({
autoBind: true,
optionLabel: "--Chọn nhà thầu--",
dataTextField: "TenNhaThau",
dataValueField: "NhaThau_ID",
dataSource: new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_DanhMuc.aspx",
data: {
cmd: 'DS_NhaThau'
},
dataType: 'json',
success: function (result) {
//options.success(result);
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
})
});
$("#btn_huy_loc_nt").click(function () {
$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD);
//$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD);
});
$("#btn_loc_nt").click(function () {
DS_PO_Loc = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'Lay_DS_PO_NT',
NhaThau_ID: $("#cmb_Loc_NhaThau").data("kendoDropDownList").value()
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 7
});
$("#grid_PO").data("kendoGrid").setDataSource(DS_PO_Loc);
//$("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_Loc);
});
///////////////////Lọc hợp đồng ///////////////////////
$("#cmb_Loc_SoHD").kendoComboBox({
placeholder: "--Chọn hợp đồng--",
dataTextField: "MaHD",
dataValueField: "HopDong_ID",
filter: "startswith",
dataSource: {
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'Lay_DS_PO_HD_Ctr'
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
}
}
});
$("#btn_huy_loc_hd").click(function () {
$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD);
//$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD);
});
$("#btn_loc_hd").click(function () {
if ($("#cmb_Loc_SoHD").data("kendoComboBox").select() == -1) {
//alert("Chưa chọn đúng mã hợp đồng!");
$("#notification").data("kendoNotification").show({
title: "Chưa chọn đúng mã hợp đồng!",
message: "Hãy chọn hợp đồng!"
}, "error");
}
else {
DS_PO_Loc = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'Lay_DS_PO_HD',
HopDong_ID: $("#cmb_Loc_SoHD").data("kendoComboBox").value()
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 7
});
$("#grid_PO").data("kendoGrid").setDataSource(DS_PO_Loc);
//$("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_Loc);
}
});
//#endregion
$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD);
//$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD);
});
//#region Sửa PO
function Ham_SuaPO(p_PO_ID) {
$("#wd_PO_Sua").data("kendoWindow").center().open();
PO_ID_Sua = p_PO_ID;
var grid_data = $("#grid_PO").data("kendoGrid"),
data = grid_data.dataSource.data();
var res = $.grep(data, function (d) {
return d.PO_ID == p_PO_ID;
});
$("#txt_SoPO_Sua").val(res[0].SoPO);
$("#txt_NgayKy_Sua").val(res[0].NgayKyPO_f);
$("#txt_VB_Sua").val(res[0].SoVanBan);
//Load check đơn vị
var arr_dv = res[0].Str_PO_DonVi.split(",");
for (var j = 1; j < $("#grid_DonVi_Sua tr").length; j++) {
$("#grid_DonVi_Sua tr")[j].cells[1].childNodes[0].childNodes[0].checked = false;
arr_dv.forEach(function (entry) {
if ($("#grid_DonVi_Sua tr")[j].cells[0].childNodes[0].textContent == entry) {
$("#grid_DonVi_Sua tr")[j].cells[1].childNodes[0].childNodes[0].checked = true;
}
});
}
Path_Sua = res[0].FileVB;
if (res[0].FileVB == "" || res[0].FileVB == null) {
$("#tr_download").hide();
$("#tr_upload").show();
} else {
$("#tr_download").show();
$("#tr_upload").hide();
$("#btn_download").attr("href", "" + res[0].FileVB + "");
}
}
function Ham_Sua_PO_Luu() {
var str_id_dv = '';
for (var j = 1; j < $("#grid_DonVi_Sua tr").length; j++) {
var chb_dv = $("#grid_DonVi_Sua tr")[j].cells[1].childNodes[0].childNodes[0];
var id = $("#grid_DonVi_Sua tr")[j].cells[0].childNodes[0].textContent;
if (chb_dv.checked == true) {
str_id_dv += '' + id + ',';
}
}
str_id_dv = str_id_dv.replace(/^,|,$/g, '');
var check = 0;
if ($("#txt_SoPO_Sua").val() == "") {
check = 1;
//alert("Chưa nhập số PO!");
$("#notification").data("kendoNotification").show({
title: "Chưa nhập số PO!",
message: "Hãy nhập số PO!"
}, "error");
return;
}
if ($("#txt_NgayKy_Sua").val() == "") {
check = 1;
//alert("Chưa nhập ngày ký PO!");
$("#notification").data("kendoNotification").show({
title: "Chưa nhập ngày ký PO",
message: "Hãy nhập ngày ký PO!"
}, "error");
return;
}
if ($("#txt_VB_Sua").val() == "") {
check = 1;
//alert("Chưa nhập văn bản xác nhận PO!");
$("#notification").data("kendoNotification").show({
title: "Chưa nhập văn bản xác nhận PO",
message: "Hãy nhập văn bản xác nhận PO"
}, "error");
return;
}
//if ($("#txt_NgayGiaoHang_Sua").val() == "") {
// check = 1;
// alert("Chưa nhập ngày giao hàng!");
// return;
//}
//if ($("#txt_SoNgayGH_Sua").data("kendoNumericTextBox").value() == "" || $("#txt_SoNgayGH_Sua").data("kendoNumericTextBox").value() == "0") {
// check = 1;
// alert("Chưa nhập số ngày giao hàng!");
// return;
//}
//if ($("#Ngay_GH_Sua").val() == "") {
// check = 1;
// alert("Chưa nhập ngày xác nhận giao hàng!");
// return;
//}
//if ($("#Ngay_KHGH_Sua").val() == "") {
// check = 1;
// alert("Chưa nhập ngày kế hoạch giao hàng!");
// return;
//}
if (str_id_dv == '') {
check = 1;
//alert("Chưa chọn đơn vị tham gia!");
$("#notification").data("kendoNotification").show({
title: "Chưa chọn đơn vị tham gia",
message: "Hãy nhập số PO!"
}, "error");
return;
}
if (check == 0) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'PO_Update',
PO_ID: PO_ID_Sua,
SoPO: $("#txt_SoPO_Sua").val(),
NgayKyPO: $("#txt_NgayKy_Sua").val(),
SoVanBan: $("#txt_VB_Sua").val(),
DonViPO: str_id_dv,
//SoNgayGH: $("#txt_SoNgayGH_Sua").data("kendoNumericTextBox").value(),
//NgayGiaoHang: $("#txt_NgayGiaoHang_Sua").val(),
//NgayXacNhanGH: $("#Ngay_GH_Sua").val(),
//NgayKeHoachGH: $("#Ngay_KHGH_Sua").val(),
SoNgayGH: 0,
NgayGiaoHang: "",
NgayXacNhanGH: "",
NgayKeHoachGH: "",
FileVB: Path_Sua
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
//alert("Đã sửa thành công PO!");
$("#notification").data("kendoNotification").show({
message: "Đã sửa thành công PO!"
}, "upload-success");
$("#wd_PO_Sua").data("kendoWindow").close();
//DS_PO.read();
var ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type)
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_bySoPO",
data: {
SoPO: $('#txt_search_soPO').val().trim()
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
$('#grid_PO').data('kendoGrid').setDataSource(ds);
uploadReset();
}
else {
//alert(msg[0].ErrorMessage);
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
function Ham_Sua_PO_Huy() {
$("#wd_PO_Sua").data("kendoWindow").close();
uploadReset();
}
//#endregion
//#region Xóa PO
function Ham_XoaPO(PO_ID) {
if (confirm("Bạn có chắc muốn xóa PO này không? Xóa tất cả từ PO con,PO chi tiết")) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'PO_Delete',
PO_ID: PO_ID
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
//alert("Đã xóa thành công PO!");
$("#notification").data("kendoNotification").show({
message: "Đã xóa thành công PO!"
}, "upload-success");
var ds = new kendo.data.DataSource({
requestEnd: function (e) {
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO"
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
$("#grid_PO").data("kendoGrid").setDataSource(ds);
$("#txt_search_soPO").data("kendoAutoComplete").dataSource.read();
}
else {
//alert(msg[0].ErrorMessage);
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
//#endregion
//#region Thêm mới PO
function Ham_Them_PO() {
$("#wd_PO_them").data("kendoWindow").center().open();
}
function Ham_Them_PO_Luu() {
var str_id_dv = '';
for (var j = 1; j < $("#grid_DonVi tr").length; j++) {
var chb_dv = $("#grid_DonVi tr")[j].cells[1].childNodes[0].childNodes[0];
var id = $("#grid_DonVi tr")[j].cells[0].childNodes[0].textContent;
if (chb_dv.checked == true) {
str_id_dv += '' + id + ',';
}
}
str_id_dv = str_id_dv.replace(/^,|,$/g, '');
var check = 0;
if ($("#txt_SoPO").val() == "") {
check = 1;
alert("Chưa nhập số PO!");
return;
}
if ($("#txt_NgayKy").val() == "") {
check = 1;
alert("Chưa nhập ngày ký PO!");
return;
}
//if ($("#txt_VB").val() == "") {
// check = 1;
// alert("Chưa nhập văn bản xác nhận PO!");
// return;
//}
//if ($("#txt_NgayGiaoHang").val() == "") {
// check = 1;
// alert("Chưa nhập ngày giao hàng!");
// return;
//}
//if ($("#txt_SoNgayGH").data("kendoNumericTextBox").value() == "" || $("#txt_SoNgayGH").data("kendoNumericTextBox").value() == "0") {
// check = 1;
// alert("Chưa nhập số ngày giao hàng!");
// return;
//}
//if ($("#Ngay_GH").val() == "") {
// check = 1;
// alert("Chưa nhập ngày xác nhận giao hàng!");
// return;
//}
//if ($("#Ngay_KHGH").val() == "") {
// check = 1;
// alert("Chưa nhập ngày kế hoạch giao hàng!");
// return;
//}
if (str_id_dv == '') {
check = 1;
alert("Chưa chọn đơn vị tham gia!");
return;
}
if (check == 0) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'PO_Create',
SoPO: $("#txt_SoPO").val(),
NgayKyPO: $("#txt_NgayKy").val(),
SoVanBan: $("#txt_VB").val(),
DonViPO: str_id_dv,
//SoNgayGH: $("#txt_SoNgayGH").data("kendoNumericTextBox").value(),
//NgayGiaoHang: $("#txt_NgayGiaoHang").val(),
//NgayXacNhanGH: $("#Ngay_GH").val(),
//NgayKeHoachGH: $("#Ngay_KHGH").val(),
SoNgayGH: 0,
NgayGiaoHang: "",
NgayXacNhanGH: "",
NgayKeHoachGH: "",
FileVB: Path
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
//alert("Đã tạo mới thành công PO!");
$("#notification").data("kendoNotification").show({
message: "Đã tạo mới thành công PO!"
}, "upload-success");
$("#wd_PO_them").data("kendoWindow").close();
DS_PO.read();
Ham_Clear_Form_PO();
uploadReset();
$("#txt_search_soPO").data("kendoAutoComplete").dataSource.read();
}
else {
//alert(msg[0].ErrorMessage);
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
function Ham_Them_PO_Huy() {
$("#wd_PO_them").data("kendoWindow").close();
uploadReset();
}
function Ham_Clear_Form_PO() {
$("#txt_SoPO").val("");
$("#txt_NgayKy").val("");
$("#txt_VB").val("");
for (var j = 1; j < $("#grid_DonVi tr").length; j++) {
$("#grid_DonVi tr")[j].cells[1].childNodes[0].childNodes[0].checked = false;
}
}
//#endregion
//#region Hiển thị chi tiết PO
function Ham_ChiTiet_PO(f) {
BienChiTietPO = f;
var detailRow = f.detailRow;
detailRow.find("#tabstrip").kendoTabStrip({
animation: {
open: { effects: "fadeIn" }
},
select: function (e) {
//alert($("#tabstrip").data("kendoTabStrip").select().index());
//$(e.item).find("> .k-link").text().trim()
//alert(this.select().index());
var content_tab = $(e.item).find("> .k-link").text().trim();
switch (content_tab) {
case "Danh sách đơn vị tham gia PO":
//#region Hiển thị danh sách đơn vị tham gia PO
detailRow.find("#tab_DonVi").empty();
detailRow.find("#tab_DonVi").kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'PO_DonVi_SelectbyPO_ID',
PO_ID: f.data.PO_ID
},
dataType: 'json',
success: function (result) {
//options.success(result);
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
},
pageSize: 8
}),
sortable: true,
pageable: {
messages: {
display: "Tổng số {2} đơn vị",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
columns:
[
{
title: "STT",
headerAttributes: {
class: "header_css"
},
field: "STT",
attributes: {
class: "row_css"
},
width: "30%"
},
{
title: "Đơn vị",
headerAttributes: {
class: "header_css"
},
field: "DonVi_Ten",
attributes: {
class: "row_css"
}
}
]
});
//#endregion
break;
case "Hiển thị phân rã đơn vị":
//#region Hiển thị Phân rã đơn vị
detailRow.find("#tab_PhanRa_DV").empty();
detailRow.find("#tab_PhanRa_DV").kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Con.aspx",
data: {
cmd: 'Lay_DS_PO_Con',
PO_ID: f.data.PO_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
}),
pageable: {
messages: {
display: "Tổng số {2} đơn vị",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
detailInit: function (e) {
e.detailCell.empty();
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_CT.aspx",
data: {
cmd: 'PO_CT_SelectByPO_ID_Con',
PO_ID_Con: e.data.PO_ID_Con
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
},
aggregate: [
{ field: "ThanhTien", aggregate: "sum" }
]
}),
columns:
[
{
title: "Vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
attributes: {
class: "row_css"
}
},
{
title: "Số lượng",
headerAttributes: {
class: "header_css"
},
field: "SoLuong",
template: "#= OnChangeFormat(SoLuong) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
},
{
title: "Thành tiền",
headerAttributes: {
class: "header_css"
},
field: "ThanhTien",
template: "#= OnChangeFormat(ThanhTien) #",
attributes: {
class: "row_css"
},
aggregates: ["sum"],
footerTemplate: "<div class=\"row_css\">#=OnChangeFormat(sum) #</div>",
groupFooterTemplate: "<div class=\"row_css\">#=OnChangeFormat(sum) #</div>",
},
{
title: "VAT",
headerAttributes: {
class: "header_css"
},
field: "VAT",
template: "#= OnChangeFormat(VAT) #",
attributes: {
class: "row_css"
}
}
]
});
},
columns:
[
{
title: "Đơn vị",
headerAttributes: {
class: "header_css"
},
field: "DonVi_Ten",
attributes: {
class: "row_css",
style: "font-weight: bold !important;text-align: left !important;"
}
}
]
});
//#endregion
case "Danh sách PO con đã xuất":
//#region Hiển thị Danh sách PO con đã xuất
DS_PO_Con = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'PONT_Select_By_PO',
PO_ID: f.data.PO_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
if (result.length == 0) {
$("#tab_PO_Con .k-grid-header").css('display', 'none');
}
else {
options.success(result);
}
}
}
});
}
}
//pageSize: 8
});
detailRow.find("#tab_PO_Con").empty();
detailRow.find("#tab_PO_Con").kendoGrid({
dataSource: DS_PO_Con,
sortable: true,
pageable: {
messages: {
display: "Tổng số {2} PO con",
empty: "Chưa xuất PO con ",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
detailInit: function (e) {
DS_TamUng = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_TamUng.aspx",
data: {
cmd: 'HienThi_TamUng_byPO_NhaThau_ID',
PO_NhaThau_ID: e.data.PO_NhaThau_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
},
aggregate: [
{ field: "GiaTri_DeNghi", aggregate: "sum" }
]
});
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: DS_TamUng,
pageable: {
messages: {
display: "Tổng số {2} lần tạm ứng",
empty: "Chưa có tạm ứng ",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
detailInit: function (g) {
$("<div/>").appendTo(g.detailCell).kendoGrid({
dataSource: {
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_TamUng.aspx",
data: {
cmd: 'HienThi_TamUng_ThanhVien',
TamUng_ID: g.data.TamUng_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
},
pageable: {
messages: {
display: "Tổng số {2} thành viên",
empty: "Chưa có tạm ứng ",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
columns:
[
{
title: "Thành viên",
headerAttributes: {
class: "header_css"
},
field: "Ten_ThanhVien",
attributes: {
class: "row_css",
style: "font-weight:bold;"
},
width: 200
},
{
title: "Giá trị đề nghị",
headerAttributes: {
class: "header_css"
},
field: "GiaTri_DeNghi",
template: "#= GiaTri_DeNghi== null ? 0 : OnChangeFormat(GiaTri_DeNghi) #",
attributes: {
class: "row_css",
style: "font-weight:bold;"
},
width: 200
},
{
title: "Số VB đề nghị",
headerAttributes: {
class: "header_css"
},
field: "SoVB_DeNghi",
attributes: {
class: "row_css"
},
width: 200
},
{
title: "Ngày VB đề nghị",
headerAttributes: {
class: "header_css"
},
field: "NgayVB_DeNghi",
attributes: {
class: "row_css"
},
width: 150
},
{
title: "Tài khoản thụ hưởng",
headerAttributes: {
class: "header_css"
},
field: "TaiKhoanThuHuong",
attributes: {
class: "row_css"
},
width: 200
},
{
title: "Tại ngân hàng",
headerAttributes: {
class: "header_css"
},
field: "TaiNganHang",
attributes: {
class: "row_css"
},
width: 200
},
{
title: "Số VB bão lãnh",
headerAttributes: {
class: "header_css"
},
field: "SoVB_BaoLanh",
attributes: {
class: "row_css"
},
width: 200
},
{
title: "Ngày VB bão lãnh",
headerAttributes: {
class: "header_css"
},
field: "NgayVB_BaoLanh",
attributes: {
class: "row_css"
},
width: 150
},
{
title: "Ngân hàng phát hành",
headerAttributes: {
class: "header_css"
},
field: "NganHang_PhatHanh",
attributes: {
class: "row_css"
},
width: 200
},
{
title: "Ngày hiệu lực bảo lãnh",
headerAttributes: {
class: "header_css"
},
field: "NgayHieuLuc_BaoLanh",
attributes: {
class: "row_css"
},
width: 150
},
{
title: "Số VB chuyển HS đề nghị",
headerAttributes: {
class: "header_css"
},
field: "SoVB_ChuyenHS_DeNghi",
attributes: {
class: "row_css"
},
width: 200
},
{
title: "Ngày VB chuyển HS đề nghị",
headerAttributes: {
class: "header_css"
},
field: "NgayVB_ChuyenHS_DeNghi",
attributes: {
class: "row_css"
},
width: 200
}
]
});
},
columns:
[
{
template: function (data) {
if (data.TinhTrang_TamUng == '0') {
return '<center><a class="btn btn-info" onclick="Ham_Sua_TamUng(' + data.TamUng_ID + ',\'' + data.SoVB_TamUng + '\',\'' + data.NgayVB_TamUng_f + '\',\'' + data.GiaTri_DeNghi + '\',\'' + data.GiaTri_PO + '\',\'' + data.SoVB_XacNhan_HieuLuc_PO + '\',\'' + data.NgayVB_XacNhan_HieuLuc_PO_f + '\');"><i class="fa fa-edit "></i> Sửa</a></center>'
}
else {
return ''
}
},
width: 80
},
{
template: function (data) {
if (data.TinhTrang_TamUng == '0') {
return '<center><a class="btn btn-danger" onclick="Ham_Xoa_TamUng(' + data.TamUng_ID + ');"><i class="fa fa-trash-o "></i> Xóa</a></center>'
} else {
return ''
}
},
width: 80
},
{
template: function (data) {
return '<center><a class="btn btn-info" onclick="Ham_Ex_TamUng(' + data.TamUng_ID + ');"><i class="fa fa-download"></i> Report</a></center>'
},
width: 90
},
{
title: "Lần",
headerAttributes: {
class: "header_css"
},
field: "STT",
attributes: {
class: "row_css"
},
width: 80
},
{
title: "Giá trị tạm ứng",
headerAttributes: {
class: "header_css"
},
field: "GiaTri_DeNghi",
template: "#= OnChangeFormat(GiaTri_DeNghi) #",
aggregates: ["sum"],
footerTemplate: "<div class=\"row_css\" >Tổng tạm ứng:<br><div style=\"color:red;\"> #=OnChangeFormat(sum) # </div></div>",
attributes: {
class: "row_css",
style:"font-weight:bold;"
},
width:150
},
{
title: "Số VB xác nhận hiệu lực PO",
headerAttributes: {
class: "header_css"
},
field: "SoVB_XacNhan_HieuLuc_PO",
attributes: {
class: "row_css"
},
width:150
},
{
title: "Ngày VB xác nhận hiệu lực PO",
headerAttributes: {
class: "header_css"
},
field: "NgayVB_XacNhan_HieuLuc_PO_f",
attributes: {
class: "row_css"
},
width:150
},
{
title: "Số VB bảo lãnh",
headerAttributes: {
class: "header_css"
},
field: "SoVB_TamUng",
attributes: {
class: "row_css"
},
width:150
},
{
title: "Ngày VB bảo lãnh",
headerAttributes: {
class: "header_css"
},
field: "NgayVB_TamUng_f",
attributes: {
class: "row_css"
},
width:150
}
]
});
},
columns:
[
//{
// title: "Tình trạng",
// headerAttributes: {
// class: "header_css"
// },
// field: "TinhTrang_ThanhToan",
// template: function (data) {
// if (data.TinhTrang_ThanhToan == '0') {
// return '<center><span class="label label-success">Chưa thanh toán</span></center>';
// }
// else {
// return '<center><span class="label label-important">Đã thanh toán</span></center>';
// }
// },
// width: "12%"
//},
{
title: "Khóa Tạm Ứng",
headerAttributes: {
class: "header_css"
},
template: function (data) {
if ($("[id$=_hf_quyen_KhoaTamUng]").val() == "true") {
if (data.TinhTrang_TamUng == '0') {
return '<center><input type="button" class="button_mokhoa" onclick="Ham_DongKhoa_TamUng(\'' + data.PO_NhaThau_ID + '\');"/></center>';
}
else {
return '<center><input type="button" class="button_khoa" onclick="Ham_MoKhoa_TamUng(\'' + data.PO_NhaThau_ID + '\');"/><div style="color:green;font-weight:bold;">Chuyển kế toán</div><div style="font-weight:bold;">' + data.TW_HS + '</div><div style="font-weight:bold;">' + data.TW_NgayChuyen_KeToan_f + '</div></center>';
}
}
else {
if (data.TinhTrang_TamUng == '0') {
return '<center><input type="button" style="cursor: text;" class="button_mokhoa" /></center>';
}
else {
return '<center><input type="button" class="button_khoa" /><div style="color:green;font-weight:bold;">Chuyển kế toán</div><div style="font-weight:bold;">' + data.TW_HS + '</div><div style="font-weight:bold;">' + data.TW_NgayChuyen_KeToan_f + '</div></center>';
}
}
},
width: 200
},
{
title: "Số hợp đồng",
headerAttributes: {
class: "header_css"
},
field: "MaHD",
attributes: {
class: "row_css"
}
},
{
title: "Nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "NhaThau_Ten",
attributes: {
class: "row_css"
}
},
{
title: "Số VB gửi nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "SoVB",
attributes: {
class: "row_css"
}
},
//{
// title: "Ngày VB",
// headerAttributes: {
// class: "header_css"
// },
// field: "NgayVB",
// template: "#= NgayVB_f #",
// attributes: {
// class: "row_css"
// }
//},
{
title: "File VB",
headerAttributes: {
class: "header_css"
},
field: "FileVB",
template: function (data) {
if (data.FileVB == "" || data.FileVB == null) {
return '';
} else {
return '<center><a href= "' + data.FileVB + '" target="_blank" class="btn btn-inverse" ><i class="fa fa-download"></i> Tải</a></center>';
}
},
width: "9%"
},
//{
// title: "Ngày xuất PO",
// headerAttributes: {
// class: "header_css"
// },
// field: "NgayTaoDonHang",
// template: "#= NgayTaoDonHang_f #",
// attributes: {
// class: "row_css"
// }
//},
{
title: "Tổng thanh toán",
headerAttributes: {
class: "header_css"
},
field: "TongTienThanhToan",
template: "#= OnChangeFormat(TongTienThanhToan) #",
attributes: {
class: "row_css",
style: "font-weight:bold;"
},
width: "15%"
},
{
template: function (data) {
if (data.TinhTrang_TamUng == '0') {
return '<center><a class="btn btn-info" onclick="Ham_TamUng(' + data.PO_NhaThau_ID + ',' + data.NhaThau_ID + ',' + data.TongTienThanhToan + ');"><i class="fa fa-money"></i> Tạm ứng</a></center>'
}
else {
return ''
}
},
width: "15%"
}
//{
// title: "Ngày bắt đầu",
// headerAttributes: {
// class: "header_css"
// },
// field: "NgayBatDau",
// template: "#= NgayBatDau_f #",
// attributes: {
// class: "row_css"
// }
//},
//{
// title: "Ngày kết thúc",
// headerAttributes: {
// class: "header_css"
// },
// field: "NgayKetThuc",
// template: "#= NgayKetThuc_f #",
// attributes: {
// class: "row_css"
// }
//},
]
});
//#endregion
}
}
});
//#region Hiển thị phân rã vật tư
var toolbar_vattu;
var columns_vattu;
if (BienChiTietPO.data.TinhTrang == "0") {
toolbar_vattu = kendo.template($("#Templ_PO_VatTu").html());
columns_vattu = [
{
title: "Số hợp đồng",
headerAttributes: {
class: "header_css"
},
field: "MaHD",
groupHeaderTemplate: "#= Ham_HienThi_Xuat_PO( value ) #",
hidden: true,
attributes: {
class: "row_css"
}
},
{
title: "Tên nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "TenNhaThau",
attributes: {
class: "row_css",
style: "font-weight:bold;color:blue;"
},
hidden: true
},
{
title: "Vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>",
attributes: {
class: "row_css",
style: "font-weight:bold;"
},
width: "20%"
},
//{
// title: "Số lượng đã phân rã",
// headerAttributes: {
// class: "header_css"
// },
// field: "abc",
// template: "#= OnChangeFormat(SoLuong_PO - SoLuongConLai_PO) #",
// attributes: {
// class: "row_css",
// style: "font-weight:bold;color:green;"
// }
//},
// {
// title: "Số lượng còn lại",
// headerAttributes: {
// class: "header_css"
// },
// field: "SoLuongConLai_PO",
// template: "#= OnChangeFormat(SoLuongConLai_PO) #",
// attributes: {
// class: "row_css",
// style: "font-weight:bold;color:blue;"
// }
// },
{
title: "Số lượng tổng PO",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_PO",
template: "#= OnChangeFormat(SoLuong_PO) #",
attributes: {
class: "row_css",
style: "color:red;font-weight:bold;"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
},
{
title: "Thành tiền",
headerAttributes: {
class: "header_css"
},
field: "ThanhTien_PO",
template: "#= OnChangeFormat(ThanhTien_PO) #",
attributes: {
class: "row_css"
},
aggregates: ["sum"],
groupFooterTemplate: "<div class=\"row_css\">Tổng cộng: #=OnChangeFormat(sum) #</div>",
width: "12%"
},
{
template: function (data) {
if ($("[id$=_hf_quyen_capnhat]").val() == "true") {
if (data.Check_XuatPO_HD == "0") {
return '<center><a onclick="Ham_PhanRa(' + data.PO_ID + ',' + data.PO_HD_ID + ',' + data.VatTu_ID + ');" class="btn btn-info"><i class="fa fa-list"></i> Phân rã</a></center>'
} else {
return '';
}
}
else {
return '';
}
},
width: "12%"
},
{
template: function (data) {
if ($("[id$=_hf_quyen_capnhat]").val() == "true") {
if (data.Check_XuatPO_HD == "0") {
return '<center><a class="btn btn-info" onclick="Ham_Sua_PO_HD_CT(' + data.PO_HD_ID + ',\'' + data.VatTu_Ten + '\',' + data.SoLuongTongHD + ',' + data.HopDong_ID + ',' + data.VatTu_ID + ',' + data.SoLuong_PO + ');"><i class="fa fa-edit "></i> Sửa</a></center>'
} else {
return ''
}
}
else {
return ''
}
},
width: "9%"
},
{
template: function (data) {
if ($("[id$=_hf_quyen_capnhat]").val() == "true") {
if (data.Check_XuatPO_HD == "0") {
return '<center><a class="btn btn-danger" onclick="Ham_Xoa_PO_HD_CT(' + data.PO_HD_ID + ');"><i class="fa fa-trash-o "></i> Xóa</a></center>'
} else {
return ''
}
}
else {
return ''
}
},
width: "8%"
}
];
}
else {
toolbar_vattu = "";
columns_vattu = [
{
title: "Số hợp đồng",
headerAttributes: {
class: "header_css"
},
field: "MaHD",
groupHeaderTemplate: "#= Ham_HienThi_MaHD( value ) #",
hidden: true,
attributes: {
class: "row_css"
}
},
{
title: "Tên nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "TenNhaThau",
attributes: {
class: "row_css",
style: "font-weight:bold;color:blue;"
},
hidden: true
},
{
title: "Vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>",
attributes: {
class: "row_css"
},
width: "20%"
},
//{
// title: "Số lượng đã phân rã",
// headerAttributes: {
// class: "header_css"
// },
// field: "abc",
// template: "#= OnChangeFormat(SoLuong_PO - SoLuongConLai_PO) #",
// attributes: {
// class: "row_css",
// style: "font-weight:bold;color:green;"
// }
//},
// {
// title: "Số lượng còn lại",
// headerAttributes: {
// class: "header_css"
// },
// field: "SoLuongConLai_PO",
// template: "#= OnChangeFormat(SoLuongConLai_PO) #",
// attributes: {
// class: "row_css",
// style: "font-weight:bold;color:blue;"
// }
// },
{
title: "Số lượng tổng PO",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_PO",
template: "#= OnChangeFormat(SoLuong_PO) #",
attributes: {
class: "row_css",
style: "color:red;font-weight:bold;"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
},
{
title: "Thành tiền",
headerAttributes: {
class: "header_css"
},
field: "ThanhTien_PO",
template: "#= OnChangeFormat(ThanhTien_PO) #",
attributes: {
class: "row_css"
},
aggregates: ["sum"],
groupFooterTemplate: "<div class=\"row_css\">Tổng cộng: #=OnChangeFormat(sum) #</div>"
},
];
}
DS_BangKe_Cap1 = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_DonVi_SelectbyPO_ID',
PO_ID: f.data.PO_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
},
pageSize: 8,
group:
[
{
field: "MaHD",
aggregates: [
{ field: "ThanhTien_PO", aggregate: "sum" }
]
}
]
});
///////////////////////////////////////
detailRow.find("#tab_VatTu").empty();
detailRow.find("#tab_VatTu").kendoGrid({
dataSource: DS_BangKe_Cap1,
sortable: true,
pageable: {
messages: {
display: "Tổng số {2} vật tư",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
toolbar: $("[id$=_hf_quyen_capnhat]").val() == "true" ? toolbar_vattu : "",
columns: columns_vattu,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
detailInit: Ham_ChiTiet_VatTu
});
///////////////////////////////////////
//#endregion
}
function Ham_HienThi_Xuat_PO(value) {
var arr_dv = value.split("*");
if ($("[id$=_hf_quyen_capnhat]").val() == "true") {
if ($("[id$=_hf_quyen_GoXuatPO]").val() == "true") {
if (arr_dv[0] == "0") {
return "<b>Số hợp đồng: " + arr_dv[1] + "</b><span class='label label-success' style='margin-left:10px !important;'>Chưa xuất PO con</span><span style='margin-left:50px !important;margin-right:10px !important;' class='btn btn-info' onclick ='Ham_Xuat_DonHang(\" " + arr_dv[1] + " \");'><i class='fa fa-star-half-o'></i> Xuất PO con</span><span class='btn btn-info' style='margin-right:10px !important;' onclick='Ham_Xuat_Ex(\" " + value + " \");'><i class='fa fa-download'></i> Xuất Excel</span><span class='btn btn-info' onclick='Ham_Xuat_TDH(\" " + arr_dv[1] + " \");'><i class='fa fa-envelope'></i> Xuất thư đặt hàng</span>";
}
else {
return '<b>Số hợp đồng: ' + arr_dv[1] + '</b><span class="label label-important" style="margin-left:10px !important;">Đã xuất PO con</span><span style="margin-left:160px !important;" class="btn btn-info" onclick ="Ham_Go_DonHang(\' ' + arr_dv[1] + ' \');"><i class="fa fa-mail-reply"></i> Gỡ xuất PO con</span>';
}
}
else {
if (arr_dv[0] == "0") {
return "<b>Số hợp đồng: " + arr_dv[1] + "</b><span class='label label-success' style='margin-left:10px !important;'>Chưa xuất PO con</span><span style='margin-left:50px !important;margin-right:10px !important;' class='btn btn-info' onclick ='Ham_Xuat_DonHang(\" " + arr_dv[1] + " \");'><i class='fa fa-star-half-o'></i> Xuất PO con</span><span class='btn btn-info' style='margin-right:10px !important;' onclick='Ham_Xuat_Ex(\" " + value + " \");'><i class='fa fa-download'></i> Xuất Excel</span><span class='btn btn-info' onclick='Ham_Xuat_TDH(\" " + arr_dv[1] + " \");'><i class='fa fa-envelope'></i> Xuất thư đặt hàng</span>";
}
else {
return '<b>Số hợp đồng: ' + arr_dv[1] + '</b><span class="label label-important" style="margin-left:10px !important;">Đã xuất PO con</span>';
}
}
} else {
if (arr_dv[0] == "0") {
return "<b>Số hợp đồng: " + arr_dv[1] + "</b><span class='label label-success' style='margin-left:10px !important;'>Chưa xuất PO con</span>";
}
else {
return '<b>Số hợp đồng: ' + arr_dv[1] + '</b><span class="label label-important" style="margin-left:10px !important;">Đã xuất PO con</span>';
}
}
}
//#endregion
//#region Gỡ xuất đơn hàng
function Ham_Go_DonHang(p_MaHD) {
if (confirm("Bạn có chắc chắn muốn gỡ xuất PO con này không?")) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_DonDatHang.aspx",
data: {
cmd: 'Go_DonHang',
PO_ID: BienChiTietPO.data.PO_ID,
MaHD: p_MaHD
},
dataType: 'json'
});
request.done(function (msg) {
switch (msg[0].ErrorMessage) {
case "An invalid parameter or option was specified for procedure 'Co_Thanh_Toan'.":
$("#notification").data("kendoNotification").show({
title: "",
message: "PO con này đã thanh toán nêu không thể gỡ xuất!"
}, "error");
break;
case "An invalid parameter or option was specified for procedure 'Co_TienDo_ThucTe'.":
$("#notification").data("kendoNotification").show({
title: "",
message: "PO con này nhà thầu đã cam kết thực tế nêu không thể gỡ xuất!"
}, "error");
break;
case "An invalid parameter or option was specified for procedure 'Co_TienDo_CamKet'.":
$("#notification").data("kendoNotification").show({
title: "",
message: "PO con này nhà thầu đã cam kết nêu không thể gỡ xuất!"
}, "error");
break;
case null:
$("#notification").data("kendoNotification").show({
message: "Đã gỡ xuất thành công!"
}, "upload-success");
DS_PO.read();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
//#endregion
//#region Xuất đơn hàng
function Ham_Xuat_DonHang(p_MaHD) {
$("#lb_MaHD").text(p_MaHD);
$("#wd_DatHang").data("kendoWindow").center().open();
uploadReset();
Path_PO = "";
}
function Ham_Huy_DonHang() {
$("#wd_DatHang").data("kendoWindow").close();
$("#txt_SoNgayTH").data("kendoNumericTextBox").value("");
$("#txt_NgayBatDau").val("");
$("#txt_vb_DatHang").val("");
$("#txt_NgayVB").val("");
}
function Ham_Luu_Xuat_DonHang() {
var check = 0;
if ($("#txt_vb_DatHang").val() == "") {
check = 1;
alert("Chưa nhập số văn bản đặt hàng!");
return;
}
if ($("#txt_NgayVB").val() == "") {
check = 1;
alert("Chưa nhập ngày kí văn bản đặt hàng!");
return;
}
if (Path_PO == "") {
check = 1;
alert("Chưa upload tập tin văn bản!");
return;
}
if ($("#txt_NgayBatDau").val() == "") {
check = 1;
alert("Chưa chọn ngày thực hiện!");
return;
}
if ($("#txt_SoNgayTH").val() == "") {
check = 1;
alert("Chưa nhập số ngày thực hiện!");
return;
}
if (check == 0) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_DonDatHang.aspx",
data: {
cmd: 'Xuat_DonHang',
PO_ID: BienChiTietPO.data.PO_ID,
SoVB: $("#txt_vb_DatHang").val(),
NgayVB: $("#txt_NgayVB").val(),
MaHD: $("#lb_MaHD").text().trim(),
FileVB: Path_PO,
NgayBatDau: $("#txt_NgayBatDau").val(),
SoNgayThucHien: $("#txt_SoNgayTH").val()
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
//alert("Đã xuất các đơn hàng thành công!");
$("#notification").data("kendoNotification").show({
message: "Đã xuất các đơn hàng thành công!"
}, "upload-success");
DS_PO.read();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
$("#wd_DatHang").data("kendoWindow").close();
$("#txt_SoNgayTH").data("kendoNumericTextBox").value("");
$("#txt_NgayBatDau").val("");
$("#txt_vb_DatHang").val("");
$("#txt_NgayVB").val("");
}
else {
//alert(msg[0].ErrorMessage);
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
//#endregion
//#region Hiển thị chi tiết vật tư
function Ham_ChiTiet_VatTu(e) {
Bien_ChiTiet_VatTu = e;
DS_BangKe_Cap2 = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Con.aspx",
data: {
cmd: 'BangKe_Cap2',
PO_ID: BienChiTietPO.data.PO_ID,
VatTu_ID: e.data.VatTu_ID,
},
dataType: 'json',
success: function (result) {
//options.success(result);
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
});
e.detailCell.empty();
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: DS_BangKe_Cap2,
pageable: {
messages: {
display: "Tổng số {2} đơn vị",
empty: "Chưa phân rã",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
columns:
[
{
title: "Đơn vị",
headerAttributes: {
class: "header_css"
},
field: "TenDonVi",
attributes: {
class: "row_css"
}
},
{
title: "Số lượng",
headerAttributes: {
class: "header_css"
},
field: "SoLuong",
//template: "#= OnChangeFormat(SoLuong) #",
template: function (data) {
if (data.TinhTrang_DC == 0) {
return '' + OnChangeFormat(data.SoLuong) + '';
} else {
return '' + OnChangeFormat(data.SoLuong) + '</br><a>(Đã điều chỉnh)</a>';
}
},
attributes: {
class: "row_css",
style: "font-weight:bold;color:green;"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Thành tiền",
headerAttributes: {
class: "header_css"
},
field: "ThanhTien",
template: "#= OnChangeFormat(ThanhTien) #",
attributes: {
class: "row_css"
}
},
{
title: "VAT",
headerAttributes: {
class: "header_css"
},
field: "VAT",
template: "#= OnChangeFormat(VAT) #",
attributes: {
class: "row_css"
}
},
{
template: function (data) {
//if ($("[id$=_hf_quyen_capnhat]").val() == "true") {
// if (data.HienThi_DC_PO == "0") {
return '<center><a class="btn btn-info" onclick="Ham_DC_PO(' + data.PO_ChiTiet_ID + ',\'' + data.SoLuong + '\');"><i class="fa fa-pencil"></i> Điều chỉnh</a></center>'
// } else {
// return ''
// }
//}
//else {
// return ''
//}
},
width: "14%"
}
]
});
}
function Ham_HienThi_MaHD(value) {
var arr_dv = value.split("*");
return "<b>Số hợp đồng: " + arr_dv[1] + "</b>";
}
//#endregion
//#region Tìm và chọn Vật tư
function Ham_TaoMoiVatTu_KhaDung() {
$("#wd_Show_VatTu").data("kendoWindow").center().open();
$('#grid_VatTu').data('kendoGrid').dataSource.read();
//#region hiển thị danh sách vật tư được chọn
DS_VatTu_PO = new kendo.data.DataSource({
data: [],
schema: {
model: {
fields: {
SoLuong_KhaDung: { editable: false, type: "number" },
SoLuong_PO: {
type: "number",
validation: {
//required: { message: "Chưa nhập số lượng!" }
//////////////////////////////////
NameValidation: function (input) {
var grid = $("#grid_VatTu_PO").data("kendoGrid");
var tr = $(input).closest('tr');
var dataRow = grid.dataItem(tr);
var SL_PO = $(input).val();
var SL_KhaDung = dataRow.SoLuong_KhaDung;
if (input.is("[name='SoLuong_PO']") && input.val() == "") {
input.attr("data-NameValidation-msg", "Chưa nhập số lượng!");
return false;
}
if (input.is("[name='SoLuong_PO']") && SL_PO > SL_KhaDung) {
input.attr("data-NameValidation-msg", "Số lượng PO vượt quá số lượng khả dụng!");
return false;
}
//if (input.is("[name='SoLuong_PO']") && SL_PO > SL_KhaDung) {
// if (confirm("Số lượng PO vượt quá số lượng khả dụng! Có muốn tiếp tục?")) {
// alert("ok");
// return true;
// } else {
// input.attr("data-NameValidation-msg", "Số lượng PO vượt quá số lượng khả dụng!");
// return false;
// }
//}
return true;
}
/////////////////////////////////////
////Hàm ràng buộc http://jsfiddle.net/psu8umLn/1/
//required: false,
//validationMessage: "Số lượng PO vượt quá số lượng khả dụng!",
//custom: function (element) {
// var grid = $("#grid_VatTu_PO").data("kendoGrid");
// var tr = $(element).closest('tr');
// var dataRow = grid.dataItem(tr);
// var SL_PO = $(element).val();
// var SL_KhaDung = dataRow.SoLuong_KhaDung;
// return (SL_PO <= SL_KhaDung);
//}
////////////////////////
}
}
}
}
}
});
$("#grid_VatTu_PO").empty();
$("#grid_VatTu_PO").kendoGrid({
dataSource: DS_VatTu_PO,
pageable: {
messages: {
display: "Tổng số {2} vật tư của PO",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
editable: true,
edit: function (e) {
var input = e.container.find(".k-input");
input.val("");
},
toolbar: kendo.template($("#Templ_VatuTu_PO").html()),
columns:
[
{
title: "Vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
//template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>",
attributes: {
class: "row_css",
style: "font-weight:bold;"
}
},
{
title: "Số lượng khả dụng",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_KhaDung",
template: "#= OnChangeFormat(SoLuong_KhaDung) #",
attributes: {
class: "row_css",
style: "font-weight:bold;color:green;"
}
},
{
title: "Số lượng PO",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_PO",
template: function (data) {
if (data.SoLuong_PO == 0) {
return data.SoLuong_PO;
} else {
return '<b style="color:blue;">' + OnChangeFormat(data.SoLuong_PO) + '</b>';
}
},
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoNumericTextBox({
format: 'n3',
decimals: 3
})
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
},
{
title: "Số HĐ",
headerAttributes: {
class: "header_css"
},
field: "MaHD",
attributes: {
class: "row_css",
style: "font-weight:bold;"
}
},
{
title: "Nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "NhaThau_Ten",
attributes: {
class: "row_css"
}
},
{
template: '<center><a class="btn btn-danger" onclick="Ham_Xoa_VatTu_PO(#= STT #);"><i class="fa fa-trash-o "></i> Xóa</a></center>',
width: "8%"
}
]
});
//#endregion
}
function Ham_TaoMoiVatTu_HD() {
$("#wd_ChonVatTu_Vuot").data("kendoWindow").center().open();
$("#grid_VatTu_Vuot").empty();
$("#grid_VatTu_Vuot").kendoGrid({
pageable: {
messages: {
display: "Tổng số {2} vật tư của PO",
empty: "Không có dữ liệu",
page: "Trang",
of: "of {0}",
itemsPerPage: "Số mục trong một trang"
}
},
editable: true,
edit: function (e) {
var input = e.container.find(".k-input");
input.val("");
},
toolbar: kendo.template($("#Templ_VatTu_Vuot").html()),
columns:
[
{
title: "Vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
//template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>",
attributes: {
class: "row_css",
style: "font-weight:bold;"
}
},
{
title: "Số lượng hợp đồng",
headerAttributes: {
class: "header_css"
},
field: "SoLuong",
template: "#= OnChangeFormat(SoLuong) #",
attributes: {
class: "row_css",
//style: "font-weight:bold;color:green;"
}
},
{
title: "Số lượng khả dụng",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_KhaDung",
template: "#= OnChangeFormat(SoLuong_KhaDung) #",
attributes: {
class: "row_css",
style: "font-weight:bold;color:green;"
}
},
{
title: "Số lượng PO",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_PO",
//template: function (data) {
// if (data.SoLuong_PO == 0) {
// return data.SoLuong_PO;
// } else {
// return '<b style="color:blue;">' + OnChangeFormat(data.SoLuong_PO) + '</b>';
// }
//},
template: function (data) {
if (data.SoLuong_PO == "null" || data.SoLuong_PO == null) {
return 0;
} else {
return '<b style="color:blue;">' + OnChangeFormat(data.SoLuong_PO) + '</b>';
}
},
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoNumericTextBox({
format: 'n3',
decimals: 3
})
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
}
]
});
$("#div_GTHD").hide();
var txt_search_sohd_vuot = $("#txt_search_sohd_vuot").kendoComboBox({
dataTextField: "MaHD",
dataValueField: "HopDong_ID",
filter: "contains",
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_HopDong.aspx",
data: {
cmd: 'Lay_DS_HopDong'
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
}),
change: function () {
GiaTriHopDong_ConLai = txt_search_sohd_vuot.dataItem(txt_search_sohd_vuot.select()).GiaTriConLai_HD;
//$("#lb_GTHD").text(OnChangeFormat(txt_search_sohd_vuot.dataItem(txt_search_sohd_vuot.select()).GiaTriTruocThue));
$("#lb_GTHD_ConLai").text(OnChangeFormat(txt_search_sohd_vuot.dataItem(txt_search_sohd_vuot.select()).GiaTriConLai_HD));
var ds = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_HopDong_CT.aspx",
data: {
cmd: 'Lay_DS_HopDong_CT',
HopDong_ID: txt_search_sohd_vuot.value()
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
fields: {
SoLuong_KhaDung: { editable: false, type: "number" },
SoLuong_PO: { type: "number" }
}
}
}
});
$("#grid_VatTu_Vuot").data("kendoGrid").setDataSource(ds);
$("#div_GTHD").show();
}
}).data("kendoComboBox");
}
function Ham_TaoMoiVatTu() {
$("#wd_List_Option").data("kendoWindow").center().open();
}
function Ham_Chon_TaoMoiVatTu() {
if ($("#rdo_sl").is(":checked")) {
Ham_TaoMoiVatTu_KhaDung();
} else {
Ham_TaoMoiVatTu_HD();
}
}
function Ham_Huy_ChonTaoMoiVatTu() {
$("#wd_List_Option").data("kendoWindow").close();
}
var ItemChecked = {};
function selectRow() {
var checked = this.checked,
row = $(this).closest("tr"),
grid = $("#grid_VatTu").data("kendoGrid"),
dataItem = grid.dataItem(row);
ItemChecked[dataItem.uid] = checked;
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
//#endregion
//#region Hàm chọn vật tư
function Ham_Chon_VatTu() {
//http://docs.telerik.com/kendo-ui/web/grid/how-to/Selection/grid-selection-checkbox
for (var i in ItemChecked) {
if (ItemChecked[i]) {
var grid = $("#grid_VatTu").data("kendoGrid");
var selectedTopic = grid.dataSource.getByUid(i);
var check = 0;
for (var i = 0; i < DS_VatTu_PO.data().length; i++) {
if (DS_VatTu_PO.data()[i].STT == selectedTopic.STT) {
check = 1;
break;
}
}
if (check == 0) {
DS_VatTu_PO.add(selectedTopic);
}
}
}
for (var i = 0; i < $("#grid_VatTu tr").length; i++) {
var className_ = $("#grid_VatTu tr")[i].className;
if (className_ == 'k-state-selected' || className_ == 'k-alt k-state-selected') {
$($("#grid_VatTu tr")[i]).removeClass("k-state-selected");
$("#grid_VatTu tr")[i].cells[0].childNodes[0].childNodes[0].checked = false;
}
}
ItemChecked = {};
//var grid = $("#grid_VatTu").data("kendoGrid");
//var selectedTopic = grid.dataSource.getByUid(grid.select().data("uid"));
//if (selectedTopic == undefined) {
// alert("Chưa chọn vật tư!");
// return;
//}
//else {
// ///////////////////////////////////////////////////////////
// var check = 0;
// for (var i = 0; i < DS_VatTu_PO.data().length; i++) {
// if (DS_VatTu_PO.data()[i].STT == selectedTopic.STT) {
// check = 1;
// break;
// }
// }
// if (check == 0) {
// DS_VatTu_PO.add(selectedTopic);
// }
// else {
// alert("Vật tư đã được chọn!");
// }
// ////////////////////////////////////////////////////////////
// //$("#wd_Show_VatTu").data("kendoWindow").close();
// //$("#txt_VatTu_PO").text(selectedTopic.VatTu_Ten);
// //VatTu_ID_PO = selectedTopic.VatTu_ID;
// //$("#txt_SoLuong_HD").text(OnChangeFormat(selectedTopic.SoLuong_KhaDung));
// //HopDong_ID = selectedTopic.HopDong_ID;
// //var request = $.ajax({
// // type: "POST",
// // url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
// // data: {
// // cmd: 'PO_HopDong_CT_SLTong',
// // HopDong_ID: selectedTopic.HopDong_ID,
// // VatTu_ID: selectedTopic.VatTu_ID
// // },
// // dataType: 'json'
// //});
// //request.done(function (msg) {
// // if (msg[0].SoLuongKhaDung == "0") {
// // alert("Vật tư này đã được đặt hết!");
// // $("#txt_SoLuong_PO").val("");
// // } else {
// // $("#wd_VatTu_PO").data("kendoWindow").center().open();
// // $("#txt_SoLuong_KD").text(OnChangeFormat(msg[0].SoLuongKhaDung));
// // }
// //});
// //request.fail(function (jqXHR, textStatus) {
// // alert("Request failed: " + textStatus);
// //});
//}
}
//#endregion
//#region Hàm xóa vật tư tạm trong danh sách vật tư PO
function Ham_Xoa_VatTu_PO(p_STT) {
for (var i = 0; i < DS_VatTu_PO.data().length; i++) {
var item = DS_VatTu_PO.data()[i];
if (item.STT == p_STT) {
DS_VatTu_PO.remove(item);
}
}
}
//#endregion
//#region Hàm lưu thiệt vật tư PO theo danh sách chọn
function Ham_Luu_VatTu_PO_Vuot() {
var DS_Grid_Vuot = $("#grid_VatTu_Vuot").data("kendoGrid").dataSource.data();
if (DS_Grid_Vuot.length == 0) {
alert("Chưa chọn hợp đồng!");
} else {
var TongSoLuong = 0;
for (var j = 0; j < DS_Grid_Vuot.length; j++) {
var p_soluong = DS_Grid_Vuot[j].SoLuong_PO == null ? 0 : DS_Grid_Vuot[j].SoLuong_PO;
TongSoLuong += DS_Grid_Vuot[j].DonGia * parseFloat(ReplaceComma('' + p_soluong + ''));
}
if (parseFloat(TongSoLuong) > parseFloat(GiaTriHopDong_ConLai)) {
alert("Vượt quá giá trị hợp đồng!");
} else {
for (var j = 0; j < DS_Grid_Vuot.length; j++) {
var p_HopDong_ID = $("#txt_search_sohd_vuot").data("kendoComboBox").value();
var p_VatTu_ID = DS_Grid_Vuot[j].VatTu_ID;
var p_SoLuong_PO = DS_Grid_Vuot[j].SoLuong_PO == null ? 0 : DS_Grid_Vuot[j].SoLuong_PO;
if (p_SoLuong_PO != 0) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_HopDong_CT_Create',
PO_ID: BienChiTietPO.data.PO_ID,
HopDong_ID: p_HopDong_ID,
VatTu_ID: p_VatTu_ID,
SoLuong_PO: p_SoLuong_PO
},
dataType: 'json'
});
}
}
//alert("Đã thêm thành công vật tư!");
$("#notification").data("kendoNotification").show({
message: "Đã thêm thành công vật tư!"
}, "upload-success");
$("#wd_ChonVatTu_Vuot").data("kendoWindow").close();
$("#wd_List_Option").data("kendoWindow").close();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
DS_VatTu.read();
DS_PO.read();
}
}
}
function Ham_Huy_VatTu_PO_Vuot() {
$("#wd_ChonVatTu_Vuot").data("kendoWindow").close();
}
function Ham_Luu_VatTu_PO() {
var DS_Grid = $("#grid_VatTu_PO").data("kendoGrid").dataSource.data();
var check = 0;
for (var j = 0; j < DS_Grid.length; j++) {
var p_HopDong_ID = DS_Grid[j].HopDong_ID;
var p_VatTu_ID = DS_Grid[j].VatTu_ID;
var p_SoLuong_PO = DS_Grid[j].SoLuong_PO;
if (p_SoLuong_PO == 0) {
//alert("Chưa nhập số lượng PO!");
$("#notification").data("kendoNotification").show({
title: "Chưa nhập số lượng PO!",
message: "Hãy nhập số lượng PO!"
}, "error");
check = 1;
break;
}
else {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_HopDong_CT_Create',
PO_ID: BienChiTietPO.data.PO_ID,
HopDong_ID: p_HopDong_ID,
VatTu_ID: p_VatTu_ID,
SoLuong_PO: p_SoLuong_PO
},
dataType: 'json'
});
}
}
if (check == 0) {
//alert("Đã thêm thành công vật tư!");
$("#notification").data("kendoNotification").show({
message: "Đã thêm thành công vật tư!"
}, "upload-success");
$("#wd_Show_VatTu").data("kendoWindow").close();
$("#wd_List_Option").data("kendoWindow").close();
DS_PO.read();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
DS_VatTu.read();
}
}
//#endregion
//#region Hàm lưu vật tư PO đơn lẻ (ver cũ)
function Ham_Luu_ThemPO_HD_CT() {
//var str_id_vattu = '';
//var hopdong_id;
//for (var j = 1; j < $("#grid_HD_CT tr").length; j++) {
// var chb_dv = $("#grid_HD_CT tr")[j].cells[2].childNodes[0].childNodes[0];
// var id = $("#grid_HD_CT tr")[j].cells[1].childNodes[0].textContent;
// if (chb_dv.checked == true) {
// str_id_vattu += '' + id + ',';
// hopdong_id = $("#grid_HD_CT tr")[j].cells[0].childNodes[0].textContent;
// }
//}
//str_id_vattu = str_id_vattu.replace(/^,|,$/g, '');
//if (str_id_vattu=='') {
// alert("Chưa chọn vật tư!");
// check = 1;
// return;
//}
var check = 0;
if ($("#txt_SoLuong").val() == "" || $("#txt_SoLuong").val() == "0") {
check = 1;
//alert("Chưa nhập số lượng!");
$("#notification").data("kendoNotification").show({
title: "Chưa nhập số lượng!",
message: "Hãy nhập số lượng!"
}, "error");
return;
}
if (check == 0) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_HopDong_CT_Create',
PO_ID: BienChiTietPO.data.PO_ID,
HopDong_ID: HopDong_ID,
VatTu_ID: VatTu_ID_PO,
SoLuong_PO: parseFloat($("#txt_SoLuong_PO").val())
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
//alert("Đã thêm thành công vật tư!");
$("#notification").data("kendoNotification").show({
message: "Đã thêm thành công vật tư!"
}, "upload-success");
$("#wd_VatTu_PO").data("kendoWindow").close();
$("#wd_List_Option").data("kendoWindow").close();
DS_PO.read();
Ham_ChiTiet_PO(BienChiTietPO);
//$("#txt_SoLuong_PO").val("");
$("#txt_SoLuong_PO").data("kendoNumericTextBox").value("");
}
else {
//alert(msg[0].ErrorMessage);
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
function Ham_Huy_ThemPO_HD_CT() {
$("#wd_VatTu_PO").data("kendoWindow").close();
}
//#endregion
//#region Sửa vật tư PO
function Ham_Sua_PO_HD_CT(p_PO_HD_ID, VatTu_Ten, SoLuongTongHD, HopDong_ID, VatTu_ID, SoLuong_PO) {
$("#wd_VatTu_PO_Sua").data("kendoWindow").center().open();
$("#txt_VatTu_PO_Sua").text(VatTu_Ten);
$("#txt_SoLuong_HD_Sua").text(OnChangeFormat(SoLuongTongHD));
$("#txt_SoLuong_PO_Sua").data("kendoNumericTextBox").value(SoLuong_PO);
PO_HD_ID = p_PO_HD_ID;
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_HopDong_CT_SLTong',
HopDong_ID: HopDong_ID,
VatTu_ID: VatTu_ID
},
dataType: 'json'
});
request.done(function (msg) {
$("#txt_SoLuong_KD_Sua").text(OnChangeFormat(msg[0].SoLuongKhaDung));
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
function Ham_Luu_SuaPO_HD_CT() {
var check = 0;
var SoLuong_PO = parseFloat(ReplaceComma($("#txt_SoLuong_PO_Sua").val()));
var SoLuong_HD = parseFloat(ReplaceComma($("#txt_SoLuong_HD_Sua").text()));
if (SoLuong_PO > SoLuong_HD) {
check = 1;
//alert("Số lượng vượt số lượng khả dụng!");
$("#notification").data("kendoNotification").show({
title: "Số lượng vượt số lượng khả dụng!",
message: "Hãy nhập lại!"
}, "error");
return;
}
if ($("#txt_SoLuong_Sua").val() == "" || $("#txt_SoLuong_Sua").val() == "0") {
check = 1;
//alert("Chưa nhập số lượng!");
$("#notification").data("kendoNotification").show({
title: "Chưa nhập số lượng!",
message: "Hãy nhập số lượng!"
}, "error");
return;
}
if (check == 0) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_HopDong_CT_Update_SL',
PO_HD_ID: PO_HD_ID,
SoLuong_PO: parseFloat($("#txt_SoLuong_PO_Sua").val())
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
//alert("Đã sửa thành công vật tư!");
$("#notification").data("kendoNotification").show({
message: "Đã sửa thành công vật tư! Hãy phân rã lại vật tư"
}, "upload-success");
$("#wd_VatTu_PO_Sua").data("kendoWindow").close();
DS_PO.read();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
}
else {
//alert(msg[0].ErrorMessage);
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
function Ham_Huy_SuaPO_HD_CT() {
$("#wd_VatTu_PO_Sua").data("kendoWindow").close();
}
//#endregion
//#region Xóa vật tư PO
function Ham_Xoa_PO_HD_CT(p_PO_HD_CT) {
if (confirm("Bạn có chắc muốn xóa vật tư này không?")) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_HopDong_CT_Delete',
PO_HD_CT: p_PO_HD_CT
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
//alert("Đã xóa thành công vật tư!");
$("#notification").data("kendoNotification").show({
message: "Đã xóa thành công vật tư!"
}, "upload-success");
DS_PO.read();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
}
else {
//alert(msg[0].ErrorMessage);
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
//#endregion
//#region Hiển thị phân rã vật tư PO
function Ham_PhanRa(p_PO_ID, p_PO_HD_ID, p_VatTu_ID) {
$("#wd_PhanRa").data("kendoWindow").center().open();
var ds = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_DonVi_SelectbyPO_ID',
PO_ID: p_PO_ID
},
dataType: 'json',
success: function (result) {
//options.success(result);
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
},
filter: { field: "PO_HD_ID", operator: "eq", value: p_PO_HD_ID }
});
ds.fetch(function () {
var view = ds.view();
$("#txt_VatTu").text(view[0].VatTu_Ten);
$("#txt_MaVatTu").text(view[0].MaVatTu_TD);
VatTu_ID = view[0].VatTu_ID;
$("#txt_DonGia").text(OnChangeFormat(view[0].DonGia));
MaDVT = view[0].MaDVT;
$("#txt_DVT").text(view[0].TenDVT);
$("#txt_SoLuong_Tong").text(OnChangeFormat(view[0].SoLuong_PO));
});
$("#grid_PhanRa").kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'PhanRa_ShowSL',
PO_ID: p_PO_ID,
VatTu_ID: p_VatTu_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
},
schema: {
model: {
fields: {
PO_DV_ID: { editable: false, type: "number" },
DonVi_Ten: { editable: false, type: "string" },
SoLuong_DV: {
type: "number",
validation: {
required: { message: "Chưa nhập số lượng!" }
}
}
}
}
}
}),
height: 300,
editable: true,
edit: function (e) {
var input = e.container.find(".k-input");
input.val("");
//input.keyup(function () {
// value = input.val();
//});
//$("[name='SoLuong_DV']", e.container).blur(function () {
// var input = $(this);
// var grid = $("#grid_PhanRa").data("kendoGrid");
// var row = $(this).closest("tr");
// var item = grid.dataItem(row);
// //alert(item.SoLuong_DV);
//});
},
columns:
[
{ field: "PO_DV_ID", hidden: true },
{
title: "Đơn vị",
headerAttributes: {
class: "header_css"
},
field: "DonVi_Ten",
attributes: {
class: "row_css"
},
width: "50%"
},
{
title: "Số lượng",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_DV",
template: function (data) {
if (data.SoLuong_DV == 0) {
return data.SoLuong_DV;
} else {
return '<b style="color:green;">' + OnChangeFormat(data.SoLuong_DV) + '</b>';
}
},
editor: function (container, options) {
$('<input name="' + options.field + '"/>')
.appendTo(container)
.kendoNumericTextBox({
format: 'n3',
decimals: 3
})
},
attributes: {
class: "row_css",
style: "background-color:lightyellow;"
},
width: "50%"
}
]
});
}
//#endregion
//#region Lưu phân rã
function Ham_Luu_PhanRa() {
var TongSL_PO = parseFloat(ReplaceComma($("#txt_SoLuong_Tong").text()));
var Chuoi_JSON = "";
var TongSL_DV = 0;
for (var j = 1; j < $("#grid_PhanRa tr").length; j++) {
var PO_DV_ID = parseInt($("#grid_PhanRa tr")[j].cells[0].childNodes[0].textContent);
var ClassName = $("#grid_PhanRa tr")[j].cells[2].className;
var SoLuong = parseFloat(ReplaceComma($("#grid_PhanRa tr")[j].cells[2].textContent));
if (ClassName == "row_css k-dirty-cell") {
Chuoi_JSON += "{'PO_DV_ID':" + PO_DV_ID + ",'VatTu_ID':" + VatTu_ID + ",'SoLuong':" + SoLuong + "},";
}
TongSL_DV += SoLuong;
}
Chuoi_JSON = Chuoi_JSON.replace(/^,|,$/g, '');
var check = 0;
if ((TongSL_DV).toFixed(3) > (TongSL_PO).toFixed(3)) {
check = 1;
//alert("Số lượng phân rã vượt quá số lượng tổng PO!");
$("#notification").data("kendoNotification").show({
title: "Số lượng phân rã vượt số lượng tổng PO!",
message: "Hãy nhập lại!"
}, "error");
return;
}
if (((TongSL_DV).toFixed(3) < (TongSL_PO).toFixed(3)) && ((TongSL_DV).toFixed(3) != (TongSL_PO).toFixed(3))) {
check = 1;
//alert("Chưa phân rã hết số lượng vật tư");
$("#notification").data("kendoNotification").show({
title: "Chưa phân rã hết số lượng vật tư!",
message: "Hãy nhập lại!"
}, "error");
}
if (check == 0) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'PhanRa_Luu',
gData: "[" + Chuoi_JSON + "]",
VatTu_ID: VatTu_ID,
MaDVT: MaDVT,
DonGia: ReplaceComma($("#txt_DonGia").text())
},
dataType: 'json'
});
request.done(function (msg) {
if (msg == "OK") {
//alert("Đã cập nhật phân rã!");
$("#notification").data("kendoNotification").show({
message: "Đã cập nhật phân rã!"
}, "upload-success");
$("#wd_PhanRa").data("kendoWindow").close();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
DS_BangKe_Cap2.read();
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
});
}
}
function Ham_Huy_PhanRa() {
$("#wd_PhanRa").data("kendoWindow").close();
}
//#endregion
//#region Hàm reset Upload
function uploadReset(id) {
if (id) {
//if an id is passed as a param, only reset the element's child upload controls (in case many upload widgets exist)
$("#" + id + " .k-upload-files").remove();
$("#" + id + " .k-upload-status").remove();
$("#" + id + " .k-upload.k-header").addClass("k-upload-empty");
$("#" + id + " .k-upload-button").removeClass("k-state-focused");
} else {
//reset all the upload things!
$(".k-upload-files").remove();
$(".k-upload-status").remove();
$(".k-upload.k-header").addClass("k-upload-empty");
$(".k-upload-button").removeClass("k-state-focused");
}
}
//#endregion
//#region Xuất ex PO con
function Ham_Xuat_Ex(p_MaHD) {
$("#tab_VatTu_ex").empty();
var grid = $("#tab_VatTu_ex").kendoGrid({
excel: {
allPages: true
},
excelExport: function (e) {
e.preventDefault();
var workbook = e.workbook;
detailExportPromises = [];
var masterData = e.data;
for (var rowIndex = 0; rowIndex < masterData.length; rowIndex++) {
exportChildData(BienChiTietPO.data.PO_ID, masterData[rowIndex].VatTu_ID, rowIndex);
}
$.when.apply(null, detailExportPromises)
.then(function () {
// get the export results
var detailExports = $.makeArray(arguments);
// sort by masterRowIndex
detailExports.sort(function (a, b) {
return a.masterRowIndex - b.masterRowIndex;
});
// add an empty column
workbook.sheets[0].columns.unshift({
width: 30
});
// prepend an empty cell to each row
for (var i = 0; i < workbook.sheets[0].rows.length; i++) {
workbook.sheets[0].rows[i].cells.unshift({});
}
// merge the detail export sheet rows with the master sheet rows
// loop backwards so the masterRowIndex doesn't need to be updated
for (var i = detailExports.length - 1; i >= 0; i--) {
var masterRowIndex = detailExports[i].masterRowIndex + 1; // compensate for the header row
var sheet = detailExports[i].sheet;
// prepend an empty cell to each row
for (var ci = 0; ci < sheet.rows.length; ci++) {
if (sheet.rows[ci].cells[0].value) {
sheet.rows[ci].cells.unshift({});
}
}
// insert the detail sheet rows after the master row
[].splice.apply(workbook.sheets[0].rows, [masterRowIndex + 1, 0].concat(sheet.rows));
}
// save the workbook
kendo.saveAs({
dataURI: new kendo.ooxml.Workbook(workbook).toDataURL(),
fileName: "Export.xlsx"
});
});
},
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_DonVi_SelectbyPO_ID',
PO_ID: BienChiTietPO.data.PO_ID
},
dataType: 'json',
success: function (result) {
//options.success(result);
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
filter: { field: "MaHD", operator: "eq", value: p_MaHD.trim() },
aggregate: [
{ field: "ThanhTien_PO", aggregate: "sum" }
]
}),
columns:
[
{
title: "Tên vật tư",
headerAttributes: {
class: "header_css"
},
field: "VatTu_Ten",
attributes: {
class: "row_css"
},
width: "20%"
},
{
title: "Mã vật tư",
headerAttributes: {
class: "header_css"
},
field: "MaVatTu_TD",
attributes: {
class: "row_css"
},
width: "20%"
},
{
title: "Số hợp đồng",
headerAttributes: {
class: "header_css"
},
field: "MaHD_",
groupHeaderTemplate: "#= Ham_HienThi_MaHD( value ) #",
attributes: {
class: "row_css"
}
},
{
title: "Tên nhà thầu",
headerAttributes: {
class: "header_css"
},
field: "TenNhaThau",
attributes: {
class: "row_css",
style: "font-weight:bold;color:blue;"
},
},
{
title: "Số lượng tổng PO",
headerAttributes: {
class: "header_css"
},
field: "SoLuong_PO",
template: "#= OnChangeFormat(SoLuong_PO) #",
attributes: {
class: "row_css",
style: "color:red;font-weight:bold;"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
},
{
title: "Thành tiền",
headerAttributes: {
class: "header_css"
},
field: "ThanhTien_PO",
template: "#= OnChangeFormat(ThanhTien_PO) #",
attributes: {
class: "row_css"
},
aggregates: ["sum"],
footerTemplate: "Tổng cộng: #=OnChangeFormat(sum) #",
width: "12%"
},
],
});
$("#tab_VatTu_ex").data("kendoGrid").saveAsExcel();
}
function exportChildData(key_PO_ID, key_VatTu_ID, rowIndex) {
var deferred = $.Deferred();
detailExportPromises.push(deferred);
var rows = [{
cells: [
{ value: "Đơn vị", bold: true, vAlign: "center", hAlign: "center", background: "#DDDDDD" },
{ value: "Số lượng", bold: true, vAlign: "center", hAlign: "center", background: "#DDDDDD" },
{ value: "Đơn vị tính", bold: true, vAlign: "center", hAlign: "center", background: "#DDDDDD" },
{ value: "Đơn giá", bold: true, vAlign: "center", hAlign: "center", background: "#DDDDDD" },
{ value: "Thành tiền", bold: true, vAlign: "center", hAlign: "center", background: "#DDDDDD" },
{ value: "VAT", bold: true, vAlign: "center", hAlign: "center", background: "#DDDDDD" }
]
}];
var exporter = new kendo.ExcelExporter({
dataSource: new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Con.aspx",
data: {
cmd: 'BangKe_Cap2',
PO_ID: key_PO_ID,
VatTu_ID: key_VatTu_ID,
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
}
}
}),
columns:
[
{
title: "Đơn vị",
headerAttributes: {
class: "header_css"
},
field: "TenDonVi",
attributes: {
class: "row_css"
}
},
{
title: "Số lượng",
headerAttributes: {
class: "header_css"
},
field: "SoLuong",
template: "#= OnChangeFormat(SoLuong) #",
attributes: {
class: "row_css",
style: "font-weight:bold;color:green;"
}
},
{
title: "Đơn vị tính",
headerAttributes: {
class: "header_css"
},
field: "TenDVT",
attributes: {
class: "row_css"
}
},
{
title: "Đơn giá",
headerAttributes: {
class: "header_css"
},
field: "DonGia",
template: "#= OnChangeFormat(DonGia) #",
attributes: {
class: "row_css"
}
},
{
title: "Thành tiền",
headerAttributes: {
class: "header_css"
},
field: "ThanhTien",
template: "#= OnChangeFormat(ThanhTien) #",
attributes: {
class: "row_css"
}
},
{
title: "VAT",
headerAttributes: {
class: "header_css"
},
field: "VAT",
template: "#= OnChangeFormat(VAT) #",
attributes: {
class: "row_css"
}
}
]
});
exporter.workbook().then(function (book, data) {
deferred.resolve({
masterRowIndex: rowIndex,
sheet: book.sheets[0]
});
});
}
//#endregion
//#region đóng khóa mở khóa PO
function Ham_DongKhoa(p_po_id) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'DongKhoa_PO',
PO_ID: p_po_id
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
var ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type)
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_bySoPO",
data: {
SoPO: $('#txt_search_soPO').val().trim()
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
$('#grid_PO').data('kendoGrid').setDataSource(ds);
}
else {
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
function Ham_MoKhoa(p_po_id) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'MoKhoa_PO',
PO_ID: p_po_id
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
var ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type)
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_bySoPO",
data: {
SoPO: $('#txt_search_soPO').val().trim()
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
$('#grid_PO').data('kendoGrid').setDataSource(ds);
}
else {
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
//#endregion
//#region Điều chỉnh PO
function Ham_DC_PO(p_PO_ChiTiet_ID, p_SoLuong) {
$("#wd_dieuchinh").data("kendoWindow").center().open();
$("#lb_sl_ht").text(OnChangeFormat(p_SoLuong));
PO_ChiTiet_ID = p_PO_ChiTiet_ID;
uploadReset();
Path_PO_DC = "";
$("#txt_sl_dc").data("kendoNumericTextBox").value("");
var DS_PO_DC = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'Lay_DS_PO_DC',
PO_ChiTiet_ID: p_PO_ChiTiet_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 7
});
$("#grid_DieuChinh").data("kendoGrid").setDataSource(DS_PO_DC);
}
function Ham_Luu_DC() {
var check = 0;
if ($("#txt_sl_dc").data("kendoNumericTextBox").value() == null) {
check = 1;
//alert("Chưa nhập số lượng điều chỉnh!");
$("#notification").data("kendoNotification").show({
title: "Chưa nhập số lượng điều chỉnh!",
message: "Hãy nhập số lượng điều chỉnh!"
}, "error");
return;
}
if (Path_PO_DC == "") {
check = 1;
//alert("Chưa upload tập tin văn bản điều chỉnh!");
$("#notification").data("kendoNotification").show({
title: "Chưa upload tập tin văn bản điều chỉnh!",
message: "Hãy upload tập tin văn bản điều chỉnh!"
}, "error");
return;
}
if (check == 0) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_Cha.aspx",
data: {
cmd: 'DieuChinh_PO',
PO_ChiTiet_ID: PO_ChiTiet_ID,
SoLuong_DC: $("#txt_sl_dc").data("kendoNumericTextBox").value(),
PO_HD_ID: Bien_ChiTiet_VatTu.data.PO_HD_ID,
FileVB_DC: Path_PO_DC
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
//alert("Đã điều chỉnh thành công!");
$("#notification").data("kendoNotification").show({
message: "Đã điều chỉnh thành công!"
}, "upload-success");
$("#wd_dieuchinh").data("kendoWindow").close();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
DS_BangKe_Cap2.read();
}
else {
//alert(msg[0].ErrorMessage);
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
function Ham_Dong_DC() {
$("#wd_dieuchinh").data("kendoWindow").close();
}
//#endregion
////#region xuất excel PO lớn
//function Ham_PO_Xuat_Ex() {
// $("#grid_PO_ex").data("kendoGrid").saveAsExcel();
//}
//function exportChiTiet_PO(key_PO_ID, rowIndex) {
// var deferred = $.Deferred();
// detailExportPromises.push(deferred);
// var exporter = new kendo.ExcelExporter({
// dataSource: new kendo.data.DataSource({
// transport: {
// read: function (options) {
// $.ajax({
// type: "POST",
// url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
// data: {
// cmd: 'PO_DonVi_SelectbyPO_ID',
// PO_ID: key_PO_ID
// },
// dataType: 'json',
// success: function (result) {
// //options.success(result);
// options.success(result);
// }
// });
// }
// },
// group:
// [
// {
// field: "MaHD_",
// aggregates: [
// { field: "ThanhTien_PO", aggregate: "sum" }
// ]
// }
// ]
// }),
// columns:
// [
// {
// title: "Số hợp đồng",
// headerAttributes: {
// class: "header_css"
// },
// field: "MaHD_",
// //hidden: true,
// attributes: {
// class: "row_css"
// }
// },
// {
// title: "Tên nhà thầu",
// headerAttributes: {
// class: "header_css"
// },
// field: "TenNhaThau",
// attributes: {
// class: "row_css",
// style: "font-weight:bold;color:blue;"
// },
// hidden: true
// },
// {
// title: "Vật tư",
// headerAttributes: {
// class: "header_css"
// },
// field: "VatTu_Ten",
// attributes: {
// class: "row_css",
// style: "font-weight:bold;"
// }
// },
// {
// title: "Mã vật tư",
// headerAttributes: {
// class: "header_css"
// },
// field: "MaVatTu_TD",
// attributes: {
// class: "row_css",
// style: "font-weight:bold;"
// }
// },
// {
// title: "Số lượng tổng PO",
// headerAttributes: {
// class: "header_css"
// },
// field: "SoLuong_PO",
// attributes: {
// class: "row_css",
// style: "color:red;font-weight:bold;"
// }
// },
// {
// title: "Đơn giá",
// headerAttributes: {
// class: "header_css"
// },
// field: "DonGia",
// attributes: {
// class: "row_css"
// }
// },
// {
// title: "Đơn vị tính",
// headerAttributes: {
// class: "header_css"
// },
// field: "TenDVT",
// attributes: {
// class: "row_css"
// }
// },
// {
// title: "Thành tiền",
// headerAttributes: {
// class: "header_css"
// },
// field: "ThanhTien_PO",
// attributes: {
// class: "row_css"
// },
// aggregates: ["sum"],
// //groupFooterTemplate: "Tổng cộng: #=OnChangeFormat(sum) #"
// groupFooterTemplate: "#=OnChangeFormat(sum) #"
// }
// ]
// });
// exporter.workbook().then(function (book, data) {
// deferred.resolve({
// masterRowIndex: rowIndex,
// sheet: book.sheets[0]
// });
// });
//}
////#endregion
//#region xuất thư đặt hàng
function Ham_Xuat_TDH(p_MaHD) {
window.open('rp_thudathang.aspx?PO_ID=' + BienChiTietPO.data.PO_ID + '&MaHD=' + p_MaHD + '', '_blank');
}
//#endregion
//#region vật tư dây nhảy
function Ham_TaoMoiVatTuDayNhay() {
$("#wd_List_Option_DayNhay").data("kendoWindow").center().open();
}
function Ham_Chon_TaoMoiVatTuDayNhay() {
if ($("#rdo_sl_daynhay").is(":checked")) {
Ham_TaoMoiVatTu_DayNhay();
} else {
Ham_TaoMoiVatTuDayNhay_HD();
}
}
function Ham_Huy_ChonTaoMoiVatTuDayNhay() {
$("#wd_List_Option_DayNhay").data("kendoWindow").close();
}
function Ham_TaoMoiVatTu_DayNhay() {
$("#wd_TaoMoi_VT_DayNhay").data("kendoWindow").center().open();
$("#grid_daynhay").data("kendoGrid").setDataSource(DS_VT_DayNhay);
$("#txt_search_sohd_daynhay").data("kendoComboBox").setDataSource(DS_SoHD);
$("#txt_search_sohd_daynhay").data("kendoComboBox").text("");
$("#grid_daynhay_po").data("kendoGrid").setDataSource(
new kendo.data.DataSource({
data: []
})
);
}
function Ham_TinhDonGia() {
var grid_daynhay = $("#grid_daynhay").data("kendoGrid");
var selectedItem = grid_daynhay.dataItem(grid_daynhay.select());
if (selectedItem == null) {
$("#notification").data("kendoNotification").show({
title: "Chưa chọn vật tư dây nhảy!",
message: "Hãy chọn vật tư dây nhảy!"
}, "error");
return;
}
if ($("#txt_search_sohd_daynhay").data("kendoComboBox").select() == -1) {
$("#notification").data("kendoNotification").show({
title: "Chưa chọn hợp đồng!",
message: "Hãy chọn hợp đồng!"
}, "error");
return;
}
var ds = new kendo.data.DataSource({
transport: {
read: function (options) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_DM_VT_DayNhay.aspx",
data: {
cmd: 'TinhGia_VatTuDayNhay',
HopDong_ID: $("#txt_search_sohd_daynhay").data("kendoComboBox").value(),
VatTu_DayNhay_ID: selectedItem.VatTu_ID
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].DonGia_DayNhay == null) {
if (msg[0].ErrorMessage == "Chua_Du_Nguyen_Lieu") {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: "Hợp đồng chưa đủ nguyên liệu!"
}, "error");
$("#grid_daynhay_po").data("kendoGrid").setDataSource(
new kendo.data.DataSource({
data: []
})
);
}
else {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: "Vật tư chưa áp được đơn giá!"
}, "error");
$("#grid_daynhay_po").data("kendoGrid").setDataSource(
new kendo.data.DataSource({
data: []
})
);
}
}
else {
options.success(msg);
}
});
request.fail(function (jqXHR, textStatus) {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: textStatus
}, "error");
});
},
parameterMap: function (options, operation) {
return { models: kendo.stringify(options.models) };
}
},
schema: {
model: {
fields: {
SoLuong_KhaDung: { editable: false, type: "number" },
SoLuong_PO: {
type: "number",
validation: {
NameValidation: function (input) {
var grid = $("#grid_daynhay_po").data("kendoGrid");
var tr = $(input).closest('tr');
var dataRow = grid.dataItem(tr);
var SL_PO = $(input).val();
var SL_KhaDung = dataRow.SoLuongKhaDung_DayNhay;
if (input.is("[name='SoLuong_PO']") && input.val() == "") {
input.attr("data-NameValidation-msg", "Chưa nhập số lượng!");
return false;
}
if (input.is("[name='SoLuong_PO']") && SL_PO > SL_KhaDung) {
input.attr("data-NameValidation-msg", "Số lượng PO vượt quá số lượng khả dụng!");
return false;
}
return true;
}
}
}
}
}
}
});
$("#grid_daynhay_po").data("kendoGrid").setDataSource(ds);
}
function Ham_Luu_VTDN_PO() {
var DS_Grid = $("#grid_daynhay_po").data("kendoGrid").dataSource.data();
var p_HopDong_ID = DS_Grid[0].HopDong_ID;
var p_VatTu_ID = DS_Grid[0].VatTu_ID;
var p_SoLuong_PO = DS_Grid[0].SoLuong_PO;
if (p_SoLuong_PO == 0) {
$("#notification").data("kendoNotification").show({
title: "Chưa nhập số lượng PO!",
message: "Hãy nhập số lượng PO!"
}, "error");
return;
}
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_HopDong_CT_Create',
PO_ID: BienChiTietPO.data.PO_ID,
HopDong_ID: p_HopDong_ID,
VatTu_ID: p_VatTu_ID,
SoLuong_PO: p_SoLuong_PO
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
$("#notification").data("kendoNotification").show({
message: "Đã thêm thành công vật tư!"
}, "upload-success");
$("#wd_TaoMoi_VT_DayNhay").data("kendoWindow").close();
$("#wd_List_Option_DayNhay").data("kendoWindow").close();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
DS_VatTu.read();
}
else {
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: textStatus
}, "error");
});
}
//////////////Vượt khả dụng \\\\\\\\\\\\\\\\\\\\\\\\
function Ham_TaoMoiVatTuDayNhay_HD() {
$("#wd_ChonVatTuDayNhay_Vuot").data("kendoWindow").center().open();
$("#grid_daynhay_hd").data("kendoGrid").setDataSource(DS_VT_DayNhay);
$("#txt_search_sohd_daynhay_hd").data("kendoComboBox").setDataSource(DS_SoHD);
$("#txt_search_sohd_daynhay_hd").data("kendoComboBox").text("");
$("#grid_daynhay_po_hd").data("kendoGrid").setDataSource(
new kendo.data.DataSource({
data: []
})
);
$("#div_GTHD_dn").hide();
}
function Ham_TinhDonGia_hd() {
var grid_daynhay_hd = $("#grid_daynhay_hd").data("kendoGrid");
var selectedItem = grid_daynhay_hd.dataItem(grid_daynhay_hd.select());
if (selectedItem == null) {
$("#notification").data("kendoNotification").show({
title: "Chưa chọn vật tư dây nhảy!",
message: "Hãy chọn vật tư dây nhảy!"
}, "error");
return;
}
if ($("#txt_search_sohd_daynhay_hd").data("kendoComboBox").select() == -1) {
$("#notification").data("kendoNotification").show({
title: "Chưa chọn hợp đồng!",
message: "Hãy chọn hợp đồng!"
}, "error");
return;
}
var ds = new kendo.data.DataSource({
transport: {
read: function (options) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_DM_VT_DayNhay.aspx",
data: {
cmd: 'TinhGia_VatTuDayNhay_Vuot',
HopDong_ID: $("#txt_search_sohd_daynhay_hd").data("kendoComboBox").value(),
VatTu_DayNhay_ID: selectedItem.VatTu_ID
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].DonGia_DayNhay == null) {
if (msg[0].ErrorMessage == "Chua_Du_Nguyen_Lieu") {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: "Hợp đồng chưa đủ nguyên liệu!"
}, "error");
$("#grid_daynhay_po_hd").data("kendoGrid").setDataSource(
new kendo.data.DataSource({
data: []
})
);
$("#div_GTHD_dn").hide();
}
else {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: "Vật tư chưa áp được đơn giá!"
}, "error");
$("#grid_daynhay_po_hd").data("kendoGrid").setDataSource(
new kendo.data.DataSource({
data: []
})
);
$("#div_GTHD_dn").hide();
}
}
else {
options.success(msg);
$("#lb_GTHD_ConLai_dn").text(OnChangeFormat(msg[0].GiaTriConLai_HD));
$("#div_GTHD_dn").show();
}
});
request.fail(function (jqXHR, textStatus) {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: textStatus
}, "error");
$("#div_GTHD_dn").hide();
});
},
parameterMap: function (options, operation) {
return { models: kendo.stringify(options.models) };
}
},
schema: {
model: {
fields: {
SoLuong_KhaDung: { editable: false, type: "number" },
SoLuong_PO: {
type: "number",
validation: {
NameValidation: function (input) {
var grid = $("#grid_daynhay_po_hd").data("kendoGrid");
var tr = $(input).closest('tr');
var dataRow = grid.dataItem(tr);
var SL_PO = $(input).val();
var SL_KhaDung = dataRow.SoLuongKhaDung_DayNhay;
if (input.is("[name='SoLuong_PO']") && input.val() == "") {
input.attr("data-NameValidation-msg", "Chưa nhập số lượng!");
return false;
}
return true;
}
}
}
}
}
}
});
$("#grid_daynhay_po_hd").data("kendoGrid").setDataSource(ds);
}
function Ham_Luu_VTDN_PO_hd() {
var DS_Grid_Vuot = $("#grid_daynhay_po_hd").data("kendoGrid").dataSource.data();
var GiaTriHopDong_ConLai = ReplaceComma($("#lb_GTHD_ConLai_dn").text());
var TongSoLuong = 0;
for (var j = 0; j < DS_Grid_Vuot.length; j++) {
var p_soluong = DS_Grid_Vuot[j].SoLuong_PO == null ? 0 : DS_Grid_Vuot[j].SoLuong_PO;
TongSoLuong += DS_Grid_Vuot[j].DonGia_DayNhay * parseFloat(ReplaceComma('' + p_soluong + ''));
}
if (parseFloat(TongSoLuong) > parseFloat(GiaTriHopDong_ConLai)) {
alert("Vượt quá giá trị hợp đồng!");
} else {
for (var j = 0; j < DS_Grid_Vuot.length; j++) {
var p_HopDong_ID = DS_Grid_Vuot[j].HopDong_ID;
var p_VatTu_ID = DS_Grid_Vuot[j].VatTu_ID;
var p_SoLuong_PO = DS_Grid_Vuot[j].SoLuong_PO == null ? 0 : DS_Grid_Vuot[j].SoLuong_PO;
if (p_SoLuong_PO != 0) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_PO_HopDong_CT.aspx",
data: {
cmd: 'PO_HopDong_CT_Create',
PO_ID: BienChiTietPO.data.PO_ID,
HopDong_ID: p_HopDong_ID,
VatTu_ID: p_VatTu_ID,
SoLuong_PO: p_SoLuong_PO
},
dataType: 'json'
});
}
}
$("#notification").data("kendoNotification").show({
message: "Đã thêm thành công vật tư!"
}, "upload-success");
$("#wd_ChonVatTuDayNhay_Vuot").data("kendoWindow").close();
$("#wd_List_Option_DayNhay").data("kendoWindow").close();
BienChiTietPO.detailRow.find("#tab_VatTu").data('kendoGrid').dataSource.read();
DS_VatTu.read();
DS_PO.read();
}
}
function filterPO() {
var ds;
if ($('#txt_search_soPO').val().trim() !== '') {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type)
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO_bySoPO",
data: {
SoPO: $('#txt_search_soPO').val().trim()
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
else {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
e.response.d = JSON.parse(e.response.d);
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'PO_ID',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_PO_Cha.aspx/Lay_DS_PO"
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO").data("kendoGrid").setDataSource(ds) : $("#grid_PO").data("kendoGrid").setDataSource(DS_PO_TD);
//$("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#grid_PO_ex").data("kendoGrid").setDataSource(ds) : $("#grid_PO_ex").data("kendoGrid").setDataSource(DS_PO_TD);
}
function filterVatTuHopDong() {
var ds;
if ($('#txtSearchValue_VT_Thuong').val().trim() !== '') {
var value_cbo = $('#cboSearchBy_VT_Thuong').data('kendoDropDownList').text();
if (value_cbo === 'Số hợp đồng') {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type) {
e.response.d = JSON.parse(e.response.d);
}
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'STT',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_HopDong_CT.aspx/HopDong_CT_SelectAll_HD",
data: {
MaHD: $('#txtSearchValue_VT_Thuong').val().trim()
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
else if (value_cbo === 'Tên vật tư') {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type) {
e.response.d = JSON.parse(e.response.d);
}
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'STT',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_HopDong_CT.aspx/HopDong_CT_SelectAll_TenVT",
data: {
TenVT: $('#txtSearchValue_VT_Thuong').val().trim()
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
else if (value_cbo === 'Mã vật tư') {
ds = new kendo.data.DataSource({
requestEnd: function (e) {
if (e.type) {
e.response.d = JSON.parse(e.response.d);
}
},
schema: {
data: 'd.Data',
total: 'd.Total[0].Total'
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
sort: {
field: 'STT',
dir: 'desc'
},
transport: {
read: {
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: "assets/ajax/Ajax_HopDong_CT.aspx/HopDong_CT_SelectAll_MaVT",
data: {
MaVT: $('#txtSearchValue_VT_Thuong').val().trim()
}
},
parameterMap: function (options, operation) {
return kendo.stringify(options);
}
}
});
}
}
else {
//ds = new kendo.data.DataSource({
// requestEnd: function (e) {
// e.response.d = JSON.parse(e.response.d);
// },
// schema: {
// data: 'd.Data',
// total: 'd.Total[0].Total'
// },
// pageSize: 5,
// serverPaging: true,
// serverSorting: true,
// sort: {
// field: 'STT',
// dir: 'desc'
// },
// transport: {
// read: {
// contentType: "application/json; charset=utf-8",
// dataType: 'json',
// type: 'POST',
// url: "assets/ajax/Ajax_HopDong_CT.aspx/HopDong_CT_SelectAll"
// },
// parameterMap: function (options, operation) {
// return kendo.stringify(options);
// }
// }
//});
ds = new kendo.data.DataSource({
data: []
});
}
$("#grid_VatTu").data("kendoGrid").setDataSource(ds);
}
//#endregion
//#region Tạm ứng
function Ham_TamUng(p_PO_NhaThau_ID, p_NhaThau_ID, p_TongTienThanhToan) {
var ds_abc = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_TamUng.aspx",
data: {
cmd: 'Get_NhaThau_LienDanh',
NhaThau_ID: p_NhaThau_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
}
});
$("#grid_thanhvien").data("kendoGrid").setDataSource(ds_abc);
$("#hf_PO_NhaThau_ID").val(p_PO_NhaThau_ID);
$("#hf_TamUng_ID").val("");
$("#txt_TyLe_TamUng").data("kendoNumericTextBox").value("");
$("#txt_SoVB_BaoLanh").val("");
$("#txt_NgayVB_BaoLanh").val("");
$("#txt_GT_TamUng").val("");
$("#txt_SoVB_XN_PO").val("");
$("#txt_NgayVB_XN_PO").val("");
$("#lb_TamUng_GT_PO").text(OnChangeFormat(p_TongTienThanhToan));
$("#wd_TamUng").data("kendoWindow").center().open();
}
function Ham_Luu_TamUng() {
if ($("#txt_GT_TamUng").val().trim() != "" && $("#txt_GT_TamUng").val().trim() != "0") {
var TongTienThanhVien = 0;
for (var i = 0; i < $("#grid_thanhvien").data("kendoGrid").dataSource.view().length; i++) {
TongTienThanhVien += $("#grid_thanhvien").data("kendoGrid").dataSource.view()[i].GiaTri_DeNghi;
}
if (TongTienThanhVien != ReplaceComma($("#txt_GT_TamUng").val().trim())) {
$("#notification").data("kendoNotification").show({
title: "Giá trị tạm ứng thành viên chưa đúng!",
message: ""
}, "error");
return;
}
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_TamUng.aspx",
data: {
cmd: 'CapNhat_TamUng',
TamUng_ID: $("#hf_TamUng_ID").val(),
PO_NhaThau_ID: $("#hf_PO_NhaThau_ID").val(),
SoVB_BaoLanh: $("#txt_SoVB_BaoLanh").val().trim(),
NgayVB_BaoLanh: $("#txt_NgayVB_BaoLanh").val().trim(),
gData: JSON.stringify($("#grid_thanhvien").data("kendoGrid").dataSource.view()),
GiaTri_PO: ReplaceComma($("#lb_TamUng_GT_PO").text().trim()),
GiaTri_DeNghi: ReplaceComma($("#txt_GT_TamUng").val().trim()),
SoVB_XacNhan_PO: $("#txt_SoVB_XN_PO").val().trim(),
NgayVB_XacNhan_PO: $("#txt_NgayVB_XN_PO").val().trim()
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
$("#notification").data("kendoNotification").show({
message: "Đã cập nhật thành công!"
}, "upload-success");
$("#wd_TamUng").data("kendoWindow").close();
DS_TamUng.read();
}
else {
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: textStatus
}, "error");
});
}
}
function Ham_Sua_TamUng(p_TamUng_ID, p_SoVB_BaoLanh, p_NgayVB_BaoLanh_f, p_GiaTri_DeNghi, p_GiaTri_PO, p_SoVB_XacNhan_HieuLuc_PO, p_NgayVB_XacNhan_HieuLuc_PO) {
$("#txt_SoVB_BaoLanh").val(p_SoVB_BaoLanh);
$("#txt_NgayVB_BaoLanh").val(p_NgayVB_BaoLanh_f == "null" ? "" : p_NgayVB_BaoLanh_f);
$("#lb_TamUng_GT_PO").text(OnChangeFormat(p_GiaTri_PO));
$("#txt_GT_TamUng").val(OnChangeFormat(p_GiaTri_DeNghi));
$("#txt_SoVB_XN_PO").val(OnChangeFormat(p_SoVB_XacNhan_HieuLuc_PO));
$("#txt_NgayVB_XN_PO").val(p_NgayVB_XacNhan_HieuLuc_PO);
$("#hf_TamUng_ID").val(p_TamUng_ID);
var ds_abc = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
type: "POST",
url: "assets/ajax/Ajax_TamUng.aspx",
data: {
cmd: 'HienThi_TamUng_ThanhVien',
TamUng_ID: p_TamUng_ID
},
dataType: 'json',
success: function (result) {
if (result == "err401") {
alert("Phiên đã hết hạn!Vui lòng đăng nhập lại.");
window.location.href = "DangNhap.aspx?p=PO.aspx";
}
else {
options.success(result);
}
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
}
});
$("#grid_thanhvien").data("kendoGrid").setDataSource(ds_abc);
$("#wd_TamUng").data("kendoWindow").center().open();
}
function Ham_Xoa_TamUng(p_TamUng_ID) {
if (confirm("Bạn có chắc muốn xóa lần tạm ứng này không?")) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_TamUng.aspx",
data: {
cmd: 'Xoa_TamUng',
TamUng_ID: p_TamUng_ID
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
$("#notification").data("kendoNotification").show({
message: "Đã cập nhật thành công!"
}, "upload-success");
DS_TamUng.read();
}
else {
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
$("#notification").data("kendoNotification").show({
title: "Lỗi",
message: textStatus
}, "error");
});
}
}
//#region đóng khóa mở khóa Tạm ứng
function Ham_DongKhoa_TamUng(p_PO_NhaThau_ID) {
$("#hf_PO_NhaThau_ID_khoa").val(p_PO_NhaThau_ID);
$("#txt_NgayChuyen_KT").val("");
$("#txt_HS_TW").val("");
$("#wd_Khoa_TamUng").data().kendoWindow.center().open();
}
function Ham_Luu_KhoaTamUng() {
if ($("#txt_HS_TW").val() == "") {
$("#notification").data("kendoNotification").show({
title: "Chưa nhập hồ sơ tạm ứng!",
message: "Hãy nhập hồ sơ tạm ứng!"
}, "error");
return;
}
if ($("#txt_NgayChuyen_KT").val() == "") {
$("#notification").data("kendoNotification").show({
title: "Chưa nhập ngày chuyển kế toán!",
message: ""
}, "error");
return;
}
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_TamUng.aspx",
data: {
cmd: 'DongKhoa_TamUng',
PO_NhaThau_ID: $("#hf_PO_NhaThau_ID_khoa").val(),
HS_TW: $("#txt_HS_TW").val().trim(),
NgayChuyen_KeToan: $("#txt_NgayChuyen_KT").val()
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
$("#wd_Khoa_TamUng").data().kendoWindow.close();
DS_TamUng.read();
DS_PO_Con.read();
}
else {
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
function Ham_MoKhoa_TamUng(p_PO_NhaThau_ID) {
if (confirm("Bạn có chắc mở khóa? Chương trình sẽ xóa số hồ sơ tạm ứng và ngày chuyển kế toán!")) {
var request = $.ajax({
type: "POST",
url: "assets/ajax/Ajax_TamUng.aspx",
data: {
cmd: 'MoKhoa_TamUng',
PO_NhaThau_ID: p_PO_NhaThau_ID
},
dataType: 'json'
});
request.done(function (msg) {
if (msg[0].ErrorMessage == null) {
DS_TamUng.read();
DS_PO_Con.read();
}
else {
$("#notification").data("kendoNotification").show({
title: msg[0].ErrorMessage,
message: "Hãy thao tác lại!"
}, "error");
}
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
}
//#endregion
function Ham_Ex_TamUng(p_TamUng_ID) {
var request = $.ajax({
type: "POST",
url: "ExportEx.aspx",
data: {
cmd: 'TamUng',
TamUng_ID: p_TamUng_ID
},
dataType: 'json'
});
request.done(function (msg) {
$('#id_xuat_ex').attr("href", msg.FilePath);
($('#id_xuat_ex')[0]).click();
});
request.fail(function (jqXHR, textStatus) {
//alert("Request failed: " + textStatus);
$("#notification").data("kendoNotification").show({
title: "Request failed: " + textStatus,
message: "Hãy thao tác lại!"
}, "error");
});
}
//#endregion
|
function update()
{
$.get("scripts/server/view/get_current_reading.php", function (data)
{
//alert(data.device);
$('#textDevice').text(data.device);
$('#textVoltage').text(data.voltage + 'V');
$('#textInternal').text(data.internal + '\xB0C Internal');
$('#textExternal').text(data.external + '\xB0C External');
$('#textLight').text(data.light);
}, 'json');
//alert('Checked');
};
$(document).ready(function ()
{
//$.get("scripts/server/view/get_current_reading.php", function (data)
//{
// //alert(data.device);
// $('#textDevice').text(data.device);
// $('#textVoltage').text(data.voltage + 'V');
// $('#textInternal').text(data.internal + '\xB0C Internal');
// $('#textExternal').text(data.external + '\xB0C External');
// $('#textLight').text(data.light);
//}, 'json');
update();
setInterval(update, 3000);
});
|
import React from 'react';
export function AuthInputLabelComponent ({ error }) {
return error ? <p className = "validation-error">{ error }</p> : null ;
}
|
import React, { Component } from 'react';
import Axios from 'axios';
import {connect} from 'react-redux'
// import noImage from './../../assets/no_image.jpg';
// import './Form.css';
class Form extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
img: '',
content: ''
};
this.submit = this.submit.bind(this);
}
async submit() {
const id = this.props.id
console.log(id)
const {title, img, content} = this.state
await Axios.post(`/api/post/${id}`, {title, img, content})
this.props.history.push('/dashboard')
}
render() {
let imgSrc = this.state.img;
return (
<div className='Form content_box'>
Form
<h2 className='title'>New Post</h2>
<div className='form_input_box'>
<p>Title:</p>
<input value={this.state.title} onChange={e => this.setState({ title: e.target.value })} />
</div>
<div className='form_img_prev' style={{ backgroundImage: `url('${imgSrc}')` }} alt='preview' ></div>
<div className='form_input_box'>
<p>Image URL:</p>
<input value={this.state.img} onChange={e => this.setState({ img: e.target.value })} />
</div>
<div className='form_text_box'>
<p>Content:</p>
<textarea value={this.state.content} onChange={e => this.setState({ content: e.target.value })} />
</div>
<button onClick={this.submit} className='dark_button form_button'>Post</button>
</div>
);
}
}
function mapStateToProps(store) {
return {
id: store.id
}
}
export default connect(mapStateToProps)(Form)
|
$(document).ready(function() {
let input = document.querySelector('input.form-control[name="username"]');
input.onkeyup = function() {
$.get('/check', { username: input.value }, function(data) {
if (data === true) {
input.style.borderColor = "green";
}
else if (data === false) {
input.style.borderColor = "red";
document.querySelector('form').onsubmit = function() {
return false;
};
}
});
};
});
|
window.addEventListener("load", () => document.querySelector("#Display").textContent = "");
window.addEventListener("keydown", function(event){ handleKeyDown(event); });
const operators = ["+", "-", "*", "/"];
const numpad = ["7", "8", "9", "4", "5", "6", "1", "2", "3", "0"];
const auxiliary = ["C", "<-", "MS", "MR"];
const numberButtons = 10;
const numpadDiv = document.querySelector("#NumpadDiv");
for(var i = 0 ; i < numberButtons ; i++){
const button = document.createElement("button");
button.textContent = numpad[i];
button.addEventListener("click", function(){ handleNumberClick(button.textContent); });
numpadDiv.appendChild(button);
}
const operatorButtons = 4;
const operationsDiv = document.querySelector("#OperationsDiv");
for(var i = 0 ; i < operatorButtons ; i++){
const button = document.createElement("button");
button.textContent = operators[i];
button.addEventListener("click", function(){ handleOperatorClick(button.textContent); });
operationsDiv.appendChild(button);
}
const auxiliaryButtons = 4;
const auxiliaryDiv = document.querySelector("#AuxiliaryDiv");
for(var i = 0 ; i < auxiliaryButtons ; i++){
const button = document.createElement("button");
button.textContent = auxiliary[i];
button.addEventListener("click", function(){ handleAuxiliaryClick(button.textContent); });
auxiliaryDiv.appendChild(button);
}
const period = document.createElement("button");
period.textContent = ".";
period.addEventListener("click", function(){ handleDecimal(); });
const equals = document.createElement("button");
equals.textContent = "=";
equals.addEventListener("click", function(){ evaluateExpression(); });
numpadDiv.appendChild(period);
numpadDiv.appendChild(equals);
|
const { query } = require("../index");
sqlDrop = "DROP TABLE games;"
async function dropTable() {
const result = await query(sqlDrop);
console.log(result);
}
dropTable();
|
import banner from '../assets/images/banner.jpg';
export class experienceBanner extends HTMLElement {
constructor() {
super();
this.template();
}
get banner() {
return this.getAttribute('banner') || banner;
}
get link() {
return this.getAttribute('link') || '#';
}
get hide() { // ซ่อน Banner
return this.getAttribute('hide') || '';
}
template() {
this.innerHTML = `
<div class="exp-banner ${this.hide}">
<a href="${this.link}" target="_blank">
<img src="${this.banner}">
</a>
</div>
`;
}
}
|
import { HtmlView } from 'gml-html';
import template from './template.html';
import * as style from './style.scss';
export default async function ({ system, locale }) {
const view = HtmlView(template, style, locale.get());
view.style();
rx.connect
.partial({
loading: () => system.store.loading
})
.subscribe(function ({loading}) {
view.get('progress').style.opacity = loading ? 1 : 0;
});
view.setTitle = function (title) {
view.get('title').innerHTML = title;
};
return view;
}
|
(() =>{
const BUTTONS = document.querySelectorAll("button")
const COUNTER = document.querySelector("#counter")
BUTTONS.forEach((button) =>{
const _thisButton = button
button.addEventListener('click',() =>{
// Prepare all data
let counterCurrentValue = returnIntCounterValue()
const mathSign = _thisButton.dataset.value[0] // input: '+10' output: '+'
const value = parseInt(_thisButton.dataset.value.slice(1)) // input: '+10' output: 10
if (isNaN(value)) return NaN // rise error
// Update counter value
if (mathSign === '+') COUNTER.textContent = counterCurrentValue + value
else if (mathSign === '-') COUNTER.textContent = counterCurrentValue - value
// Update counter style
counterCurrentValue = returnIntCounterValue()
if (counterCurrentValue > 0) COUNTER.style.color = 'green'
else if (counterCurrentValue < 0) COUNTER.style.color = 'red'
else COUNTER.style.color = 'inherit'
})
})
function returnIntCounterValue(){
const counterValue = parseInt(COUNTER.textContent)
if (isNaN(counterValue)) return NaN // rise error
return counterValue
}
})()
|
import React, { Component } from 'react'
import { Text, View, StyleSheet } from 'react-native'
import { Form, Item, Input, Label, Spinner } from 'native-base';
import { connect } from 'react-redux'
import { addingUserInCircle } from '../../Config/Firebase/Firebase'
import CustomHeader from '../../Components/CustomHeader/CustomHeader'
import CustomButton from '../../Components/CustomButton/CustomButton'
class JoinCircle extends Component {
constructor(){
super()
this.state = {
circleCode : '',
isLoading : false
}
}
async addInCircle(){
const { circleCode } = this.state
const { userUid } = this.props.userObj
this.setState({isLoading : true})
if(circleCode === ''){
alert('Write Your Circle Code')
this.setState({isLoading : false})
return
}
try{
const result = await addingUserInCircle(circleCode , userUid)
console.log('REsult' , result);
this.setState({isLoading : false})
alert(result)
}
catch(e){
this.setState({isLoading : false})
alert(e)
}
}
render() {
const { circleCode, isLoading } = this.state
return (
<View style={{flex : 1}}>
<CustomHeader title={'Join Circle'} backArrow />
{isLoading &&
<View style={styles.loaderDiv}>
<Spinner color='blue' />
</View>
}
<View style={styles.container}>
<Text style={styles.text}>Please , enter valid invite code</Text>
<Form>
<Item floatingLabel style={{ width: '60%' }}>
<Label>Circle Code</Label>
<Input
value={circleCode}
onChange={(e) => { this.setState({ circleCode: e.nativeEvent.text }) }}
/>
</Item>
</Form>
<CustomButton
title={'Submit'}
buttonStyle={styles.submitBtn}
textStyle={styles.submitBtnText}
onPress = {()=>{this.addInCircle()}}
/>
<Text style={styles.note}>Ask circel code to circel admin</Text>
</View>
</View>
)
}
}
const mapDispatchToProps = () => {
return {}
}
const mapStateToProps = (state) => {
return {
userObj : state.authReducer.user
}
}
export default connect(mapStateToProps , mapDispatchToProps)(JoinCircle)
const styles = StyleSheet.create({
container : {
flex : 1,
alignItems : 'center',
justifyContent : 'center',
opacity : 0.6
},
text : {
fontSize : 22,
textAlign : 'center',
color : '#353b48',
fontWeight : '600'
},
submitBtn : {
backgroundColor : '#eb2f06',
borderWidth : 2,
borderRadius : 25,
width :'60%',
borderColor : '#eb2f06',
marginTop : 15
},
submitBtnText : {
color : '#fff',
padding : 8,
fontSize : 19,
textAlign : 'center'
},
note : {
color : '#353b48',
textAlign : 'center',
fontSize : 19,
marginTop : 15,
fontWeight : '600'
},
loaderDiv : {
position : 'absolute',
height : '100%',
width : '100%',
backgroundColor : '#fff',
opacity : 0.6,
alignItems : 'center',
justifyContent : 'center',
zIndex : 100
},
})
|
'use strict';
module.exports = {
SECRET: 'keepitsecret',
AUTH_COOKIE_NAME: 'st',
AUTH_TOKEN_EXPIRY: 3600, // 1 hour
AUTH_COOKIE_MAX_AGE: '3600000', // 1 hour
SESSION_COOKIE_NAME: 'stp',
SESSION_COOKIE_MAX_AGE: '31536000000', // 365 days (in milliseconds)
};
|
var path = require('path');
var fs = require('fs');
var defaults = require('./default');
var config = require('../util/config.js').configData;
/**
* redirect to /view/
*/
function doGet(request, response, url) {
defaults.found(response, '/view/');
};
exports.doGet = doGet;
|
// function problem1(str){
// for (let i = 0; i < str.length; i++) {
// console.log(`str[${i}] -> ${str[i]}`);
// }
// }
// function problem2(arr){
// console.log(arr.reverse().map(a => a.split('').reverse().join('')).join(''));
// }
//problem2(['I', 'am', 'student']);
// function problem3(a,b){
// let count = 0;
// let pos = b.indexOf(a);
//
// while (pos > -1) {
// ++count;
// pos = b.indexOf(a, ++pos);
// }
//
// console.log(count); //
// }
// function problem4(input){
// // let pattern = /[(].+?[)]/g;
// //
// // let matches = input.match(pattern);
// // console.log(matches.map(str => str.substring(1, str.length-1)).join(', '));
//
// let arr = [];
//
// let myRegexp = /[(].+?[)]/g;
// let match = myRegexp.exec(input);
// while (match != null) {
// // matched text: match[0]
// // match start: match.index
// // capturing group n: match[n]
// // console.log(match[0]);
// arr.push(match[0].substring(1, match[0].length-1));
// match = myRegexp.exec(input);
// }
//
// console.log(arr.join(', '))
// }
//problem4('Rakiya (Bulgarian brandy) is self-made liquor (alcoholic drink)');
// function problem5(arr){
// let megata = arr.map(str => str.split('|').filter(e => e));
//
// let cities = [];
//
// let totalIncome = 0;
//
// for (let i = 0; i < megata.length; i++) {
// let city = megata[i][0].trim();
//
// let income = Number(megata[i][1].trim());
// totalIncome+= income;
//
// cities.push(city);
// }
//
// console.log(cities.join(', '));
// console.log(totalIncome);
// }
// problem5(['| Sofia | 300',
// '| Veliko Tarnovo | 500',
// '| Yambol | 275']
//);
// function problem6(purchasesInput){
// let purchases = [];
// let sum = 0;
//
// for (let i = 0; i < purchasesInput.length; i++) {
// if(i%2 === 0){ //product
// let product = purchasesInput[i];
// purchases.push(product);
// }else{
// let price = Number(purchasesInput[i]);
//
// sum+=price;
// }
// }
//
// console.log(`You purchased ${purchases.join(', ')} for a total sum of ${sum}`);
// }
// function problem7(emailsArr){
//
// let extractedUsernames = [];
//
// for (let i = 0; i < emailsArr.length; i++) {
// let currentEmail = emailsArr[i];
//
// //let emailArgs = currentEmail.replace('@', '|').replace('.', '|').split('|');//.filter(e => e);
//
// let emailArgs = currentEmail.split('@');//.filter(e => e);
//
// let username = emailArgs[0];
//
// let domains = emailArgs[1].split('.');
//
// let charsAfterDots = "";
//
// for (let j = 0; j < domains.length; j++) {
// charsAfterDots += domains[j][0];
// }
//
// username = username + '.' + charsAfterDots;
// extractedUsernames.push(username);
// }
//
// console.log(extractedUsernames.join(', '));
// }
//problem7(['peshoo@gmail.com', 'todor_43@mail.dir.bg', 'foo@bar.com']);
// function problem8(text, words){
// for (let i = 0; i < words.length; i++) {
// let currentWord = words[i];
// let currentLength = currentWord.length;
//
// let pattern = new RegExp(currentWord, 'g');
// let replacement = '-'.repeat(currentLength);
//
// text = text.replace(pattern, replacement);
// }
//
// console.log(text);
// }
//problem8('roses are red, violets are blue', [', violets are', 'red']);
// function problem9(arr){
// let text = '<ul>\n';
//
// let symbolsReplacement = {
// '<' : '<',
// '>' : '>',
// '&' : '&',
// '"' : '"'
// };
//
// for (let i = 0; i < arr.length; i++) {
// let currentRow = ' <li>';
//
// let currentInput = arr[i];
// let replaced = replaceAllv2(currentInput, '&', symbolsReplacement['&']);
// replaced = replaceAllv2(replaced, '<', symbolsReplacement['<']);
// replaced = replaceAllv2(replaced, '>', symbolsReplacement['>']);
// replaced = replaceAllv2(replaced, '"', symbolsReplacement['"']);
//
// currentRow += replaced;
//
// currentRow += '</li>\n';
//
// text += currentRow;
// }
//
// text += '</ul>';
//
// console.log(text);
//
// function replaceAllv2(text, search, replacement) {
// return text.replace(new RegExp(search, 'g'), replacement);
// }
// // String.prototype.replaceAll = function(search, replacement) {
// // let target = this;
// // return target.replace(new RegExp(search, 'g'), replacement);
// // }
// }
// problem9(['<b>unescaped text</b>', 'normal text']);
// function problem10(input){
// let matches = input.match(/\w+/g);
//
// console.log(matches.join('|'));
// }
// problem10('A Regular Expression needs to have the global flag in order to match all occurrences in the text');
// function problem11(email) {
// let regex = RegExp('^[a-zA-Z0-9]+@[a-z]+\\.[a-z]+$', 'g');
// //let excuseme = /^[a-zA-Z0-9]+@[a-z]+\.[a-z]+$/;
//
// let isEmailValid = regex.test(email);
// if(isEmailValid){
// console.log('Valid');
// }else{
// console.log('Invalid');
// }
// }
//problem11('valid@email.bg');
// function problem12(str) {
// //first the commas
//
// //then everything else
// // (spaces) ; . ( )
//
// //str = str.replace(/,/g, ' let ');
// str = str.replace(/[ ;,.)(]/g, ' ');
//
// let args = str.split(/ /g).filter(e => e);
//
// console.log(args.join('\n'));
// }
//problem12('let sum = 4 * 4,b = "wow";');
// function problem13(arr) {
// let regex = RegExp('(?<![\\d])[0-9]{1,2}-[A-Z][a-z]{2}-[0-9]{4}(?![\\d])', 'g');
//
// for (let i = 0; i < arr.length; i++) {
// let currentSentence = arr[i];
//
// let matches = currentSentence.match(regex);
// if(matches !== null && matches !== undefined){
// for (let j = 0; j < matches.length; j++) {
// let currentMatch = matches[j];
// let matchArgs = currentMatch.split(/-/g);
//
// let day = matchArgs[0];
// let month = matchArgs[1];
// let year = matchArgs[2];
//
// console.log(`${currentMatch} (Day: ${day}, Month: ${month}, Year: ${year})`);
// }
//
// }
//
// }
//
// function parseDate(s) {
// let months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
// jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
// let p = s.split('-');
// return new Date(p[2], months[p[1].toLowerCase()], p[0]);
// }
// }
// problem13(['I am born on 30-Dec-1994.I am born on 30-Dec-1994.', 'This is not date: 512-Jan-1996.', 'My father is born on the 29-Jul-1955.']);
//
// function problem14(arr) {
// let people = [];
//
// let regex = RegExp('^([A-Z][A-Za-z]*)\\s-\\s([1-9][0-9]*)\\s-\\s([A-Za-z 0-9-]+)$', 'g');
//
// for (let i = 0; i < arr.length; i++) {
// let currentLine = arr[i];
//
// let match = regex.exec(currentLine);
//
// while(match !== null){
// let name = match[1].trim();
// let salary = match[2].trim();
// let position = match[3].trim();
//
// let employee = {
// 'Name': name,
// 'Position': position,
// 'Salary': salary
// };
//
// people.push(employee);
//
// match = regex.exec(currentLine);
// }
//
// }
//
// for (let person of people) {
// console.log(`Name: ${person['Name']}`);
// console.log(`Position: ${person['Position']}`);
// console.log(`Salary: ${person['Salary']}`);
// }
// }
// problem14(['Isacc - 1000 - CEO', 'Ivan - 500 - Employee', 'Peter - 500 - Employee']);
//problem14(['Jonathan - 2000 - Manager','Peter- 1000- Chuck', 'George - 1000 - Team Leader']);
function problem15(username, email, phone, arr) {//Form Filler
for (let i = 0; i < arr.length; i++) {
let currentLine = arr[i];
currentLine = currentLine.replace(/<![a-zA-Z]+?!>/g, username);
currentLine = currentLine.replace(/<@[a-zA-Z]+?@>/g, email);
currentLine = currentLine.replace(/<[+][a-zA-Z]+?[+]>/g, phone)
console.log(currentLine);
}
}
problem15('Pesho', 'pesho@softuni.bg', '90-60-90',
['Hello, <!username!>! <!a!> <!!>',
'Welcome to your Personal profile.',
'Here you can modify your profile freely.',
'Your current username is: <!fdsfs!>. Would you like to change that? (Y/N)',
'Your current email is: <@DasEmail@>. Would you like to change that? (Y/N)',
'Your current phone number is: <+number+>. Would you like to change that? (Y/N)']);
// function problem16(inputStr) { //match multiplication
// let regex = RegExp('(-?[\\d]+\\.?[\\d]*)\\s*[*]{1}\\s*(-?[\\d]+\\.?[\\d]*)', 'g');
//
// let match = regex.exec(inputStr);
// while(match !== null){
// let wholeMatch = match[0];
// let firstNumber = Number(match[1]);
// let secondNumber = Number(match[2]);
//
// let product = firstNumber * secondNumber;
//
// inputStr = inputStr.replace(wholeMatch, product + '');
//
// match = regex.exec(inputStr);
// }
//
// console.log(inputStr);
// }
//
// problem16('My bill: 2*2.50 (beer); 2* 1.20 (kepab); -2 * 0.5 (deposit).');
|
const musicList = [
{
name: "Life",
artist: "DJ Quads",
image: "image1",
audio: "music1"
},
{
name: "Warm Nights",
artist: "LAKEY INSPIRED",
image: "image2",
audio: "music2"
},
{
name: "Ice Tea",
artist: "Not The King",
image: "image3",
audio: "music3"
},
{
name: "When You Move Your Body",
artist: "Quesa",
image: "image4",
audio: "music4"
}
]
|
import WorldContainer from './containers/WorldContainer';
import QuizContainer from './containers/QuizContainer';
import ReactQuizContainer from './containers/ReactQuizContainer';
import NavBar from './components/NavBar';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Scores from './components/Scores';
import { postResults as postResultsFlags } from "./services/FlagsQuizService";
import { postResults as postResultsCapitals } from "./services/CapitalsQuizService";
import { getResults as getResultsCapitals } from "./services/CapitalsQuizService";
import { getResults as getResultsFlags } from "./services/FlagsQuizService";
import { getResults as getResultsNationalAnimals } from "./services/NationalAnimalQuizService";
import { postResults as postResultsNationalAnimals } from "./services/NationalAnimalQuizService";
import './App.css';
import FlagsQuizQuestion from "./components/FlagsQuizQuestion"
import CapitalsQuizQuestion from "./components/CapitalsQuizQuestion"
import ErrorPage from "./components/ErrorPage"
import { deleteResult as deleteResultFlags } from "./services/FlagsQuizService"
import { deleteResult as deleteResultCapitals } from "./services/CapitalsQuizService"
import MapContainer from './containers/MapContainer';
import { deleteResult as deleteResultNationalAnimals } from "./services/NationalAnimalQuizService"
function App() {
return (
<div>
<Router>
<>
<NavBar />
<Switch>
<Route exact path="/quiz/national-animals/scores" render={() => <Scores getResults={getResultsNationalAnimals} deleteResult={deleteResultNationalAnimals} />} />
<Route exact path="/quiz/national-animals" render={() => <ReactQuizContainer postResults={postResultsNationalAnimals} />} />
<Route exact path="/quiz/capitals/scores" render={() => <Scores key="capitals-scores" getResults={getResultsCapitals} deleteResult={deleteResultCapitals} />} />
<Route exact path="/quiz/capitals" render={() => <QuizContainer key={Math.random()} postResults={postResultsCapitals} QuestionComponent={CapitalsQuizQuestion} />} />
<Route exact path="/quiz/flags/scores" render={() => <Scores key="flags-scores" getResults={getResultsFlags} deleteResult={deleteResultFlags} />} />
<Route exact path="/quiz/flags" render={() => <QuizContainer key={Math.random()} postResults={postResultsFlags} QuestionComponent={FlagsQuizQuestion} />} />
<Route exact path="/" render={() => <WorldContainer />} />
<MapContainer />
<Route component={ErrorPage} />
</Switch>
</>
</Router>
</div>
);
}
export default App;
|
import {put, takeEvery, select} from 'redux-saga/effects'
import {push} from 'connected-react-router/immutable'
// local libs
import {BACKEND_URL} from 'src/config'
import {plainProvedGet as g, immutableProvedGet as ig} from 'src/App/helpers'
import errorActions from 'src/generic/ErrorMessage/actions'
import actions from 'src/App/MainHeader/Search/actions'
export function* loadSuggestionsFlow({payload: formData}) {
try {
const
reqData = yield select(x => ({
localeCode: ig(x, 'app', 'locale', 'localeCode'),
orientationCode: ig(x, 'app', 'mainHeader', 'niche', 'currentOrientation'),
...formData
})),
suggestions = yield fetch(`${BACKEND_URL}/get-search-suggestions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json',
},
body: JSON.stringify(reqData),
}).then(response => {
if (response.status !== 200)
throw new Error(`Response status is ${response.status} (not 200)`)
return response.json()
})
yield put(actions.setNewSuggestions(suggestions))
} catch (err) {
console.error('loadSuggestionsFlow is failed with exception:', err)
yield put(actions.setEmptySuggestions())
yield put(errorActions.openErrorMessage())
}
}
export function* runSearchFlow({payload: {path}}) {
yield put(push(path))
}
export default function* saga() {
yield takeEvery(g(actions, 'suggestionsFetchRequest'), loadSuggestionsFlow)
yield takeEvery(g(actions, 'runSearch'), runSearchFlow)
}
|
import React from 'react';
import { Provider } from 'react-redux'
import configureStore from './store';
import { PersistGate } from 'redux-persist/integration/react'
import Theme from './themes/defaultTheme';
import Steps from './containers/Steps';
const { store, persistor } = configureStore()
class App extends React.Component {
render() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Theme>
<Steps />
</Theme>
</PersistGate>
</Provider>
)
}
}
export default App;
|
import React, {Component} from 'react'
import axios from 'axios'
export default class Login extends Component{
handleSubmit = e =>{
e.preventDefault();
const data = {
email: this.email,
password: this.password
}
axios.post('login',data)
.then(res => {
console.log(res)
localStorage.setItem("token", res.data.token);
})
.catch(err => {
if(!err.response){
this.errStatus ="Error: Network Error";
}else{
this.errStatus=err.response.data.message;
}console.log(err)}
)
console.log("Works", data)
}
render(){
return(
<form onSubmit={this.handleSubmit}>
<h3>Login</h3>
<div className="form-group">
<label> Email</label>
<input type="email" className="form-control" placeholder="Email"
onChange={e => this.email=e.target.value}/></div>
<div className="form-group">
<label> Password</label>
<input type="password" className="form-control" placeholder="Password"
onChange ={e => this.password=e.target.value}/></div>
<div className="form-group">
<button className="btn btn-primary btn-block">Login</button>
</div>
</form>
)
}
}
|
import { Design } from '@freesewing/core'
import { data } from '../data.mjs'
import { back } from './back.mjs'
import { frontRight } from './frontright.mjs'
import { frontLeft } from './frontleft.mjs'
import { buttonPlacket } from './buttonplacket.mjs'
import { buttonholePlacket } from './buttonholeplacket.mjs'
import { yoke } from './yoke.mjs'
import { sleeve } from './sleeve.mjs'
import { collarStand } from './collarstand.mjs'
import { collar } from './collar.mjs'
import { sleevePlacketUnderlap } from './sleeveplacket-underlap.mjs'
import { sleevePlacketOverlap } from './sleeveplacket-overlap.mjs'
import { cuff } from './cuff.mjs'
/* Re-export skeleton part */
import { front } from './front.mjs'
// Setup our new design
const Simon = new Design({
data,
parts: [
back,
buttonholePlacket,
buttonPlacket,
collar,
collarStand,
cuff,
front,
frontRight,
frontLeft,
sleeve,
sleevePlacketOverlap,
sleevePlacketUnderlap,
yoke,
],
})
// Named exports
export {
back,
buttonholePlacket,
buttonPlacket,
collar,
collarStand,
cuff,
front,
frontRight,
frontLeft,
sleeve,
sleevePlacketOverlap,
sleevePlacketUnderlap,
yoke,
Simon,
}
/*
import freesewing from '@freesewing/core'
import Brian from '@freesewing/brian'
import plugins from '@freesewing/plugin-bundle'
import flipPlugin from '@freesewing/plugin-flip'
import plugin from '@freesewing/plugin-bust' // Note: conditional plugin
import config from '../config'
// Parts
import draftBack from './back'
import draftFront from './front'
import draftFrontRight from './frontright'
import draftButtonPlacket from './buttonplacket'
import draftFrontLeft from './frontleft'
import draftButtonholePlacket from './buttonholeplacket'
import draftYoke from './yoke'
import draftSleeve from './sleeve'
import draftCollarStand from './collarstand'
import draftCollar from './collar'
import draftSleevePlacketUnderlap from './sleeveplacket-underlap'
import draftSleevePlacketOverlap from './sleeveplacket-overlap'
import draftCuff from './cuff'
//
const condition = (settings = false) =>
settings &&
settings.options &&
settings.options.draftForHighBust &&
settings.measurements.highBust
? true
: false
// Create design
const Simon = new freesewing.Design(config, [plugins, flipPlugin], { plugin, condition })
// Attach draft methods to prototype
Simon.prototype.draftBase = function (part) {
return new Brian(this.settings).draftBase(part)
}
Simon.prototype.draftFrontBase = function (part) {
return new Brian(this.settings).draftFront(part)
}
Simon.prototype.draftBackBase = function (part) {
return new Brian(this.settings).draftBack(part)
}
Simon.prototype.draftSleeveBase = function (part) {
const brian = new Brian(this.settings)
return brian.draftSleeve(brian.draftSleevecap(part))
}
Simon.prototype.draftBack = draftBack
Simon.prototype.draftFront = draftFront
Simon.prototype.draftFrontRight = draftFrontRight
Simon.prototype.draftButtonPlacket = draftButtonPlacket
Simon.prototype.draftFrontLeft = draftFrontLeft
Simon.prototype.draftButtonholePlacket = draftButtonholePlacket
Simon.prototype.draftYoke = draftYoke
Simon.prototype.draftSleeve = draftSleeve
Simon.prototype.draftCollarStand = draftCollarStand
Simon.prototype.draftCollar = draftCollar
Simon.prototype.draftSleevePlacketUnderlap = draftSleevePlacketUnderlap
Simon.prototype.draftSleevePlacketOverlap = draftSleevePlacketOverlap
Simon.prototype.draftCuff = draftCuff
// Named exports
export { config, Simon }
// Default export
export default Simon
*/
|
import React, { Component } from 'react';
import { Link } from "react-router-dom";
import { Formik, Form, Field } from 'formik';
import {userService} from '../services/user.service';
import * as Yup from 'yup';
//Form validation
const SignupSchema = Yup.object().shape({
name: Yup.string()
.min(4, 'Too Short!, minimum 4 characters')
.max(50, 'Too Long!')
.required('Required'),
password: Yup.string()
.min(4, 'Too Short!, minimum 4 characters')
.max(50, 'Too Long!')
.required('Required'),
email: Yup.string()
.email('Invalid email')
.required('Required'),
});
class Register extends Component {
constructor(props) {
super(props);
//TODO: if user already logged, redirect him to create cv
this.state = {
isRegistrationFailed: false, //for showing error msg
};
}
//if user already logged, redirect him to cvs
componentDidMount(){
if(userService.isUserLogged()) this.toCvs();
}
render(){
let errorMsg;
if (this.state.isRegistrationFailed) errorMsg = <div className="text-danger">Registation failed, try again!</div>
return(
<div>
<div className="title">Create Account</div>
<div className="container spacer col-md-4 offset-md-4 col-sm-12 login-form">
{errorMsg}
<Formik
initialValues={{
name: '',
password: '',
email: '',
}}
validationSchema={SignupSchema}
onSubmit={values => {
const { name, email, password } = values;
this.handleRegister(name, email, password);
}}
>
{({ errors, touched }) => (
<Form>
<Field name="name"
className="form-control border rounded" placeholder="full name"/>
{errors.name && touched.name ? (
<div className="text-danger">{errors.name}</div>
) : null}
<Field name="email"
className="form-control border rounded" placeholder="email"/>
{errors.email && touched.email ? (
<div className="text-danger">{errors.email}</div>
) : null}
<Field name="password" type="password"
className="form-control border rounded" placeholder="password"/>
{errors.password && touched.password ? <div className="text-danger">{errors.password}</div> : null}
<br/>
<div>
<button type="submit" className="btn btn-dark">Register</button>
<p>Already registred?<Link to="/login">Sign in</Link></p>
</div>
</Form>
)}
</Formik>
</div>
</div>
)
}
handleRegister (name, email, password){
userService.register(name, email, password)
.then(response => {
console.log(response);
return response;
})
.then(json => {
if (json.data.success) {
const {id, name, email, api_token } = json.data.data;
let userData = {
id,
name,
email,
api_token,
timestamp: new Date().toString()
};
// save user data in browser local storage
localStorage["user"] = JSON.stringify(userData);
//REDIRECT to user's cvs
this.toCvs();
}
// show error msg
else this.setState({isRegistrationFailed:true});
})
.catch(error => {
//show error msg
this.setState({isRegistrationFailed:true});
});
}
toCvs(){
window.location.href = "/cvs";
}
}
export default Register;
|
function needleInHaystack(needle, haystack) {
//last index of needle
let needleLength = needle.length - 1;
let indexes = []
let count = 0;
let currentIndex = 0;
let startIndex = null;
for (let i = 0; i < haystack.length; i++) {
if (haystack[i] === needle[currentIndex]) {
if (currentIndex === 0) {
startIndex = i;
}
//if we match the first char in the string
if (currentIndex === needleLength){
//if we at the end
count++;
currentIndex = 0;
indexes.push(startIndex);
} else {
//otherwise keep looking over the string
currentIndex++;
}
}
}
return indexes + ' --- ' + count;
}
console.log(needleInHaystack("ABC","ABCDSGDABCSAGAABCCCCAAABAABC"));
|
$(document).ready(function () {
$.ajax({
url: 'http://localhost/final/Controller/ProductController.php?method=index',
dataType: 'json'
}).done(function (data) {
var i;
for (i = 0; i < data.length; i++) {
products = "<tr id='product"+data[i].id+"'><td>" + data[i].id + "</td><td>" + data[i].name + "</td><td>" + data[i].description + "</td><td>" + data[i].price + "</td>";
products += "<td><a href='../../../../final/View/product/create-update.html?id=" + data[i].id + "' class='btn btn-primary'>Editar </a> ";
products += '<button id="'+data[i].id+'" class="btn btn-danger" type="button" onclick="destroy(this.id)" value="'+data[i].id+'">Excluir</button></tr>';
$('#product-list').append(products);
}
});
});
$(document).ready(function () {
var query = location.search.slice(1);
var partes = query.split('&');
var data = {};
partes.forEach(function (parte) {
var chaveValor = parte.split('=');
var chave = chaveValor[0];
var valor = chaveValor[1];
data[chave] = valor;
});
$.ajax({
url: 'http://localhost/final/Controller/ProductController.php?method=show&id=' + data.id,
dataType: 'json'
}).done(function (data) {
$('#name').val(data.name);
$('#description').val(data.description);
$('#price').val(data.price);
if (data.id) {
btnupdate = '<button type="button" id="save" name="save" class="btn btn-primary" onclick="updateProduct()">Atualizar</button>';
id = '<input id="id" name="id" type="hidden" value="' + data.id + '">';
$('#save').remove();
$('#btn-salvar').append(btnupdate);
$('#field').append(id);
$('#method').val('update');
}
});
});
function saveProduct() {
var data = $('#form-product').serialize();
$.ajax({
url: '../../Controller/ProductController.php',
method: 'POST',
data: data,
dataType: 'json'
}).done(function (data) {
if (!data.msg == "") {
$('.display-error').html('<ul>' + data.msg + '</ul>');
$('.display-error').css('display', 'block');
$('.display-success').hide();
}
else {
console.log(data);
$('.display-success').html('<ul><li>Produto Cadastrado!</li></ul>');
$('.display-success').css('display', 'block');
$('.display-error').hide();
$('#form-product').trigger('reset');
}
})
}
function updateProduct() {
var data = $('#form-product').serialize();
$.ajax({
url: '../../Controller/ProductController.php',
method: 'POST',
data: data,
dataType: 'json',
}).done(function (data) {
if (!data.msg == "") {
$('.display-error').html('<ul>' + data.msg + '</ul>');
$('.display-error').css('display', 'block');
$('.display-success').hide();
}
else {
console.log(data);
$('.display-success').html('<ul><li>Produto Atualizado!</li></ul>');
$('.display-success').css('display', 'block');
$('.display-error').hide();
}
})
}
function destroy(id){
$.ajax({
url: 'http://localhost/final/Controller/ProductController.php?method=destroy&id='+id,
dataType: 'json'
}).done(function () {
});
$('#product'+id).remove();
}
|
import React from 'react';
const Terms = () => {
return (
<React.Fragment>
<h3>A. Registration Process and Payment Methods</h3>
<ol>
<li>Conference registrations will not be approved until the correct payment is received and processed. </li>
<li>Registrants should obtain confirmation before committing to other travel arrangements. </li>
<li>The prices are exclusive of VAT/GST and local charges.</li>
<li>Directions cannot be responsible for your spam filters blocking your confirmation email. </li>
<li>Please be sure spam filters will allow mail from the conference coordinator / website administration.</li>
<li>Accommodation and Travel costs are not included in the conference registration fee. Directions will offer some Hotel suggestions or a link to a dedicated booking site. However, attendees are responsible for making their own room arrangements.</li>
<li>The total accepted number of attendees can be limited based on the capacity of the venue. Registrations will be handled on a first-come, first-served basis. </li>
<li>Spouses who would like to join the Community Party only, should register and pay guests fee. </li>
<li>You accept all the terms and conditions of Directions by registering to the Directions conference. </li>
<li>You will need to comply at all times with the rules and regulations imposed by the venue.</li>
<li>It may be necessary for reasons beyond the control of Directions to alter the content and timing of the conference, the identity of the speakers, the date or the venue. In the unlikely event of the conference being cancelled. In case of cancellation, Directions will refund you the registration fee but we will not be liable to you for any other costs or losses, whether direct or indirect. Should we be unable to perform any obligations under this Agreement due to causes or circumstances beyond its reasonable control, including any war or threatened war, terrorism or threatened terrorism, fire, flood, drought, strike, lock out or actions of the venue, we will not be liable to you for this.</li>
</ol>
<h3>B. Cancellation Policy</h3>
Conference registration can be cancelled and is refundable until 30 days before the start of the event.
You can always create substitutes by only making amendment on your account on our registration area.
<h3>C. Conference program</h3>
Conference program is subject to change. We will publish and update our actual information on the event website and in the Conference App.
<h3>D. Participation and Behavior on Directions Conference and Activities</h3>
<ol>
<li>Directions attendees are expected to behave business professionally and ethically. Excessive use of obscene language, abusive behavior, or threatening behavior directed to any other conference attendee is not tolerated and will result in eviction. Directions seeks to create a respectful, friendly, fun and inclusive experience for all participants.</li>
<li>We do not tolerate harassing or disrespectful behavior, messages, images, or interactions by any party participant, in any form, at any aspect of the program including business and social activities, regardless of location.</li>
<li>We do not tolerate any behavior that is degrading to any gender, race, sexual orientation or disability, or any behavior that would violate the Directions Anti-Harassment and Anti-Discrimination Policy, Equal Employment Opportunity Policy, or Standards of Business Conducts in any way. In short, the entire experience at the venue must meet our culture standards.</li>
<li>We encourage everyone to assist in creating a welcoming and safe environment. Please report any concerns, harassing behavior, or suspicious or disruptive activity to our venue staff, the event host or Directions Board members, or the nearest event staff.</li>
</ol>
<h3>E. Personal Information</h3>
<ol>
<li>Please note that participant contact details will be kept on the Directions database, which will only be used by Directions for future contact or relevant conference and community communication. Credit card information will NOT be stored by Directions.</li>
<li>Unless the Registrant explicit request disallowing (Opt Out during registration) to share his/her contact information – the registrant contact details will be visible to other registrants/the Directions Community Network.</li>
<li>The e-mail addresses will also be used to circulate last minute details and announcements of future Directions events.</li>
<li>If you would like your record to be deleted after the conference, please notify Direction by email or via the website.</li>
</ol>
<h3>F. Personal Property</h3>
Directions accepts no responsibility for loss or damage to personal property in any of its activities.
<h3>G. Event Restrictions</h3>
<ol>
<li>Only Dynamics Partners are allowed to attend Directions conferences. Any registrant who is not registered through a Dynamics Partner may be refused entrance to the conference without any refund. </li>
<li>Microsoft Partner Account Number (formerly known as VOICE ID) is therefore required at the registration. </li>
<li>No side events, during the conference session hours, allowed without permission of Directions Organizing Committee. Violation fee is EUR 5,000. </li>
<li>Except for use at your own exhibition table/booth: no spreading folders or placing banners without permission of committee. Violation fee is EUR 2,000. </li>
<li>No children allowed at the event or during receptions/ theme dinner. </li>
<li>Spouses should register as guests in order to join the Community Party. They have no access to any sessions or workshops unless they pay the full attendee fee. </li>
<li>Conference Badges are personal and cannot be used by more than one person. </li>
<li>Wearing your badge in a visible manner is required for the whole event especially during receptions and theme dinner. </li>
<li>Last-minute substitution of attendees must always be also reported to the Directions Organizing Committee. </li>
<li>Sponsorships are official once we received the registration. Our payment term is 14 days from the date of registration. </li>
<li>As an event sponsor it is your own responsibility to deliver the correct and required formats and meet the due dates / deadlines. When failing these you will not benefit from all sponsor opportunities and you are not entitled to any refund. The Directions Organizing Committee will use any alternative to fill the gap. </li>
</ol>
</React.Fragment>
);
};
export default Terms;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.