text
stringlengths 7
3.69M
|
|---|
import axios from 'axios';
const { REACT_APP_NOTES_URL } = process.env;
export const addNote = content => {
return axios.post(REACT_APP_NOTES_URL, {content});
};
export const deleteNote = id => {
return axios.delete(`${REACT_APP_NOTES_URL}/${id}`);
};
export const fetchNotes = () => {
return axios
.get(REACT_APP_NOTES_URL)
.then(response => response.data);
};
|
import React from 'react';
import { Row, Col } from 'reactstrap';
import Photo from '../Photo/Photo';
const PhotoList = () => {
return (
<Row>
{/* md="4" にしてレスポンシブに対応する */}
<Col md="4"><Photo /></Col>
<Col md="4"><Photo /></Col>
<Col md="4"><Photo /></Col>
<Col md="4"><Photo /></Col>
<Col md="4"><Photo /></Col>
<Col md="4"><Photo /></Col>
<Col md="4"><Photo /></Col>
<Col md="4"><Photo /></Col>
<Col md="4"><Photo /></Col>
</Row>
);
}
export default PhotoList;
|
Zotero.Items = function(feed){
//represent items as array for ordering purposes
this.itemsVersion = 0;
this.syncState = {
earliestVersion: null,
latestVersion: null
};
this.displayItemsArray = [];
this.displayItemsUrl = '';
this.itemObjects = {};
this.unsyncedItemObjects = {};
if(typeof feed != 'undefined'){
this.addItemsFromFeed(feed);
}
};
Zotero.Items.prototype.dump = function(){
var dump = {};
dump.instance = "Zotero.Items.dump";
dump.itemsVersion = this.itemsVersion;
dump.itemsArray = [];
J.each(this.itemObjects, function(key, val){
dump.itemsArray.push(val.dump());
});
return dump;
};
Zotero.Items.prototype.loadDump = function(dump){
Z.debug("-------------------------------Zotero.Items.loadDump", 3);
var items = this;
var itemKeys = [];
for (var i = 0; i < dump.itemsArray.length; i++) {
var item = new Zotero.Item();
item.loadDump(dump.itemsArray[i]);
this.addItem(item);
itemKeys.push(item.itemKey);
}
if(this.owningLibrary){
this.owningLibrary.itemKeys = itemKeys;
}
//add child itemKeys to parent items to make getChildren work locally
Z.debug("Adding childItemKeys to items loaded from dump");
var parentItem;
J.each(items.itemObjects, function(ind, item){
if(item.parentKey){
parentItem = items.getItem(item.parentKey);
if(parentItem !== false){
parentItem.childItemKeys.push(item.itemKey);
}
}
});
//TODO: load secondary data structures
//nothing to do here yet? display items array is separate - populated with itemKey request
return this;
};
Zotero.Items.prototype.getItem = function(key){
//Z.debug("Zotero.Items.getItem", 3);
if(this.itemObjects.hasOwnProperty(key)){
return this.itemObjects[key];
}
return false;
};
Zotero.Items.prototype.getItems = function(keys){
var items = this;
var gotItems = [];
for(var i = 0; i < keys.length; i++){
gotItems.push(items.getItem(keys[i]));
}
return gotItems;
};
Zotero.Items.prototype.loadDataObjects = function(itemsArray){
//Z.debug("Zotero.Items.loadDataObjects", 3);
var loadedItems = [];
var libraryItems = this;
J.each(itemsArray, function(index, dataObject){
var itemKey = dataObject['itemKey'];
var item = new Zotero.Item();
item.loadObject(dataObject);
//Z.debug('item objected loaded');
//Z.debug(item);
libraryItems.itemObjects[itemKey] = item;
//Z.debug('item added to items.itemObjects');
loadedItems.push(item);
});
return loadedItems;
};
Zotero.Items.prototype.addItem = function(item){
this.itemObjects[item.itemKey] = item;
if(this.owningLibrary){
item.associateWithLibrary(this.owningLibrary);
}
return this;
};
Zotero.Items.prototype.addItemsFromFeed = function(feed){
var items = this;
var itemsAdded = [];
feed.entries.each(function(index, entry){
var item = new Zotero.Item(J(entry) );
items.addItem(item);
itemsAdded.push(item);
});
return itemsAdded;
};
//return array of itemKeys that we don't have a copy of
Zotero.Items.prototype.keysNotInItems = function(keys){
var notPresent = [];
J.each(keys, function(ind, val){
if(!this.itemObjects.hasOwnProperty(val)){
notPresent.push(val);
}
});
return notPresent;
};
Zotero.Items.prototype.remoteDeleteItem = function(key){
var items = this;
if(items.itemObjects.hasOwnProperty(key) && items.itemObjects[key].synced === true){
delete items.itemObjects[key];
return true;
}
return false;
};
|
var $ = require('jquery');
var React = require('react');
var Input = require('./Input.jsx');
var LoginForm = React.createClass({
renderButtonRipple: function() {
var $ripples = $('.ripples');
$ripples.on('click.Ripples', function(e) {
var $this = $(this);
var $offset = $this.parent().offset();
var $circle = $this.find('.ripplesCircle');
var x = e.pageX - $offset.left;
var y = e.pageY - $offset.top;
$circle.css({
top: y + 'px',
left: x + 'px'
});
$this.addClass('is-active');
});
$ripples.on('animationend webkitAnimationEnd mozAnimationEnd oanimationend MSAnimationEnd', function(e) {
$(this).removeClass('is-active');
});
},
componentDidMount: function() {
this.renderButtonRipple();
},
render: function () {
return (
<form>
<div className="group">
<Input type="text" name="email"
value={this.props.email} onChange={this.props.handleEmailChange} />
<span className="highlight" />
<span className="bar" />
<label>Email</label>
</div>
<div className="group">
<Input type="password" name="password"
value={this.props.password} onChange={this.props.handlePasswordChange} />
<span className="highlight" />
<span className="bar" />
<label>Password</label>
</div>
<button type="button" className="button buttonBlue" onClick={this.props.handleClickSubmit} >
Generate OAuth2 credentials
<div className="ripples buttonRipples"><span className="ripplesCircle" /></div>
</button>
</form>
)
}
})
module.exports = LoginForm;
|
import {StyleSheet} from 'react-native';
export default StyleSheet.create({
title: {
alignItems:'center',
backgroundColor:'#FFFFFF'
},
body:{
flex:6,
backgroundColor:'#cccc'
},
horizontal:{
flex:1,
flexDirection:'row',
backgroundColor:'#ddd444'
},
container:{
width:'25%'
}
})
|
Polymer.PaperSpinnerBehavior = {
listeners: {
animationend: "__reset",
webkitAnimationEnd: "__reset"
},
properties: {
active: {
type: Boolean,
value: !1,
reflectToAttribute: !0,
observer: "__activeChanged"
},
alt: {
type: String,
value: "loading",
observer: "__altChanged"
},
__coolingDown: {
type: Boolean,
value: !1
}
},
__computeContainerClasses: function(e, t) {
return [e || t ? "active" : "", t ? "cooldown" : ""].join(" ")
},
__activeChanged: function(e, t) {
this.__setAriaHidden(!e), this.__coolingDown = !e && t
},
__altChanged: function(e) {
e === this.getPropertyInfo("alt").value ? this.alt = this.getAttribute("aria-label") || e : (this.__setAriaHidden("" === e), this.setAttribute("aria-label", e))
},
__setAriaHidden: function(e) {
var t = "aria-hidden";
e ? this.setAttribute(t, "true") : this.removeAttribute(t)
},
__reset: function() {
this.active = !1, this.__coolingDown = !1
}
};
|
const myIssues ={
"results":
[
{
"id":4,
"user_id":"",
"date":"2019-03-21",
"heading":"Past one month garbage and sewage are flowing",
"detail":"Despite many complaints to chennai corporation about garbage and sewage overflowing past one month, there is no use at all. It causing problems to pedestrians and children’s ; You can see the street how bad it is.",
"address":"Diwan sahib garden, royapettah, chennai",
"posterpath":"https://i.ibb.co/WFwkwbn/4.jpg",
"category":"Garbage Dumping",
"location":"Chennai",
"status":"Open",
"comment":""
},
{
"id":5,
"user_id":"",
"date":"2019-03-14",
"heading":"At Virugambakkam market, brace yourself for an olfactory attack",
"detail":"Delayed clearance of garbage from the Virugambakkam market on Kaliamman Koil Street leaves the space with more than just accumulated waste. There is a nauseating addition to it — an overhanging smell of putrifying vegetables, fruits and vegetables.",
"address":"The market comes under the jurisdiction of Zone – 11 (Valasaravakkam) of Greater Chennai Corporation.",
"posterpath":"https://i.ibb.co/YXYy2tf/5.jpg",
"category":"Garbage Dumping",
"location":"Chennai",
"status":"Closed",
"comment":"",
}
]
}
module.exports = myIssues;
|
(function () {
'use strict';
angular
.module('app')
.directive('btnDirective', btnDirective);
btnDirective.$inject = [];
function btnDirective() {
return {
restrict: 'E',
bindToController: {
text: "@",
click: "&"
},
replace: true,
templateUrl: 'app/directives/btn-directive/btn-tpl.html',
controller: 'BtnDirectiveController as btnController'
};
}
}());
|
module.exports = [
// 猎豹浏览器
['LBBROWSER', ['LBBROWSER']],
['QQBrowser', ['QQBrowser']],
['MQQBrowser', ['MQQBrowser']],
['UCBrowser', ['UCBrowser', 'UCWEB']],
['Maxthon', ['Maxthon']],
['SamsungBrowser', ['SamsungBrowser']],
['Edge', ['Edge']],
['Chrome', ['Chrome', 'CriOS']],
['Firefox', ['Firefox']],
['Safari', ['Safari']],
]
|
'use strict';
const $ = require('jquery');
const _ = require('underscore');
const Backbone = require('backbone');
const SellerModel = require('models/Seller');
const App = require('namespace');
const {parseData} = require('utils');
module.exports = Backbone.Collection.extend({
service: 'http://loyalty2.virtualpos.ru/apimobile',
addSellerApiMethod: '/invite/activate',
getSellersApiMethod: '/seller/list',
url() {
return this.service + this.getSellersApiMethod;
},
model: SellerModel,
localStorage: new Backbone.LocalStorage('Sellers'),
addSeller(inviteCode) {
return $.ajax({
url: this.service + this.addSellerApiMethod,
data: $.extend({}, App.Model.User._authData(), {
code: inviteCode
})
});
},
upgrade() {
const deff = $.Deferred();
$.ajax({
url: this.service + this.getSellersApiMethod,
data: App.Model.User._authData()
}).then(data => {
this._upgrade(data);
deff.resolve();
});
return deff.promise();
},
_upgrade(data) {
const {data: {sellers}} = parseData(data);
const newSellers = _.map(sellers, item => {
return new this.model(item);
});
this.set(newSellers);
_.each(this.models, item => {
item.id = item.get('id');
});
console.log(this);
}
});
|
const {BOOKS, BOOKS_IDS} = require('./constant');
/**
* 获得一个随机的书籍id
*/
const getRandomBookId = () => BOOKS_IDS[Math.floor(Math.random() * BOOKS_IDS.length)];
/**
* 查询书籍名称
* @param {string} bookId 书籍id
*/
const searchBookName = (bookId) => {
const book = BOOKS.find(item => item.id == bookId);
if (typeof book === 'object' && book !== null) {
return book.name;
}
return '没有这本书哦~~';
}
module.exports = {
getRandomBookId,
searchBookName,
};
|
const express = require("express")
const app = express()
const Restaurant = require("../models/restaurant")
app.get("/restaurant", (req, res)=> {
res.render("addRestaurant")
})
app.post("/restaurant", (req, res)=> {
let newRestaurant = {
name: req.body.name,
borough: req.body.borough,
cuisine: req.body.cuisine
}
Restaurant.create(newRestaurant, (err)=> {
if(err) res.send("ERROR")
else res.redirect(`/?search=${req.body.cuisine}`)
})
})
module.exports = app
|
export default (sequelize, DataTypes) => {
const Bookmark = sequelize.define('Bookmark', {
userId: {
primaryKey: true,
type: DataTypes.INTEGER,
allowNull: {
args: false,
message: 'User id must is required'
}
},
slug: {
type: DataTypes.STRING,
allowNull: {
args: false,
message: 'The slug of the story is required'
}
},
title: {
type: DataTypes.STRING,
allowNull: {
args: true
}
},
description: {
type: DataTypes.STRING,
allowNull: {
args: true
}
}
});
Bookmark.associate = function(models) {
// associations can be defined here
};
Bookmark.removeAttribute('id');
return Bookmark;
};
|
import React, { Component } from "react";
// import Card from "@material-ui/core/Card";
// import CardActions from "@material-ui/core/CardActions";
// import CardContent from "@material-ui/core/CardContent";
// import CardMedia from "@material-ui/core/CardMedia";
// import Button from "@material-ui/core/Button";
// import Typography from "@material-ui/core/Typography";
import {
Card,
CardImg,
CardText,
CardBody,
CardTitle,
CardSubtitle,
Container,
Row,
Col,
Button
} from "reactstrap";
import Api from "../Services/Api";
export default class AllAnnounce extends Component {
constructor(props) {
super(props);
this.api = new Api();
this.state = {
annonces: []
};
}
componentDidMount() {
this.getFirstAnnonces();
}
getFirstAnnonces = () => {
this.api.getFirstAnnonces().then(res => {
console.log(res.data);
if (res.data.success) {
this.setState({ annonces: res.data.annonces });
}
});
};
render() {
let annonces = this.state.annonces.map((annonce, index) => {
return (
<Col md="4">
<Card key={index} style={{ height: "500px", marginTop: "20px" }}>
<CardImg
top
width="100%"
height="300px"
src={annonce.photo}
alt="Card image cap"
/>
<CardBody>
<CardTitle>{annonce.nom}</CardTitle>
<CardSubtitle>{annonce.prix}$</CardSubtitle>
</CardBody>
<CardBody>
<CardText>{annonce.description.substring(0, 100)}</CardText>
<Button
color="primary"
onClick={() => (window.location = "/ClientLogin")}
>
Ajouter au panier
</Button>
<Button
color="success"
onClick={() => (window.location = "/annonce/" + annonce._id)}
>
Voir le produit
</Button>
</CardBody>
</Card>
</Col>
);
});
return (
<div>
<Container>
<Row>{annonces}</Row>
</Container>
</div>
);
}
}
// render() {
// let annonces = this.state.annonces.map((annonce, index) => {
// return (
// <div>
// <Card>
// <CardMedia
// style={{ height: 0, paddingTop: "5%" }}
// src={annonce.photo}
// // title={this}
// />
// <CardContent>
// <Typography gutterBottom variant="headline" componant="h2">
// {/* {this.props.} */}
// {annonce.nom}
// </Typography>
// <Typography componant="p">
// {/* {this.props.discription} */}
// {annonce.description}
// </Typography>
// </CardContent>
// <CardActions>
// <Button size="small" color="primary" href="" target="_blank">
// go to shop
// </Button>
// </CardActions>
// </Card>
// </div>
// );
// });
// return (
// <div>
// <Container>
// {/* <AnnonceDetaille /> */}
// <Row>{annonces}</Row>
// </Container>
// </div>
// );
// }
// }
|
const commonFunction = require("../functions/commonFunctions")
const packageModel = require("../models/packages")
const recurringPaypal = require("../functions/recurring-paypal")
const oneTimePaypal = require("../functions/one-time-paypal")
const globalModel = require("../models/globalModel")
const dateTime = require("node-datetime")
exports.browse = async (req, res) => {
let package_id = req.params.package_id
let packageObj = {}
if (package_id) {
await packageModel.findById(package_id, req, res).then(result => {
if (result) {
packageObj = result
} else {
package_id = null
}
}).catch(err => {
package_id = null
})
}
req.getPackages = true
if (package_id) {
req.session.orderId = null
//delete all user pending orders
await globalModel.custom(req, "DELETE FROM orders WHERE owner_id = ? AND state = 'initial'", [req.user.user_id]).then(result => {
})
let currentDate = dateTime.create().format("Y-m-d H:M:S")
//create order
await globalModel.create(req, { owner_id: req.user.user_id, gateway_id: 1, state: "initial", creation_date: currentDate, source_type: "subscription", source_id: 0 }, "orders").then(result => {
if (result) {
req.session.orderId = result.insertId
} else {
}
})
if (!req.session.orderId) {
res.redirect("/upgrade")
res.end()
return
}
await commonFunction.getGeneralInfo(req, res, 'upgrade_browse', true)
const data = {}
data["amount"] = parseFloat(packageObj.price).toFixed(2)
data['id'] = packageObj.package_id
data["description"] = packageObj.description
data["headingTitle"] = packageObj.title
data["returnUrl"] = `${process.env.PUBLIC_URL}/upgrade/successulPayment`
data["cancelUrl"] = `${process.env.PUBLIC_URL}/upgrade/cancelPayment`
data.frequency = packageObj.type
data.interval = packageObj.interval
data.sku = "order_"+req.session.orderId
data.title = packageObj.title
if (packageObj.is_recurring == 1) {
return recurringPaypal.init(req, res, data,packageObj).then(result => {
if (result.url) {
req.session.package_id = package_id
req.session.tokenUserPayment = result.token
res.redirect(302, result.url)
} else {
res.redirect("/upgrade")
}
}).catch(err => {
console.log(err, ' ======= Upgrade RECURRING ERR ============')
return res.redirect("/upgrade")
})
} else {
return oneTimePaypal.init(req, res, data).then(result => {
if (result.url) {
req.session.package_id = package_id
req.session.tokenUserPayment = result.token
res.redirect(302, result.url)
res.end()
} else {
res.redirect("/upgrade")
res.end()
}
}).catch(err => {
console.log(err, ' ======= Upgrade ONETIME ERR ============')
res.redirect("/upgrade")
res.end()
})
}
} else {
await commonFunction.getGeneralInfo(req, res, 'upgrade_browse')
}
if (req.query.data) {
if(!req.query.packagesExists){
res.send({data: req.query,pagenotfound:1});
return
}
res.send({ data: req.query })
res.end()
return
}
if(!req.query.packagesExists){
req.app.render(req, res, '/page-not-found', req.query);
return
}
req.app.render(req, res, '/upgrade', req.query)
}
exports.successul = async (req, res, next) => {
let package_id = req.params.id
let gateway = req.body.gateway
let currentDate = dateTime.create().format("Y-m-d H:M:S")
if (!gateway && (!req.session.tokenUserPayment || !req.session.package_id || !req.session.orderId) ) {
return res.redirect(302, '/upgrade')
} else {
package_id = package_id ? package_id : req.session.package_id
let packageObj = {}
await packageModel.findById(package_id, req, res).then(result => {
if (result) {
packageObj = result
} else {
package_id = null
}
}).catch(err => {
package_id = null
})
if (!package_id) {
res.send("/upgrade")
res.end()
}
if(gateway && gateway == "2"){
req.session.orderId = null
//delete all user pending orders
await globalModel.custom(req, "DELETE FROM orders WHERE owner_id = ? AND state = 'initial'", [req.user.user_id]).then(result => {
})
//create order
await globalModel.create(req, { owner_id: req.user.user_id, gateway_id: gateway ? gateway : 1, state: "initial", creation_date: currentDate, source_type: "subscription", source_id: 0 }, "orders").then(result => {
if (result) {
req.session.orderId = result.insertId
} else {
}
})
}
let responseGateway = {}
let isValidResult = false;
if (packageObj.is_recurring == 1) {
if(gateway == "2"){
const { payment_method} = req.body;
const email = req.user.email
const stripe = require('stripe')(req.appSettings['payment_stripe_client_secret']);
await new Promise(async function(resolve, reject){
//create plan
let existingPlan = null;
await new Promise(async function(resolve, reject){
stripe.plans.retrieve(
"package_"+packageObj.package_id
,function(err,response){
if(err){
resolve()
}else{
existingPlan = response
resolve()
}
});
})
if(!existingPlan || !existingPlan.id){
existingPlan = await stripe.plans.create({
"id":"package_"+packageObj.package_id,
"amount_decimal": parseFloat(packageObj.price)*100,
"interval": packageObj.type,
"interval_count": packageObj.interval,
"currency": req.appSettings.payment_default_currency,
"product": {
"name" : packageObj.title,
"type" : "service"
},
'metadata':{
'gateway_id': 2,
'package_id': packageObj.package_id
}
})
}
await stripe.customers.create({
payment_method: payment_method,
email: email,
invoice_settings: {
default_payment_method: payment_method,
},
},function(err, customer) {
if(err){
resolve()
res.send({ error: err.raw.message });
}else{
stripe.subscriptions.create({
customer: customer.id,
items: [{ plan: existingPlan.id }],
expand: ['latest_invoice.payment_intent'],
'metadata':{
'gateway_id': 2,
'order_id': req.session.orderId,
"type":"member_subscription"
}
},function(err, subscription) {
if(err){
resolve()
res.send({ error: err.raw.message });
}else{
const status = subscription['latest_invoice']['payment_intent']['status']
const client_secret = subscription['latest_invoice']['payment_intent']['client_secret']
if(status == "requires_action"){
req.session.orderConfirmPackageID = package_id
req.session.orderConfirmPackagestate = "completed";
req.session.orderConfirmPackagesid = subscription.id;
res.json({'client_secret': client_secret, 'status': status});
}else{
responseGateway.state = "completed";
responseGateway.id = subscription.id;
isValidResult = true;
}
resolve()
}
});
}
});
})
}else{
await recurringPaypal.execute(req, req.session.tokenUserPayment).then(async executeResult => {
if (executeResult) {
responseGateway.id = executeResult.id
responseGateway.state = executeResult.state
isValidResult = true;
} else {
res.redirect("/upgrade/fail")
res.end()
}
}).catch(err => {
res.redirect("/upgrade")
res.end()
})
}
if(isValidResult){
let changed_expiration_date = await recurringPaypal.getExpirationDate(packageObj)
//cancel subscription from gateway
let memberSubscription = require("../functions/ipnsFunctions/memberSubscriptions");
await memberSubscription.cancelAll(req.user, "User changed subscription plan.",null,req);
//cancel other active subscription
await globalModel.update(req,{status:"cancelled"},"subscriptions","owner_id",req.user.user_id)
//cancel other active orders
await globalModel.update(req,{state:"cancelled"},"orders","owner_id",req.user.user_id)
await globalModel.create(req, {gateway_id:gateway ? gateway : 1,type:"member_subscription",id:req.user.user_id, expiration_date: changed_expiration_date, owner_id: req.user.user_id, package_id: package_id, status: responseGateway.state.toLowerCase(),creation_date: currentDate, modified_date: currentDate, gateway_profile_id: responseGateway.id,order_id:req.session.orderId }, "subscriptions").then(async result => {
globalModel.update(req,{gateway_id:gateway ? gateway : 1,gateway_transaction_id:responseGateway.id,state:responseGateway.state.toLowerCase(),'source_id':result.insertId},"orders","order_id",req.session.orderId)
req.query.type = responseGateway.state.toLowerCase()
if(!gateway){
res.redirect("/upgrade/success")
res.end()
}else{
res.send({status:true})
}
})
}
} else {
if(gateway == "2"){
const stripe = require('stripe')(req.appSettings['payment_stripe_client_secret']);
let stripeToken = req.body.stripeToken
await new Promise(function(resolve, reject){
stripe.customers.create({
source: stripeToken,
email: req.user.email,
},function(err, customer) {
if(err){
resolve()
res.send({ error: err.raw.message });
}else{
stripe.charges.create({
amount: parseFloat(packageObj.price)*100,
currency: req.appSettings['payment_default_currency'],
description: packageObj.title,
customer: customer.id,
metadata: {
'gateway_id': 2,
'order_id': req.session.orderId,
"type":"member_subscription"
}
},function(err, charge) {
if(err) {
res.send({ error: err.raw.message });
resolve()
}
else {
responseGateway.state = "completed";
responseGateway.id = charge.id;
responseGateway.gateway_transaction_id = charge.id
isValidResult = true;
resolve()
}
})
}
});
})
}else{
const PayerID = req.query.PayerID
await oneTimePaypal.execute(req, res, PayerID, packageObj).then(async executeResult => {
if (executeResult) {
responseGateway.gateway_transaction_id = req.session.paypalData.id
responseGateway.state = "completed";
responseGateway.id = executeResult.transaction_id;
isValidResult = true;
} else {
res.redirect("/upgrade/fail")
res.end()
}
}).catch(err => {
console.log(err)
res.redirect("/upgrade")
res.end()
})
}
if(isValidResult){
//cancel subscription from gateway
let memberSubscription = require("../functions/ipnsFunctions/memberSubscriptions");
await memberSubscription.cancelAll(req.user, "User changed subscription plan.",null,req);
//cancel other active subscription
await globalModel.update(req,{status:"cancelled"},"subscriptions","owner_id",req.user.user_id)
//cancel other active orders
await globalModel.update(req,{state:"cancelled"},"orders","owner_id",req.user.user_id)
let changed_expiration_date = await recurringPaypal.getExpirationDate(packageObj)
await globalModel.create(req, {gateway_id:gateway ? gateway : 1, type:"member_subscription",id:req.user.user_id, expiration_date: changed_expiration_date, owner_id: req.user.user_id, package_id: package_id, status: responseGateway.state.toLowerCase(),creation_date: currentDate, modified_date: currentDate, gateway_profile_id: responseGateway.id,order_id:req.session.orderId }, "subscriptions").then(async result => {
await globalModel.create(req, {package_id:package_id,type:"member_subscription",id:req.user.user_id,gateway_id:gateway ? gateway : 1, gateway_transaction_id: responseGateway.id, owner_id: req.user.user_id, order_id: req.session.orderId, state: responseGateway.state.toLowerCase(), price: packageObj.price, currency: req.appSettings.payment_default_currency, creation_date: currentDate, modified_date: currentDate,subscription_id:result.insertId }, "transactions").then(async result => {
globalModel.update(req,{gateway_transaction_id:responseGateway.gateway_transaction_id,state:responseGateway.state.toLowerCase(),'source_id':result.insertId},"orders","order_id",req.session.orderId)
if(!gateway){
req.query.type = responseGateway.state.toLowerCase()
res.redirect("/upgrade/success")
res.end()
}else{
res.send({status:true})
}
})
})
}
}
}
}
exports.finishPayment = async(req,res) => {
let package_id = req.session.orderConfirmPackageID
let responseGateway = {}
responseGateway.state = req.session.orderConfirmPackagestate;
responseGateway.id = req.session.orderConfirmPackagesid
let currentDate = dateTime.create().format("Y-m-d H:M:S")
let packageObj = {}
await packageModel.findById(package_id, req, res).then(result => {
if (result) {
packageObj = result
} else {
package_id = null
}
}).catch(err => {
package_id = null
})
if (!package_id) {
res.send({error: "error" })
return;
}
//cancel subscription from gateway
let memberSubscription = require("../functions/ipnsFunctions/memberSubscriptions");
await memberSubscription.cancelAll(req.user, "User changed subscription plan.",null,req);
//cancel other active subscription
await globalModel.update(req,{status:"cancelled"},"subscriptions","owner_id",req.user.user_id)
//cancel other active orders
await globalModel.update(req,{state:"cancelled"},"orders","owner_id",req.user.user_id)
let changed_expiration_date = await recurringPaypal.getExpirationDate(packageObj)
await globalModel.create(req, {gateway_id:2,type:"member_subscription",id:req.user.user_id, expiration_date: changed_expiration_date, owner_id: req.user.user_id, package_id: package_id, status: responseGateway.state.toLowerCase(),creation_date: currentDate, modified_date: currentDate, gateway_profile_id: responseGateway.id,order_id:req.session.orderId }, "subscriptions").then(async result => {
globalModel.update(req,{gateway_id:2,gateway_transaction_id:responseGateway.id,state:responseGateway.state.toLowerCase(),'source_id':result.insertId},"orders","order_id",req.session.orderId)
res.send({status:true});
})
}
exports.paymentSuccessul = async (req, res, next) => {
await commonFunction.getGeneralInfo(req, res, 'payment_success')
if(!req.query.type)
req.query.type = "completed"
if (req.query.data) {
res.send({ data: req.query })
res.end()
return
}
req.app.render(req, res, '/payment-state', req.query)
}
exports.paymentFail = async (req, res, next) => {
await commonFunction.getGeneralInfo(req, res, 'payment_fail')
if(!req.query.type)
req.query.type = "failed"
if (req.query.data) {
res.send({ data: req.query })
res.end()
return
}
req.app.render(req, res, '/payment-state', req.query)
}
exports.cancel = (req, res, next) => {
if (!req.session.tokenUserPayment) {
res.redirect("/upgrade")
if (req.session.paypalData) {
req.session.paypalData = null
}
res.end()
}
req.session.tokenUserPayment = null
if (req.session.paypalData) {
req.session.paypalData = null
}
return res.redirect(302, '/upgrade')
}
|
ticTacToeApp.controller('NewGameCtrl',
function NewGameCtrl($scope, notifier, game, identity) {
'use strict';
$scope.newGame = function newGame(gameName) {
if (!identity.isAuthenticated()) {
notifier.error('Not logged in!');
}
else {
game.createGame(gameName).then(function() {
notifier.success('Created');
$location.path('/my-games');
});
}
};
});
|
import { fade } from '@material-ui/core/styles/colorManipulator';
const darkBlue = '#17315a';
const lightBlue = '#2d6e8d';
const purple = '#96368d';
export default {
white: '#ffffff',
black: '#000000',
teal: '#1FBCC2',
darkBlue,
darkBlue10: fade(darkBlue, 0.1),
lightBlue,
lightBlue24: fade(lightBlue, 0.24),
lightBlue08: fade(lightBlue, 0.08),
lightBlue54: fade(lightBlue, 0.54),
purple,
purple08: fade(purple, 0.08),
purple24: fade(purple, 0.24),
red: '#be4727',
green: '#47b970',
darkIcon: '#74787e',
lightIcon: '#bec2c7',
divider: '#dddfe2',
backgroundGray: '#f8f9fa',
};
|
import React, {memo} from "react";
import {Typography} from "@material-ui/core";
function GradientTypography(props) {
const {children, ...rest} = props
return (
<Typography paragraph {...rest}>
<span className="title-montserrat" style={{
background: "linear-gradient(303.91deg, #8A8AF4 7.57%, #3984DD 94.39%)",
WebkitBackgroundClip: "text",
backgroundClip: "text",
color: "transparent"
}}>{children}</span>
</Typography>
);
}
export default memo(GradientTypography);
|
const {router} = require("../../config/expressconfig");
const {sql} = require("../../config/dbConfig")
const randomstring = require("randomstring");
const {sendMailForEmailVerification} = require("../Functions/sendMail");
const {url} = require("../../config/serverRootUrl");
const {knex} = require('../../knex/knex')
const bcrypt = require('bcrypt')
let userRegistration = router.post("/register/userSelection", (req, res) => {
bcrypt.hash(req.body.password, 10, async (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
if (req.body.userType === "Normal User") {
let {
userName, email, userType,
userToken = randomstring.generate(),
registrationDate = new Date
} = req.body;
let user = await knex('user').where({email}).select();
if (!user.length) {
let file = url + "/verify-userSelection/" + email;
sendMailForEmailVerification(email, userName, file);
if (user = await knex('user').insert({
userName,
email,
password: hash,
userType,
userToken,
registrationDate
}))
return res.json({message: "USER REGISTERED SUCCESSFULLY", responseCode: 200, user});
}
return res.json({message: "USER OF THIS EMAIL IS ALREADY EXISTS", responseCode: 404, user: user})
} else {
let {
businessABN,
businessName,
businessProfession,
email,
location,
mobile,
userName,
userType,
userToken = randomstring.generate(),
registrationDate = new Date()
} = req.body;
let user = await knex('user').where({email}).select();
if (!user.length) {
if (user = await knex('user').insert({
businessABN, businessName, businessProfession,
email, location, mobile, password: hash, userName, userType, userToken, registrationDate
})) {
return res.json({message: "USER REGISTERED SUCCESSFULLY", responseCode: 200, user});
}
}
return res.json({message: "USER OF THIS EMAIL IS ALREADY EXISTS", responseCode: 404, user})
}
}
})
});
module.exports = {userRegistration}
|
import React, { Component } from 'react';
import Humidity from './Humidity';
import { cities } from './cities';
class App extends Component {
constructor() {
super()
this.state = {
city: cities,
humidity: ''
}
}
render() {
return (
<div>
<Humidity city={cities[0].city} humidity={this.state.humidity} />
</div>
);
}
}
export default App;
|
'use strict';
module.exports = require('../../../lib/browser/appConfig');
|
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, TouchableOpacity, Dimensions } from 'react-native';
import {
Input,
Text,
Avatar,
Accessory,
BottomSheet,
ListItem,
} from 'react-native-elements';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import ImagePicker from 'react-native-image-crop-picker';
import firestore from '@react-native-firebase/firestore';
import storage from '@react-native-firebase/storage';
const dimensions = Dimensions.get('window');
const EditProfile = ({ route, navigation }) => {
const [isVisible, setIsVisible] = useState(false);
const [changed, setChanged] = useState(false);
const [userDetails, setUserDetails] = useState({
id: '',
avatar:
'https://image.freepik.com/free-vector/businessman-character-avatar-isolated_24877-60111.jpg',
name: '',
description: '',
});
const { user } = route.params;
const UserCollection = firestore().collection('Users');
useEffect(() => {
setUserDetails(user);
}, []);
const list = [
{
title: 'Click a Picture',
icon: {
name: 'camera',
type: 'antdesign',
color: '#111',
size: 25,
},
titleStyle: { fontSize: 20 },
onPress: () => imageSelector('camera'),
},
{
title: 'Choose from existing pictures',
icon: {
name: 'photo',
type: 'font-awesome',
color: '#111',
size: 25,
},
titleStyle: { fontSize: 20 },
onPress: () => imageSelector('picker'),
},
{
title: 'Cancel',
containerStyle: { backgroundColor: 'red' },
titleStyle: { color: 'white', fontSize: 20 },
icon: {
name: 'cancel',
type: 'material-community',
color: 'white',
size: 25,
},
onPress: () => setIsVisible(false),
},
];
const imageSelector = (src) => {
setChanged(true);
setIsVisible(false);
const storageReference = storage().ref(`/${userDetails.id}/dp.jpg`);
if (src === 'camera') {
ImagePicker.openCamera({
cropping: true,
})
.then(async (image) => {
const upload = storageReference.putFile(image.path);
upload.then(async () => {
const url = await storageReference.getDownloadURL();
console.log(url);
setUserDetails((prev) => {
return { ...prev, avatar: url };
});
});
})
.catch((err) => console.error(err));
} else {
ImagePicker.openPicker({
cropping: true,
})
.then(async (image) => {
const upload = storageReference.putFile(image.path);
upload.then(async () => {
const url = await storageReference.getDownloadURL();
// console.log(url);
setUserDetails((prev) => {
return { ...prev, avatar: url };
});
await UserCollection.doc(userDetails.id).update({
dp: url,
});
});
})
.catch((err) => console.error(err));
}
};
const handleSaveChanges = async () => {
await UserCollection.doc(userDetails.id)
.update({
name: userDetails.name,
description: userDetails.description,
dp: userDetails.avatar,
})
.then(() => navigation.goBack());
};
return (
<View style={styles.mainView}>
<View style={styles.avaterWrapper}>
<Avatar
rounded
source={{
uri: userDetails.avatar,
}}
size="xlarge"
title="DP"
imageProps={{ resizeMode: 'contain' }}
activeOpacity={0.5}
overlayContainerStyle={{ backgroundColor: 'white' }}
onPress={() => setIsVisible(true)}>
<Accessory size={30} />
</Avatar>
</View>
<View style={styles.inputWrapper}>
<Input
label="NAME"
leftIcon={{ type: 'entypo', name: 'user', color: 'white' }}
inputStyle={{ color: 'white' }}
inputContainerStyle={{ borderColor: '#b3b3b3' }}
labelStyle={{ color: '#b3b3b3', letterSpacing: 1 }}
value={userDetails.name}
onChangeText={(value) => {
setChanged(true);
setUserDetails((prev) => {
return { ...prev, name: value };
});
}}
/>
</View>
<View style={styles.inputWrapper}>
<Input
label="DESCRIPTION"
leftIcon={{
type: 'font-awesome-5',
name: 'pencil-alt',
color: 'white',
}}
inputStyle={{ color: 'white' }}
inputContainerStyle={{ borderColor: '#b3b3b3' }}
labelStyle={{ color: '#b3b3b3', letterSpacing: 1 }}
value={userDetails.description}
onChangeText={(value) => {
setChanged(true);
setUserDetails((prev) => {
return { ...prev, description: value };
});
}}
/>
</View>
<View>
<TouchableOpacity
style={styles.buttonstyle}
disabled={!changed}
onPress={() => handleSaveChanges()}>
<View style={styles.saveButtonWrapper}>
<FontAwesome5 name="save" color="white" size={25} />
<Text
style={{
fontFamily: 'Arial',
fontSize: 20,
color: 'white',
marginLeft: 10,
}}>
Save Changes
</Text>
</View>
</TouchableOpacity>
</View>
<BottomSheet
isVisible={isVisible}
containerStyle={{
backgroundColor: 'rgba(222.5, 222.25, 222, 0.5)',
}}>
{list.map((l, i) => (
<ListItem
key={i}
containerStyle={l.containerStyle}
onPress={l.onPress}>
<Avatar rounded icon={l.icon} />
<ListItem.Content>
<ListItem.Title style={l.titleStyle}>
{l.title}
</ListItem.Title>
</ListItem.Content>
</ListItem>
))}
</BottomSheet>
</View>
);
};
export default EditProfile;
const styles = StyleSheet.create({
mainView: {
backgroundColor: '#111',
paddingHorizontal: 10,
paddingTop: 10,
height: dimensions.height,
width: dimensions.width,
},
avaterWrapper: {
width: dimensions.width,
justifyContent: 'center',
alignItems: 'center',
},
inputWrapper: {
textAlign: 'center',
paddingBottom: 30,
flexDirection: 'row',
},
saveButtonWrapper: {
textAlign: 'center',
flexDirection: 'row',
},
buttonstyle: {
alignItems: 'center',
borderWidth: 1.5,
borderColor: 'white',
borderRadius: 10,
paddingVertical: 10,
},
actionView: {
justifyContent: 'center',
alignItems: 'center',
marginVertical: 10,
},
button: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 10,
width: '90%',
borderRadius: 7,
marginVertical: 5,
},
buttonText: {
fontSize: 20,
color: 'white',
},
buttonIcon: {
marginRight: 5,
},
});
|
export const GET_CATEGORY = 'GET_CATEGORY';
export const getCategory = (category) => ({
type: GET_CATEGORY,
category,
});
|
var Schema = function ( Schema ){
/**
* Module dependencies.
* @private
*/
var ObjectId = Schema.ObjectId;
var Models = {
User: new Schema({
email : { type : String, required : true },
password : { type : String, required : true },
first_name : { type : String, required : false },
last_name : { type : String, required : false },
is_sys_admin : { type : Boolean, default : false },
is_locked : { type : Boolean, default : false },
pwd_try_error : { type : Number, default : 0 },
verify_code : { type : String, default : UTILS.uid.bind( UTILS, 12 ) },
is_verified : { type : Boolean, default : false },
last_login : { type : Date },
create_at : { type : Date, default : Date.now },
update_at : { type : Date, default : Date.now }
}),
Category : new Schema({
name : { type : String, required : true },
order : { type : Number, default : 9999 },
create_at : { type : Date, default : Date.now },
update_at : { type : Date, default : Date.now }
}),
Post : new Schema({
title : { type : String, required : true },
body : { type : String, required : true },
user_id : { type : ObjectId, required : true, ref : 'User' },
board : { type : ObjectId, required : true, ref : 'Board' },
reply_to : { type : ObjectId, ref : 'Post' },
tags : [{ type : ObjectId, ref : 'Tag' }],
comments : [{ type : ObjectId, ref : 'Comment' }],
create_at : { type : Date, default : Date.now },
update_at : { type : Date, default : Date.now }
}),
Board: new Schema({
name : { type : String, required : true },
admin : { type : ObjectId, ref : 'User' },
order : { type : Number, default: 9999 },
category : { type : ObjectId, ref : 'Category' },
latest_post : { type : ObjectId, ref : 'Post' },
posts_count : { type : Number, default : 0 },
create_at : { type : Date, default : Date.now },
update_at : { type : Date, default : Date.now }
}),
Tag : new Schema({
name : { type : String, required : true },
create_at : { type : Date, default : Date.now },
update_at : { type : Date, default : Date.now }
}),
};
// auto update `updated_at` on save
Object.keys( Models ).forEach( function ( model ){
if( Models[ model ].tree.updated_at !== undefined ){
Models[ model ].pre( 'save', function ( next ){
this.updated_at = this.isNew?
this.created_at :
Date.now();
next();
});
}
});
return Models;
};
/**
* Exports module.
*/
module.exports = Schema;
|
/*
Implement a function called areThereDuplicates which accepts a variable number of arguments and checks whether there are any duplicates among the arguments passed in. You can solve this using the frequency counter pattern OR the multiple pointers pattern.
*/
function areThereDuplicates() {
let frequency = {};
for (let value of arguments) {
frequency[value] = (frequency[value] || 0) + 1;
}
for (let key in frequency) {
if (frequency[key] > 1) return true;
}
return false;
}
console.log(areThereDuplicates(1, 2, 3)); //false
console.log(areThereDuplicates(1, 2, 2)); //true
console.log(areThereDuplicates("a", "b", "c", "a")); //true
|
import React from 'react';
import HeaderComponent from './Header';
import BodyComponent from './Body';
import WarningComponent from './Warning';
class App extends React.Component {
render() {
return (
<div>
<HeaderComponent />
<BodyComponent />
<WarningComponent />
</div>
);
}
}
export default App;
|
module.exports = {
"repositories": [
require(__dirname + "/repositories/BrewRepositoryTest.js")
],
"resources": [
require(__dirname + "/resources/BrewTest.js")
]
}
|
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtIcon, AtCard } from 'taro-ui'
import PropTypes from 'prop-types'
import thumbPNG from '~assets/images/money.png'
import './index.scss'
class CardList extends Component {
static propTypes = {
bills: PropTypes.array
}
static defaultProps = {
bills: []
}
render() {
const { bills } = this.props
const emptyBox = (
<View className='empyt-box'>
<AtIcon value='message' size='50' color='#fff'></AtIcon>
<Text>没有数据</Text>
</View>
)
const cardBox = bills.map(bill => (
<View key={bill.FNumber} className='bill-card'>
<AtCard
// note='马静敏'
extra={`¥${Number(bill.FAmount).toFixed(2)}`}
title={bill.FBizDate}
thumb={thumbPNG}
>
<Text>单据编号:{bill.FNumber}</Text>
</AtCard>
</View>
))
return (
<View className='container'>
{bills.length > 0 ? cardBox : emptyBox}
</View>
)
}
}
export default CardList
|
import React from 'react';
const ContentBox = ({ children }) => {
return <div className='mx-6 mb-6 border-[0.5px] rounded-lg border-grey-150'>{children}</div>;
};
export default ContentBox;
|
const { createMacro, MacroError } = require('babel-plugin-macros');
const { addNamed } = require('@babel/helper-module-imports');
module.exports = createMacro(gooberMacro);
function gooberMacro({ references, babel, state }) {
const program = state.file.path;
if (references.default) {
throw new MacroError('goober.macro does not support default import');
}
// Inject import {...} from 'goober'
Object.keys(references).forEach((refName) => {
const id = addNamed(program, refName, 'goober');
references[refName].forEach((referencePath) => {
referencePath.node.name = id.name;
});
});
const t = babel.types;
const styledReferences = references.styled || [];
styledReferences.forEach((referencePath) => {
const type = referencePath.parentPath.type;
if (type === 'MemberExpression') {
const node = referencePath.parentPath.node;
const functionName = node.object.name;
let elementName = node.property.name;
// Support custom elements
if (/[A-Z]/.test(elementName)) {
elementName = elementName.replace(/[A-Z]/g, '-$&').toLowerCase();
}
referencePath.parentPath.replaceWith(
t.callExpression(t.identifier(functionName), [t.stringLiteral(elementName)])
);
}
});
}
|
/**
* @Author:hgq
* @Describe:
*/
/**
* 获取时间--时分秒 14:00:00
* @param timeStamp
* @returns {string}
*/
export function getTime(timeStamp = new Date().getTime()) {
let date = new Date(timeStamp);
return (date.getHours() + ':' + (date.getMinutes()) + ':' + date.getSeconds())
.replace(/([\-\: ])(\d{1})(?!\d)/g, '$10$2');
}
/**
* 获取日期--年月日 2019-06-01
* @param timeStamp
* @returns {string}
*/
export function getDate(timeStamp = new Date().getTime()) {
let date = new Date(timeStamp);
return (date.getFullYear() + ':' + (date.getMonth() + 1) + ':' + date.getDate())
.replace(/([\-\: ])(\d{1})(?!\d)/g, '$10$2');
}
/**
* 拷贝数组
* @param arr 数组
* @returns {Array}
*/
export function deepCopyArray(arr) {
let out = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) {
out[i] = deepCopyArray(arr[i]);
} else if (arr[i] instanceof Object) {
out[i] = JSON.parse(JSON.stringify(arr[i]));
} else {
out[i] = arr[i];
}
}
return out;
}
/**
* 获取一个区间内的随机数
* @param min 最小值
* @param max 最大值
* @returns {string}
*/
export function getRandomFrom(min, max) {
return (Math.random() * (max - min) + min).toFixed(1);
}
/**
* 获取字符串字节数(汉字算两个字符,字母数字算一个)
* @param str 字符串
* @returns {number}
*/
export function getByteLen(str) {
let len = 0;
for (let i = 0; i < str.length; i++) {
let a = str.charAt(i);
if (a.match(/[^\x00-\xff]/ig) != null) {
len += 2;
} else {
len += 1;
}
}
return len;
}
/**
* 遍历对象obj,把key和value作为参数,调用fn函数
* @param obj 传入的对象
* @param fn 需要执行的函数
*/
export const forEachObject = (obj, fn) => {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
//以key和value作为参数调用fn函数
fn(key, obj[key]);
}
}
};
/**
* Array.every的高阶函数,遍历数组(for ... of),并执行fn函数,当有一个fn()返回false时,every返回false
* @param array 传入的数组
* @param fn 需要执行的函数,必须返回boolean
* @returns {boolean}
*/
export const every = (array, fn) => {
let result = true;
for (const value of array) result = result && fn(value);
return result;
};
/**
* Array.some的高阶函数,遍历数组(for ... of),并执行fn函数,当有一个fn()返回true时,every返回true
* @param array 传入的数组
* @param fn 需要执行的函数,必须返回boolean
* @returns {boolean}
*/
export const some = (array, fn) => {
let result = false;
for (const value of array) result = result || fn(value);
return result;
};
/**
* Array.sort的高阶函数,根据比较数据的某个property进行排序
* @param property 进行比较的property
* @returns {function(*, *): number}
*/
export const sortBy = (property) => {
return (a, b) => {
return (a[property] < b[property]) ? -1 : (a[property > b[property]]) ? 1 : 0;
};
};
/**
* Array.map 方法
* @param array 数组
* @param fn 回调函数,
* @returns {Array}
*/
export const map = (array, fn) => {
let results = [];
for (const value of array) {
results.push(fn(value));
}
return results;
};
/**
* Array.filter 方法
* @param array 数组
* @param fn 回调函数 返回boolean
* @returns {Array}
*/
export const filter = (array, fn) => {
let results = [];
for (const value of array) {
fn(value) && results.push(value);
}
return results;
};
/**
* 多维数组变为1维数组
* @param array 数组
* @returns {*[]}
*/
export const flatten = (array) => {
return [].concat(...array.map(x => Array.isArray(x) ? flatten(x) : x));
};
/**
* Array.reduce
* @param array 数组
* @param fn 回调函数
* @param initialValue 累加器的初始值
* @returns {*}
*/
export const reduce = (array, fn, initialValue) => {
let accumlator;
if (initialValue !== undefined) {
accumlator = initialValue;
} else {
accumlator = array[0];
}
if (initialValue === undefined) {
for (let i = 1; i < array.length; i++) {
accumlator = fn(accumlator, array[i]);
}
} else {
for (const value of array) {
accumlator = fn(accumlator, value);
}
}
return accumlator;
};
/**
* 让某个函数只执行一次,如支付请求,
* @param fn 执行的函数
* @returns {function(): undefined}
*/
export const once = (fn) => {
let done = false;
return function() {
return done ? undefined : (done = true, fn.apply(this, arguments));
};
};
/**
* 缓存函数,新建空对象,如果对象中存在某个值,返回对应的值,
* 否则,使用新的输入作为key,fn的结果作为value,存入对象中,提高效率
* 例子:提高阶乘函数的效率
* @param fn 执行的函数
* @returns {function(*=): *}
*/
export const memoized = (fn) => {
const lookUpTable = {};
return (arg) => lookUpTable[arg] || (lookUpTable[arg] = fn(arg));
};
/**
* 防抖和节流
* 相同:在不影响客户体验的前提下,将频繁的回调函数,进行次数缩减.避免大量计算导致的页面卡顿.
* 不同:防抖是将多次执行变为最后一次执行,节流是将多次执行变为在规定时间内只执行一次.
*/
/**
* 防抖(窗口的resize、scroll,输入框内容校验)---当持续触发事件时,debounce 会合并事件且不会去触发事件,当一定时间内没有触发再这个事件时,才真正去触发事件
* 常见应用:输入框内容校验;按钮点击(收藏,点赞)
* @param fn 需要执行的函数
* @param delay 延迟执行的时间
* @param immediate true 表立即执行,false 表非立即执行
* @returns {Function}
*/
export const debounce = (fn, delay, immediate) => {
let timeout = null;
return function() {
let context = this;
let args = arguments;
if (!timeout) clearTimeout(timeout);
if (immediate) {
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, delay);
if (callNow) fn.apply(context, args);
} else {
timeout = setTimeout(() => {
fn.apply(context, args);
}, delay);
}
};
};
/**
* 节流:当持续触发事件时,在规定时间段内只能调用一次回调函数。如果在规定时间内又触发了该事件,则什么也不做,也不会重置定时器.
* 时间戳+定时器版: 实现第一次触发可以立即响应,结束触发后也能有响应 (该版才是最符合实际工作需求)
* @param fun
* @param delay
* @returns {Function}
*/
export const throttle = (fun, delay = 500) => {
let timer = null;
let previous = 0;
return function(args) {
let now = Date.now();
let remaining = delay - (now - previous); //距离规定时间,还剩多少时间
let that = this;
let _args = args;
clearTimeout(timer); //清除之前设置的定时器
if (remaining <= 0) {
fun.apply(that, _args);
previous = Date.now();
} else {
timer = setTimeout(function() {
fun.apply(that, _args);
}, remaining); //因为上面添加的clearTimeout.实际这个定时器只有最后一次才会执行
}
};
};
/**
* 柯里化函数
* @param fn 传入的函数
* @returns {curriedFn}
*/
export const curry = (fn) => {
/*检验fn是否是函数,如果不是,则抛出异常*/
if (typeof fn !== 'function') {
throw Error('No Function Provided');
}
return function curriedFn(...args) {
/*检查通过args传入的参数长度是否小于函数参数列表的长度,如果小于,则使用apply函数递归调用curriedFn*/
if (args.length < fn.length) {
return function() {
return curriedFn.apply(null, args.concat([].slice.call(arguments)));
};
}
return fn.apply(null, args);
};
};
/**
* 组合与管道---把每个函数的输出作为输入传给另一个函数
* 组合:右侧的函数最先执行,把输出作为下一个函数的输入,
* 管道:左侧的函数最先执行,把输出作为下一个函数的输入
* @param fns 传入的函数
* @returns {function(*=): *}
*/
// export const compose = (...fns) => (value) => reduce(fns.reverse(), (acc, fn) => fn(acc), value);
export const piep = (...fns) => (value) => reduce(fns, (acc, fn) => fn(acc), value);
export const compose = (...fns) => {
if (fns.length === 0) {
return arg => arg;
}
if (fns.length === 1) {
return fns[0];
}
return fns.reduce((a, b) => (...args) => a(b(...args)));
};
|
const mongoose = require('mongoose');
const beautifyUnique = require('mongoose-beautiful-unique-validation');
mongoose.Promise = require('bluebird');
// mongoose.connect('mongodb://localhost/test');
const config = require('../config/index.js');
const DATABASE_URL = config.DATABASE_URL;
mongoose.connect(DATABASE_URL);
const db = mongoose.connection;
db.on('error', () => {
console.log('mongoose connection fail ._____.');
});
db.once('open', () => {
console.log('mongoose connection success! b(^.~)z');
});
let songSchema = mongoose.Schema({
track_id: {type: Number, unique: true},
track_name: String,
artist_name: String,
album_coverart_100x100: String,
album_coverart_350x350: String,
album_coverart_500x500: String,
album_coverart_800x800: String,
lyrics: String,
spotify_uri: String
});
songSchema.plugin(beautifyUnique);
const Song = mongoose.model('Song', songSchema);
let watsonSchema = mongoose.Schema({
track_id: { type: Number, unique: true },
// Emotion Tone
anger: Number,
disgust: Number,
fear: Number,
joy: Number,
sadness: Number,
// Language Tone
analytical: Number,
confident: Number,
tentative: Number,
// Social Tone
openness: Number,
conscientiousness: Number,
extraversion: Number,
agreeableness: Number,
emotionalrange: Number
});
watsonSchema.plugin(beautifyUnique);
const Watson = mongoose.model('Watson', watsonSchema);
let userSchema = mongoose.Schema({
username: {type: String, unique: true},
password: String,
songs: [Number]
});
userSchema.plugin(beautifyUnique);
const User = mongoose.model('User', userSchema);
module.exports.Song = Song;
module.exports.Watson = Watson;
module.exports.User = User;
|
'use strict'
const AppData = require('./lib/AppData.js')
const bilibili = require('./lib/bilibili.js')
const saveClothes = require('./lib/saveClothes.js')
const fs = require('fs')
async function main(ClothesName){
//AppData.lastCheckTime()
let closet = []
if(!ClothesName){
closet = await bilibili.getAllClothesName()//设置了延迟查询
} else {
closet.push({
host: 's1.hdslb.com',
ClothesName,
path: 'bfs/static/blive/live-assets/haruna'
})
}
let haveNewClothes = saveClothes.contrastCloset(closet)
if(haveNewClothes){
//下载了新衣服,准备提交
AppData.lastCheckTime()
let clothesList = ''
for(let clothes of AppData.readData('closet')){
clothesList +=`${clothes}\n\n`
}
let md = `# live2d-2233-clothes\n\n> 一个自动爬取B站直播间2233衣服的项目\n\n## 最后发现新衣服时间 ${AppData.readData('lastCheckTime')}\n\n## 列表\n\n${clothesList}\n\n[保存地址](./dist)`
fs.writeFile('./README.md',md,(err)=>{
if(err){
console.log('更新readme出错'+err)
}
})
}
}
main()
|
const employeeRoutes = require("./employee");
const managerRoutes = require("./manager");
const newemployeeRoutes = require("./newemployee")
const loginRoutes = require("./users")
const constructorMethod = app => {
app.use("/", loginRoutes)
app.use("/employee", employeeRoutes);
app.use("/manager", managerRoutes);
app.use("/newemployee", newemployeeRoutes)
// app.use("*", (req, res) => {
// res.status(404).json({error: "invalid url please check url"});
// });
}
module.exports = constructorMethod;
|
/*==========================================================
Author : Naveen Adepu.
Date Created: 7 Nov 2016
Description : To handle the service to for ticket assignment to individual..
Change Log
s.no date author description
===========================================================*/
dashboard.service('manageticketService', ['$http', '$q', 'Flash', 'apiService', function ($http, $q, Flash, apiService) {
var manageticketService = {};
var getCatogories = function ( useremail ) {
var deferred = $q.defer();
apiService.get("ticket/getcategories/", { useremail : useremail }).then(function (response) {
if (response)
deferred.resolve(response);
else
deferred.reject("Something went wrong while processing your request. Please Contact Administrator.");
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
};
var gettickethistories = function(ticketid) {
var deferred = $q.defer();
apiService.get("ticket/gethistories/", { ticketid : ticketid }).then(function (response) {
if (response)
deferred.resolve(response);
else
deferred.reject("Something went wrong while processing your request. Please Contact Administrator.");
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
};
var gettickets = function (category) {
//return [1,2,3,4,5,6,7,8,9];
var deferred = $q.defer();
apiService.get("ticket/gettickets", { category : category }).then(function (response) {
if (response)
deferred.resolve(response);
else
deferred.reject("Something went wrong while processing your request. Please Contact Administrator.");
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
};
var updatetickets = function(object,parameters){
var deferred = $q.defer();
apiService.update("ticket/updatetickets",object,parameters).then(function (response) {
if (response)
deferred.resolve(response);
else
deferred.reject("Something went wrong while processing your request. Please Contact Administrator.");
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
};
var createTickethistory = function ( pmessage ) {
var deferred = $q.defer();
apiService.create("myTickets/createTickethistory", { pmessage : pmessage }).then(function (response) {
if (response)
deferred.resolve(response);
else
deferred.reject("Something went wrong while processing your request. Please Contact Administrator.");
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
};
manageticketService.updatetickets = updatetickets;
manageticketService.gettickets =gettickets ;
manageticketService.getCatogories = getCatogories;
manageticketService.gettickethistories = gettickethistories;
// manageticketService.getmyTickethistories = getmyTickethistories;
// manageticketService.createTickethistory = createTickethistory;
return manageticketService;
}]);
|
$(document).ready(function(e) {
$('#btnCerrarSesion').click(function(e) {
$.post('../negocio/logout.php', { },
function() { window.location='../'; });
});
});
|
'use strict';
module.exports = function(app) {
var product = require('../controllers/userController');
app.route('/rest/v1/Users')
.get(product.list_all_users)
.post(product.create_a_user);
app.route('/rest/v1/Users/:username')
.get(product.read_a_user)
.put(product.update_a_user)
.delete(product.delete_a_user);
};
|
import React from 'react';
import { connect } from 'react-redux';
import { initialize } from '../../store/app/actions';
import { getIsInitialized } from '../../store/app/selectors';
import App from '../../App';
const AppContainer = props => {
return <App {...props} />;
};
const mapStateToProps = state => ({
isInitialized: getIsInitialized(state)
});
const mapDispatchToProps = dispatch => ({
initialize: init => dispatch(initialize(init))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(AppContainer);
|
const { Course } = require('./course');
const { User } = require('../user/user');
const { Section } = require('./section');
const { Video } = require('./video');
const { Quiz } = require('./quiz');
const { PictureQuiz } = require('./pictureQuiz');
const { MatchingGame } = require('./matchingGame/matchingGame');
const { MatchingGameAnswer } = require('./matchingGame/matchingGameAnswer');
const { MatchingGameQuestion } = require('./matchingGame/matchingGameQuestion');
const { CrunchChallenge } = require('./crunchChallenge');
const { CodingChallenge } = require('./codingChallenge');
const { CodingProject } = require('./codingProject');
const { Autocomplete } = require('../global/autocomplete');
const { Payout } = require('../global/payout');
const { Review } = require('../global/review');
exports.allCourseTypes = `
${Course}
${User}
${Section}
${Video}
${Quiz}
${PictureQuiz}
${MatchingGame}
${MatchingGameQuestion}
${MatchingGameAnswer}
${CrunchChallenge}
${CodingChallenge}
${CodingProject}
${Autocomplete}
${Payout}
${Review}
`;
|
import React, { Component } from 'react';
import { Link } from "react-router-dom";
import ThumbInput from '../ThumbInput/ThumbInput';
import Modal from "../Modal/Modal";
import makeup from '../Images/makeup.svg';
import api from "../API/api";
class ProdutoEditavel extends Component {
state = {
dadosProduto: this.props.dados,
id: this.props.dados.id,
img: this.props.dados.img,
titulo: this.props.dados.titulo,
marca: this.props.dados.marca,
preco: this.props.dados.preco,
promocao: this.props.dados.promocao,
novidade: this.props.dados.novidade,
estoque: this.props.dados.estoque,
tipoProduto: this.props.dados.tipoProduto,
descricao: this.props.dados.descricao,
comprimento: this.props.dados.comprimento,
altura: this.props.dados.altura,
largura: this.props.dados.largura,
peso: this.props.dados.peso,
newImage: null,
alert: null,
atualizando: false,
}
cover = (e) => {
e.target.src = makeup;
e.target.width = 60;
}
chamarAlerta = (msg) => {
this.setState({
alert: msg,
}, () => {
let alertDiv = document.getElementById("alert-div");
if (alertDiv) alertDiv.scrollIntoView();
});
}
CliqueVerDetalhes = (ProdutoId) => { /* função para abrir o modal dos produtos*/
const modal = document.getElementById(ProdutoId);
modal.classList.add('mostrar');
modal.addEventListener('click', (e) => {
if (e.target.id === ProdutoId || e.target.className === 'fechar') {
modal.classList.remove('mostrar');
}
});
window.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
modal.classList.remove('mostrar');
}
});
}
/* funções para aparecer e desaparecer o botão Ver Detalhes quando o mouse estiver em cima do produto */
AparecerBotaoDetalhes = (BotaoId) => {
const botao = document.getElementById(BotaoId);
botao.classList.add('mostrarBotao');
}
DesaparecerBotaoDetalhes = (BotaoId) => {
const botao = document.getElementById(BotaoId);
botao.classList.remove('mostrarBotao');
}
// Remover item do banco de dados
removerItem = async (id) => {
//PopUp de confimação
const token = localStorage.getItem("@stbl/admin/user");
const res = await api.post("/removerproduto", { "_id": id }, { headers: { authorization: token } });
if (res.data._id) {
alert("Produto foi removido com êxito! Esta pagina será recarregada...");
window.location.reload();
} else {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!")
}
}
// Salvar atualizações feitas
salvar = async () => {
let { titulo, marca, preco, estoque, descricao, tipoProduto,
comprimento, altura, largura, peso, promocao, novidade } = this.state;
let erro = false;
//Verificando se algum campo foi deixado vazio antes de atualizar dados:
if (titulo && marca && preco && estoque && descricao && tipoProduto
&& comprimento && altura && largura && peso
&& titulo.toString().trim() && marca.toString().trim() && preco.toString().trim()
&& estoque.toString().trim() && descricao.toString().trim() && tipoProduto.toString().trim()
&& comprimento.toString().trim() && altura.toString().trim() && largura.toString().trim()
&& peso.toString().trim()) {
titulo = titulo.toString();
if (titulo.length > 100) return this.chamarAlerta("O título deve até 100 carecteres (PagSeguro)");
marca = marca.toString();
if (isNaN(preco) || preco < 0) return this.chamarAlerta("Formato inválido para preço!");
if (preco > 10000) return this.chamarAlerta("Valor do produto não de exceder R$ 10.000,00 (Correios)");
preco = parseFloat(preco).toFixed(2);
if (isNaN(estoque) || estoque < 0)
return this.chamarAlerta("Formato inválido para quantidade em estoque!");
estoque = parseFloat(estoque);
if (!Number.isInteger(estoque))
return this.chamarAlerta("Formato inválido para quantidade em estoque!");
tipoProduto = tipoProduto.toString();
if (isNaN(comprimento) || comprimento < 0)
return this.chamarAlerta("Formato inválido para comprimento de embalagem (Correios)! Insira um número válido!");
comprimento = parseFloat(comprimento);
if (!Number.isInteger(comprimento))
return this.chamarAlerta("Formato inválido para comprimento de embalagem (Correios)! Insira um valor inteiro!");
if (comprimento > 105)
return this.chamarAlerta("O comprimento não pode exceder 105cm (Correios).");
if (isNaN(altura) || altura < 0)
return this.chamarAlerta("Formato inválido para altura de embalagem (Correios)!");
altura = parseFloat(altura);
if (!Number.isInteger(altura))
return this.chamarAlerta("Formato inválido para altura de embalagem (Correios)! Insira um valor inteiro!");
if (altura > 105)
return this.chamarAlerta("A altura não pode exceder 105cm (Correios).");
if (isNaN(largura) || largura < 0)
return this.chamarAlerta("Formato inválido para largura de embalagem (Correios)!");
largura = parseFloat(largura);
if (!Number.isInteger(largura))
return this.chamarAlerta("Formato inválido para largura de embalagem (Correios)! Insira um valor inteiro!");
if (largura > 105)
return this.chamarAlerta("A largura não pode exceder 105cm (Correios).");
if (comprimento + altura + largura > 200)
return this.chamarAlerta("A soma resultante do comprimento + largura + altura não deve superar a 200cm (Correios)")
if (isNaN(peso) || peso < 0)
return this.chamarAlerta("Formato inválido para peso do produto (Correios)!");
peso = parseFloat(peso);
if (!Number.isInteger(peso))
return this.chamarAlerta("Formato inválido para peso do produto (Correios)! Insira um valor inteiro!");
if (peso > 30000) return this.chamarAlerta("O produto deve ter peso máximo de até 30kg (Correios)!");
const token = localStorage.getItem("@stbl/admin/user");
if (this.state.newImage !== null) {
this.setState({ atualizando: true });
const id = this.state.id;
const data = new FormData();
data.append('img', this.state.newImage);
const res = await api.post("/atualizarimagem", data, {
headers: {
authorization: token,
id
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (titulo !== this.props.dados.titulo && !erro) {
const res = await api.post("/atualizartitulo", { "id": this.state.id, "novo_titulo": titulo }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (marca !== this.props.dados.marca && !erro) {
const res = await api.post("/atualizarmarca", { "id": this.state.id, "nova_marca": marca }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (preco !== this.props.dados.preco && !erro) {
const res = await api.post("/atualizarpreco", { "id": this.state.id, "novo_preco": preco }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (estoque !== this.props.dados.estoque && !erro) {
const res = await api.post("/atualizarestoque", { "id": this.state.id, "novo_estoque": estoque }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (descricao !== this.props.dados.descricao && !erro) {
const res = await api.post("/atualizardescricao", { "id": this.state.id, "nova_descricao": descricao }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (tipoProduto !== this.props.dados.tipoProduto && !erro) {
const res = await api.post("/atualizartipo", { "id": this.state.id, "novo_tipo": tipoProduto }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
promocao = promocao === 'on' || promocao === true ? true : false;
if (promocao !== this.props.dados.promocao && !erro) {
const res = await api.post("/atualizarpromocao", { "id": this.state.id, "promocao": promocao }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
novidade = novidade === 'on' || novidade === true ? true : false;
if (novidade !== this.props.dados.novidade && !erro) {
const res = await api.post("/atualizarnovidade", { "id": this.state.id, "novidade": novidade }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (comprimento !== this.props.dados.comprimento && !erro) {
const res = await api.post("/atualizarcomprimento", { "id": this.state.id, "novo_comprimento": comprimento }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (altura !== this.props.dados.altura && !erro) {
const res = await api.post("/atualizaraltura", { "id": this.state.id, "nova_altura": altura }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (largura !== this.props.dados.largura && !erro) {
const res = await api.post("/atualizarlargura", { "id": this.state.id, "nova_largura": largura }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (peso !== this.props.dados.peso && !erro) {
const res = await api.post("/atualizarpeso", { "id": this.state.id, "novo_peso": peso }, {
headers: {
authorization: token
}
});
if (!res.data.id) {
this.chamarAlerta("Erro inesperado... Tente novamente mais tarde!");
erro = true;
}
}
if (!erro) {
alert("Produto atualizado! Esta página será recarregada...");
window.location.reload(true);
}
this.setState({ atualizando: false });
} else {
this.chamarAlerta("Preencha todos os campos!");
}
}
atualizarInput = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
atualizarInputCheckbox = (e) => {
console.log(e.target.value)
let last = this.state[e.target.name];
this.setState({
[e.target.name]: last ? false : true,
})
}
imageInput = (e) => {
this.setState({ newImage: e.target.files[0] });
}
render() {
//Ids dinâmicos dependentes do local do produto para evitar conflito de modal
let ProdutoId = this.props.dados.id;
let BotaoId = ProdutoId + "Bta";
let BotaoModal = ProdutoId + "Btamodal";
let BotaoModalCancel = ProdutoId + "BtamodalCancel";
const categorias = ['Cuidados com a pele', 'Pincéis', 'Boca', 'Pó', 'Bases', 'Paletas', 'Olhos', 'Primer', 'Iluminador', 'Blushs', 'Fixador'];
return (
<div >
{/* Produto: imagem, marca, titulo, preço e botao de ver detalhes*/}
<div className="produto" onMouseOver={() => this.AparecerBotaoDetalhes(BotaoId)} onMouseOut={() => this.DesaparecerBotaoDetalhes(BotaoId)} >
<div>
<img src={this.props.dados.img} alt="img" className="imagemProduto" onError={this.cover} onClick={() => this.CliqueVerDetalhes(ProdutoId)} />
<div className="divbotaoVerDetalhes">
<button onClick={() => this.CliqueVerDetalhes(ProdutoId)} className="botaoVerDetalhes" id={BotaoId}>Editar</button>
</div>
</div>
<div className="descricaoProduto" onClick={() => this.CliqueVerDetalhes(ProdutoId)}>
<p className="marcadescricaoProduto">{this.props.dados.marca}</p>
<p className="titulodescricaoProduto">{this.props.dados.titulo}</p>
<p className="precodescricaoProduto">R${parseFloat(this.props.dados.preco).toFixed(2)}</p>
</div>
</div>
{/* Modal com as informações mais detalhadas do produto a serem editadas*/}
<div id={ProdutoId} className="modal-container">
<div className="modal admin-form">
<div><img src={this.props.dados.img} alt="img" className="imagemProdutoModal" onError={this.cover} /></div>
<div className="descricaoProdutoModal">
<p>
<b>Título:</b>
<input className='admin-form' type='text' value={this.state.titulo} name="titulo" onChange={this.atualizarInput} />
</p>
<p>
<b>Categoria:</b>
<select className='admin-form' type="text" placeholder="TIPO" name="tipoProduto" value={this.state.tipoProduto} onChange={this.atualizarInput}>
<option key={0} value={''}></option>
{
categorias.map(cat => {
return (<option key={cat} value={cat}> {cat} </option>)
})
}
</select>
</p>
<p>
<b>Marca:</b>
<input className='admin-form' type='text' value={this.state.marca} name="marca" onChange={this.atualizarInput} />
</p>
<p>
<b>Descrição:</b>
<textarea className='admin-form' type='text' value={this.state.descricao} name="descricao" onChange={this.atualizarInput} />
</p>
<p>
<b>Quantidade em estoque:</b>
<input className='admin-form' type='number' value={this.state.estoque} name="estoque" onChange={this.atualizarInput} />
</p>
<p>
<b>Preco (R$):</b>
<input className='admin-form' type='number' value={this.state.preco} name="preco" onChange={this.atualizarInput} />
</p>
<p>
<b>Em promoção:</b>
<input className='admin-form' type='checkbox' checked={this.state.promocao} name="promocao" onClick={this.atualizarInputCheckbox} />
</p>
<p>
<b>Novidade:</b>
<input className='admin-form' type='checkbox' checked={this.state.novidade} name="novidade" onClick={this.atualizarInputCheckbox} />
<em>Produtos marcados como novidade aparecem em destaque na sua página inicial.</em>
</p>
<p>
<b>IMAGEM:</b>
<ThumbInput onChange={this.imageInput} />
</p>
<p>
<b>Comprimento:</b>
<input className='admin-form' type='number' value={this.state.comprimento} name="comprimento" onChange={this.atualizarInput} />
</p>
<p>
<b>Altura (cm):</b>
<input className='admin-form' type='number' value={this.state.altura} name="altura" onChange={this.atualizarInput} />
</p>
<p>
<b>Largura (cm):</b>
<input className='admin-form' type='number' value={this.state.largura} name="largura" onChange={this.atualizarInput} />
</p>
<p>
<b>Peso (g):</b>
<input className='admin-form' type='number' value={this.state.peso} name="peso" onChange={this.atualizarInput} />
</p>
<button onClick={() => { this.salvar() }}>Enviar</button>
{this.state.atualizando ? <em> Enviando dados... </em> : null}
<button id={BotaoModal}>Remover item</button>
<Modal listenersId={[BotaoModal, BotaoModalCancel]} actived={false}>
<h3>Tem certeza que deseja remover este item?</h3>
<p>O produto será removido completamente do catálogo da loja virtual e não poderá ser recuperado!</p>
<div><button onClick={() => { this.removerItem(this.props.dados.id) }}>Continuar</button></div>
<div><button id={BotaoModalCancel} >Cancelar</button></div>
</Modal>
{
this.state.alert ?
(<div id="alert-div" className="alertacadastro">{this.state.alert}
<Link className="fecharalerta" onClick={() => this.setState({ alert: false })} to="#">X</Link>
</div>) : null
}
</div>
</div>
</div>
</div>
)
}
}
export default ProdutoEditavel;
|
/* eslint-disable no-nested-ternary */
import React from "react";
import styled from "styled-components";
import PropTypes from "prop-types";
const StyledArrow = styled.div`
display: flex;
position: absolute;
${(props) => (props.direction === "right" ? "right: 25px; top: 50%;" : "")};
${(props) => (props.direction === "left" ? "left: 25px; top: 50%;" : "")};
${(props) => (props.direction === "pause" ? "bottom: 65px; left: 48%" : "")};
${(props) => (props.direction === "play" ? "bottom: 65px; left: 48%" : "")};
${(props) => (props.playState ? "opacity: 0;" : "opacity: 1;")}
height: 50px;
width: 50px;
justify-content: center;
background: white;
border-radius: 50%;
cursor: pointer;
align-items: center;
transition: transform ease-in 0.1s;
&:hover {
transform: scale(1.1);
}
img {
transform: translateX(
${(props) =>
props.direction === "left"
? "-2"
: props.direction === "right"
? "2"
: props.direction === "play"
? "3"
: "0"}px
);
&:focus {
outline: 0;
}
}
`;
const Arrow = ({
direction,
handleClick,
playState,
wrapperProps,
...imgProps
}) => {
let icon;
switch (direction) {
case "right":
icon =
"https://img2.pngio.com/arrow-arrow-right-chevron-chevronright-right-right-icon-icon-arrow-right-png-512_512.png";
break;
case "left":
icon =
"https://cdn1.iconfinder.com/data/icons/general-ui-outlined-thick/24/chevron-left-512.png";
break;
case "pause":
icon =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAPFBMVEX///8AAABhYWGxsbG0tLQwMDBHR0fKysrt7e1wcHC7u7tsbGyQkJCkpKReXl4VFRU6Ojr19fVAQEAeHh4NFjK4AAABjklEQVR4nO3SW2rDQBBFQcuxZcvvx/73mo/G4BCQJpA7JFBnAZeuYVYrSZIkSZIkSZKk/9953C512S2u7C6LK+O5g+Z7++vQ0rQwMzWtXPddTF+7NZ02DKfZlVPjyq2T6q1N42nDcJ9ZuTevbLrJXh2bbzvMrByaV47dZK/Wv/L6H80r626yV4SEFSFhMkLCipAwGSFhRUiYjJCwIiRMRkhYERImIySsCAmTERJWhITJCAkrQsJkhIQVIWEyQsKKkDAZIWFFSJiMkLAiJExGSFgREiYjJKwICZMRElaEhMkICStCwmSEhBUhYTJCwoqQMBkhYUVImIyQsCIkTEZIWBESJiMkrAgJkxESVoSEyQgJK0LCZISEFSFhMkLCipAwGSFhRUiYjJCwIiRMRkhYERImIySsCAmTERJWhITJCAmrvyw8Nt92mFk5NK8cu8l+ftt9ZuX+K+8U6tF42ml25dS48uikem//bDptWpiZmlaecx8h13ncLrXeLa7sLosr47mDRpIkSZIkSZIkKd0n1Z1BHSVRBlQAAAAASUVORK5CYII=";
break;
case "play":
icon = "https://i.dlpng.com/static/png/6903815_preview.png";
break;
default:
break;
}
return (
<StyledArrow
onClick={handleClick}
direction={direction}
playState={playState}
{...wrapperProps}
>
<img src={icon} alt="right arrow" className="h-6 w-6" {...imgProps} />
</StyledArrow>
);
};
Arrow.propTypes = {
handleClick: PropTypes.func,
direction: PropTypes.string,
playState: PropTypes.bool,
imgProps: PropTypes.object,
wrapperProps: PropTypes.object
};
export default Arrow;
|
import Ember from 'ember';
export default Ember.Component.extend({
userSession: Ember.inject.service(),
actions: {
upvoteAnswer(answer) {
this.get('userSession').upvoteAnswer(answer);
},
downvoteAnswer(answer) {
this.get('userSession').downvoteAnswer(answer);
}
}
});
|
//key:自定义变量名,value:接口名称
//这里面可以配置ajax请求的url,也可以配置一些固定的跳转链接
export default {
// 接口代理配置
search: `https://api.douban.com/v2/book/1220562`
}
|
var emptyString = "";
var fruits = ["kiwi", "apple", "banana", "watermelon", "peach", "strawberry", "pear", "grape", "orange", "raspberry"];
var two = 2;
var fruitList = document.getElementById("fruit-list");
var output = "";
for (var i = 1; i <= fruits.length; i += two) {
console.log(i);
var alteredFruit = fruits[i].replace(/a/g, "e");
console.log(alteredFruit);
emptyString += alteredFruit;
output += "<div class='fruit'>" + alteredFruit + "</div>";
};
console.log("empty string:", emptyString);
fruitList.innerHTML = output;
|
$(document).ready(function () {
$('#pharmacies tbody').empty();
$.ajax({
type: "GET",
url: "http://localhost:8081/patients/allpharmaciespromotion",
dataType: "json",
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS : ", data);
for (i = 0; i < data.length; i++) {
var row = "<tr>";
row += "<td>" + data[i]['name'] + "</td>";
var btn = "<button class='unsubscribe' id = " + data[i]['id'] + ">Odjava na akcije</button>";
row += "<td>" + btn + "</td>";
$('#pharmacies').append(row);
}
},
error: function (data) {
console.log("ERROR : ", data);
}
});
});
$(document).on('click', '.unsubscribe', function () {
var pharmacyId=this.id;
var pharmacyJSON = formToJSON(pharmacyId);
$.ajax({
type: "POST",
url: "http://localhost:8081/patients/unsubscribe",
dataType: "json",
contentType: "application/json",
data: pharmacyJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function () {
alert("Uspesna odjava akcije");
window.location.href = "patientWelcome.html";
},
error: function (error, data) {
console.log(data);
alert(error);
}
});
});
function formToJSON(pharmacyID) {
return JSON.stringify(
{
"id":pharmacyID
}
);
};
|
import { combineReducers } from 'redux'
// import { routerReducer } from 'react-router-redux'
// import { routerReducer } from 'react-router-redux'
import { foodData, foodUI, foodCameraUI } from './food'
import { exerciseData, exerciseUI } from './exercise'
import { activityData, activityUI } from './activity'
import { modal } from './modal'
import { route } from './route'
import { profile } from './profile'
const reducer = combineReducers({
foodData,
foodUI,
exerciseData,
exerciseUI,
foodCameraUI,
activityData,
activityUI,
profile,
modal,
route,
})
export default reducer
|
var _ = require('lodash');
var gulp = require('gulp');
var replace = require('gulp-replace');
var watch = require('gulp-watch');
var insert = require('gulp-insert');
var rename = require("gulp-rename");
var mocha = require('gulp-mocha');
/*
Constants
*/
var unityClientSourcePath = '../client/Dagger/Assets/Scripts/Dagger/'
/*
Unity client Functions
*/
var unity = {
'build.messageCode' : function () {
return gulp.src('./src/common/MessageCode.ts')
.pipe(replace('export = MessageCode;', ''))
.pipe(insert.prepend('public '))
.pipe(rename('MessageCode.cs'))
.pipe(gulp.dest(unityClientSourcePath));
},
'build.parameterCode' : function () {
return gulp.src('./src/common/ParameterCode.ts')
.pipe(replace('export = ParameterCode;', ''))
.pipe(insert.prepend('public '))
.pipe(rename('ParameterCode.cs'))
.pipe(gulp.dest(unityClientSourcePath));
},
'build.gameObjectType' : function () {
return gulp.src('./src/gameServer/enums/GameObjectType.ts')
.pipe(replace('export = GameObjectType;', ''))
.pipe(insert.prepend('public '))
.pipe(rename('GameObjectType.cs'))
.pipe(gulp.dest(unityClientSourcePath));
},
'build.objectHintType' : function () {
return gulp.src('./src/gameServer/enums/ObjectHintType.ts')
.pipe(replace('export = ObjectHintType;', ''))
.pipe(insert.prepend('public '))
.pipe(rename('ObjectHintType.cs'))
.pipe(gulp.dest(unityClientSourcePath));
}
}
gulp.task('build.unity', function () {
unity['build.messageCode']();
unity['build.parameterCode']();
unity['build.gameObjectType']();
unity['build.objectHintType']();
})
gulp.task('develop.unity', ['build.unity'], function () {
// Watch for changes in enums
watch('./src/common/MessageCode.ts', unity['build.messageCode'])
watch('./src/common/ParameterCode.ts', unity['build.parameterCode'])
watch('./src/gameServer/enums/GameObjectType.ts', unity['build.gameObjectType'])
watch('./src/gameServer/enums/ObjectHintType.ts', unity['build.objectHintType'])
});
gulp.task('default', function () {
});
/* -----------------------------------------------------------
Testing tasks
*/
var handleTestError = function (err) {
console.log(err.toString());
this.emit('end');
}
var tests = {
'all' : _.debounce(function () {
return gulp.src('./tests/tests.js', {read : false})
.pipe(mocha({reporter: 'spec'}))
.on('error', handleTestError);
}, 500)
}
gulp.task('test', function () {
return tests['all']();
});
gulp.task('test.live', function () {
watch('./src/**/*.js' ,tests['all']);
tests['all']();
});
|
import { NavLink } from 'react-router-dom';
import routes from '../../routes';
import { useSelector } from 'react-redux';
import stiles from './Navigation.module.css';
const Navigation = () => {
const authSelector = useSelector(state => state.user.token);
return (
<div className={stiles.container}>
{authSelector ? (
<NavLink
exact
to={routes.contacts}
className={stiles.link}
activeClassName={stiles.link_active}
>
Contacts
</NavLink>
) : (
''
)}
</div>
);
};
export default Navigation;
|
import { GraphQLID, GraphQLString, GraphQLNonNull } from 'graphql'
import contentType, { fields } from '../types/content'
import { ContentTypeEnum } from '../types/enums'
import { ContentInput } from '../types/inputs'
import resolve from '../resolvers/editContent'
const editContent = {
name: 'editContent',
type: contentType,
args: {
content: {
type: new GraphQLNonNull(ContentInput)
}
},
resolve
}
export default editContent
|
const express = require('express') // 加载express框架
const Router = express.Router() // 使用express的路由
const apiModel = require('./model') // 引入数据库操作
const todo = apiModel.getModel('todo') // 使用数据库的todo表
const multipart = require('connect-multiparty') // 使得post请求能支持formdata
const multipartMiddleware = multipart()
// 查询数据
Router.get('/get', (req, res) => {
todo.find({}, (err, doc) => {
if(err) return res.json({code: 1, msg: '获取数据失败!'})
return res.json({code: 0, data: doc})
})
})
// 添加数据
Router.post('/add', multipartMiddleware, (req, res) => {
const {text} = req.body
const newTodo = new todo({text: text, checked: false})
newTodo.save((err, doc) => {
if(err) return res.json({code: 1, msg: '添加数据失败!'})
return res.json({code: 0, data: doc})
})
})
// 选中
Router.post('/check', (req, res) => {
const {id, checked} = req.body
todo.findByIdAndUpdate(id, {checked: checked}, (err, doc) => {
if(err) return res.json({code: 1, msg: '删除数据失败!'})
return res.json({code: 0, data: doc})
})
})
// 全选或反选
Router.post('/checkAll', (req, res) => {
const {checked} = req.body
todo.update({}, {'$set': {checked: checked}}, { multi: true }, (err, doc) => {
if(err) return res.json({code: 1, msg: '删除数据失败!'})
return res.json({code: 0})
})
})
// 删除
Router.post('/delete', (req, res) => {
const {id} = req.body
todo.remove({_id:id}, (err, doc) => {
if(err) return res.json({code: 1, msg: '删除数据失败!'})
return res.json({code: 0})
})
})
// 清空
Router.get('/clear', (req, res) => {
todo.remove({}, (err, doc) => {
if(err) return res.json({code: 1, msg: '清空数据失败!'})
return res.json({code: 0})
})
})
// 输出路由
module.exports = Router
|
const express = require('express');
const router = express.Router();
const {infantProcess} = require ("../controllers/infant")
/* GET home page */
router.get('/', (req, res) => {
res.send('Diagnostico Integral');
});
router.post("/infants", infantProcess);
module.exports = router;
|
angular.module('tab-configure', [])
.controller('photos', ['$scope', '$ionicActionSheet', '$cordovaCamera', '$window', function ($scope, $ionicActionSheet, $cordovaCamera, $window) {
$scope.show = function () {
$ionicActionSheet.show({
//titleText: '请选择类别',
buttons: [
{ text: '查看相册' },
{ text: '拍照' }
],
cancelText: '取消',
cancel: function () { },
buttonClicked: function (index) {
console.log(index);
if (index == '1') {
$scope.takePhoto();
}
return true;
}
})
};
$scope.takePhoto = function () {
var options = {
//这些参数可能要配合着使用,比如选择了sourcetype是0,destinationtype要相应的设置
quality: 100, //相片质量0-100
destinationType: Camera.DestinationType.FILE_URI, //返回类型:DATA_URL= 0,返回作为 base64 編碼字串。 FILE_URI=1,返回影像档的 URI。NATIVE_URI=2,返回图像本机URI (例如,資產庫)
sourceType: Camera.PictureSourceType.CAMERA, //从哪里选择图片:PHOTOLIBRARY=0,相机拍照=1,SAVEDPHOTOALBUM=2。0和1其实都是本地图库
allowEdit: false, //在选择之前允许修改截图
encodingType: Camera.EncodingType.JPEG, //保存的图片格式: JPEG = 0, PNG = 1
targetWidth: 200, //照片宽度
targetHeight: 200, //照片高度
mediaType: 0, //可选媒体类型:圖片=0,只允许选择图片將返回指定DestinationType的参数。 視頻格式=1,允许选择视频,最终返回 FILE_URI。ALLMEDIA= 2,允许所有媒体类型的选择。
cameraDirection: 0, //枪后摄像头类型:Back= 0,Front-facing = 1
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: true //保存进手机相册
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$window.alert(imageData);
}, function (err) {
// error
});
};
}])
.controller('location', ['$scope', '$cordovaGeolocation', '$window', function ($scope, $cordovaGeolocation, $window) {
$scope.location = function () {
$cordovaGeolocation
.getCurrentPosition({timeout: 10000, enableHighAccuracy: false})
.then(function (position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
$window.alert(lat + ',' + lon);
}, function (err) {
$window.alert('[' + err.code + ']' + err.message);
})
}
}])
.controller('media', ['$scope', '$cordovaMedia', '$window', function ($scope, $cordovaMedia, $window) {
$scope.media = function () {
$cordovaMedia
}
}])
|
HotkeysInfo = function(){
var data=[ /*['换功能页','Ctrl+F1'],*/
['货码','Enter','enterFunction'],
['颜色','F11','updateColor'],
['尺码','F12','updateSizeType'],
['数量','Insert','updateNumber'],
/* ['价格','Delete'],*/
['折扣','Home','onDiscount'],
['优惠价','End','onOffers'],
['导购员','PageUp','onSelShippingGuide'],
['付款','PageDown','onPayment'],
['整单优惠','Ctrl+F12','onPreferential'],
['现金','F1','onPaymentMoney'],
/* ['支票','F2'],*/
['信用卡','F3','createCreditCardTypeWin'],
/* ['购物券','F4'],
['会员卡','F5'],*/
['挂单','F6'],
['打印','F7'],
/*['开钱箱','F8'],*/
['退货','F9'],
['不打印','F10','onNoPrint'],
['补单','Ctrl+B'],
['确认','Enter','enterFunction'],
['取消','Esc','escFunction'],
['删除','Back'],
['上行','↑'],
['下行','↓'],
/* ['赠送','←'],*/
['返现','Ctrl+F2'],
['备用金','Ctrl+F3'],
['交款','Ctrl+F5','onPay'],
/*['查询','Ctrl+F5'],
['修改口令','Ctrl+F7'],
['暂停','Ctrl+F8'],*/
['交班','Ctrl+F9','doChangeCasher'],/*,
['条码','→']*/
['会员卡','Ctrl+F10','vipCard'],
['赠品/销售','F8','gifts'],
['选择赠品','Ctrl+F8']
];
var store=new Ext.data.SimpleStore({data:data,fields:["description","hotkeys","action"]});
HotkeysInfo.superclass.constructor.call(this, {
id : 'hotkeysInfo',
region : 'west',
title : "功能键",
split : true,
collapseMode:"mini",
width : 160,
minSize : 120,
maxSize : 250,
margins : '0 0 -1 1',
collapsible : true,
defaults:{autoScroll:true,border: false},
layout:"fit",
items:new Ext.grid.GridPanel({
store:store,
header:false,
hideHeaders:true,
//enableHdMenu:false,
//headerAsText:false,
viewConfig:{
getRowClass:function(){
return "x-grid3-ro-pos";
}
},
columns:[
{width:70,dataIndex:"description"},
{width:70,dataIndex:"hotkeys"}]
})
});
this.grid = this.getComponent(0);
}
Ext.extend(HotkeysInfo, Ext.Panel);
PosProductGridList = Ext.extend(BaseGridList, {
border : false,
gridForceFit : false,
selectSingle:false,
pageSize : -1,
pagingToolbar:false,
loadMask:{msg:"Please wait..."},
url : "productStock.ejf?cmd=productStockWearByDepot",
storeMapping : ["id", "sn", "title","producer","brand", "dir","product","dirTitle","salePrice","attributeType","style","theYear","season","encaped"],
initComponent : function() {
/*this.keys = {
key : Ext.EventObject.ENTER,
fn : this.refresh,
stopEvent:true,
scope : this
};*/
var gridConfig={border:false},chkM=null;
if(this.selectSingle){
gridConfig.sm=new Ext.grid.RowSelectionModel({singleSelect:true});
}
else{
chkM=new Ext.grid.CheckboxSelectionModel();
gridConfig.sm=chkM;
}
this.gridConfig=Ext.apply({},gridConfig);
this.cm = new Ext.grid.ColumnModel([chkM?chkM:new Ext.grid.RowNumberer({header:"序号",width:40}),
{
header : "货号",
sortable : true,
width : 70,
dataIndex : "sn"
},{
header : "品牌",
sortable : true,
width : 80,
dataIndex : "brand"
}, {
header : "类型",
sortable : true,
width : 60,
dataIndex : "dirTitle"
}, {
header : "款型",
sortable : true,
width : 60,
dataIndex : "style"
}, {
header : "年份",
sortable : true,
width : 60,
dataIndex : "theYear"
},{
header : "季节",
sortable : true,
width : 60,
dataIndex : "season"
},{
header : "零售价",
sortable : true,
width : 60,
dataIndex : "salePrice"
}]);
this.btn_sn =new Ext.form.TextField({
xtype : "textfield",
width : 80
});
// new
// Ext.form.TextField({xtype:"textfield",width:80,listeners:{"change":this.refresh,scope:this}});
this.btn_title = new Ext.form.TextField({
xtype : "textfield",
width : 100,
listeners : {
"change" : this.refresh,
scope : this
}
});
this.btn_model = new Ext.form.TextField({
xtype : "textfield",
width : 80,
listeners : {
"change" : this.refresh,
scope : this
}
});
PosProductGridList.superclass.initComponent.call(this);
this.store.on("load", function(s, rs) {
if (rs && rs.length > 0) {
this.grid.getSelectionModel().selectFirstRow();
this.grid.getView().focusRow(0);
}
}, this);
this.store.on("beforeload",function(store,ops){
store.baseParams=store.baseParams||{};
store.baseParams.client=Global.CLIENT.id;
},this);
}
});
PosProductSelectWin = Ext.extend(Ext.Window, {
title : "选择产品",
width : 550,
height : 500,
layout : "border",
buttonAlign : "center",
closeAction : "hide",
modal:true,
selectSingle:false,
callback : Ext.emptyFn,
maximizable:true,//this.enableMaxime,
listeners:{maximize:function(win){win.doLayout();},
restore:function(win){win.doLayout();}
},
choice : function(e) {
var records = this.list.grid.getSelections();
if (records.length < 1) {
Ext.Msg.alert("提示","请选择一个产品!",this.focus,this);
return false;
}
var datas = [];
for (var i = 0; i < records.length; i++) {
datas[i] = records[i].data;
}
this.hide();
this.fireEvent('select', datas, this);
},
initComponent : function() {
this.keys = [{
key : Ext.EventObject.ENTER,
fn : this.choice,
stopEvent:true,
scope : this
},{
key : Ext.EventObject.ESC,
fn : function(){this.hide()},
scope : this
}];
this.buttons = [{
text : "确定",
handler : this.choice,
scope : this
}, {
text : "清空"
}, {
text : "取消",
handler : function() {
this.hide();
},
scope : this
}];
PosProductSelectWin.superclass.initComponent.call(this);
this.list = new PosProductGridList({selectSingle:this.selectSingle,region:"center"});
/* this.on("show",function(){
this.list.grid.store.reload();//getSelectionModel().selectFirstRow();
//this.list.grid.getView().focusRow(0);
}, this);*/
this.list.grid.on("rowdblclick", this.choice, this);
this.add(this.list);
this.addEvents("select");
}
});
ShoppingGuideGridList = Ext.extend(BaseGridList, {
border : false,
//gridForceFit : false,
selectSingle:true,
pagingToolbar:false,
pageSize : -1,
url : "employee.ejf?cmd=list&status=0",
//baseQueryParams:{status:0},
storeMapping : ["id", "name", "trueName", "email", "dept", "contractNo","sn",
"duty", "tel", "registerTime","status","sex","workerOnly"],
initComponent : function() {
var gridConfig={border:false},chkM=null;
if(this.selectSingle){
gridConfig.sm=new Ext.grid.RowSelectionModel({singleSelect:true});
}
else{
chkM=new Ext.grid.CheckboxSelectionModel();
gridConfig.sm=chkM;
}
this.cm = new Ext.grid.ColumnModel([chkM?chkM:new Ext.grid.RowNumberer({header:"序号",width:35}),{
header : "姓名",
sortable : true,
width : 100,
dataIndex : "trueName"
}, {
header : "编码",
sortable : true,
width : 100,
dataIndex : "name"
},{
header : "用户名",
sortable : true,
width : 100,
hidden:true,
dataIndex : "name"
}, {
header : "电话",
sortable : true,
width : 100,
dataIndex : "tel"
}]);
this.gridConfig=gridConfig;
ShoppingGuideGridList.superclass.initComponent.call(this);
// this.store.load();
this.store.on("load", function(s, rs) {
if (rs && rs.length > 0) {
this.grid.getSelectionModel().selectFirstRow();
this.grid.getView().focusRow(0);
}
}, this);
}
});
ShoppingGuideSelectWin = Ext.extend(Ext.Window, {
title : "选择导购",
width : 540,
height : 400,
layout : "fit",
buttonAlign : "center",
closeAction : "hide",
modal:true,
selectSingle:true,
callback : Ext.emptyFn,
choice : function(grid,rowIndex,e) {
var records = this.list.grid.getSelections();
if (!records || records.length < 1) {
Ext.Msg.alert("提示","请选择一个导购员!",this.focus,this);
return false;
}
var datas = [];
Ext.each(records,function(record,i){datas[i] = records[i].data;},this);
this.hide();
this.fireEvent('select', datas[0], this,e);
},
initComponent : function() {
this.keys = [{
key : Ext.EventObject.ENTER,
fn : this.choice,
stopEvent:true,
scope : this
},{
key : Ext.EventObject.ESC,
fn : function(){this.hide()},
scope : this
}];
this.buttons = [{
text : "确定",
handler : this.choice,
scope : this
}, {
text : "取消",
handler : function() {
this.hide();
},
scope : this
}];
ShoppingGuideSelectWin.superclass.initComponent.call(this);
this.list = new ShoppingGuideGridList();
/*this.on("show",function(){
this.list.grid.store.reload();
}, this);*/
this.list.grid.on("rowdblclick", this.choice, this);
this.add(this.list);
this.addEvents("select");
}
});
HangBillGridList = Ext.extend(BaseGridList, {
border : false,
//gridForceFit : false,
selectSingle:true,
pagingToolbar:false,
pageSize : -1,
storeMapping : ["time", "num", "totalAmount", "product","items"],
initComponent : function() {
var gridConfig={border:false},chkM=null;
if(this.selectSingle){
gridConfig.sm=new Ext.grid.RowSelectionModel({singleSelect:true});
}
else{
chkM=new Ext.grid.CheckboxSelectionModel();
gridConfig.sm=chkM;
}
this.cm = new Ext.grid.ColumnModel([chkM?chkM:new Ext.grid.RowNumberer({header:"序号",width:35}),{
header : "时间",
sortable : true,
width : 100,
dataIndex : "time",
renderer:this.dateRender("Y-m-d H:i")
}, {
header : "数量",
sortable : true,
width : 100,
dataIndex : "num"
},{
header : "总金额",
sortable : true,
width : 100,
dataIndex : "totalAmount"
}, {
header : "主要产品",
sortable : true,
width : 100,
dataIndex : "product",
renderer:this.objectRender("title")
}]);
this.gridConfig=gridConfig;
HangBillGridList.superclass.initComponent.call(this);
this.store.on("load", function(s, rs) {
if (rs && rs.length > 0) {
(function(){
this.grid.getSelectionModel().selectFirstRow();
this.grid.getView().focusRow(0);
}).defer(500,this);
}
}, this);
}
});
HangBillSelectWin = Ext.extend(Ext.Window, {
title : "选择挂单",
width : 540,
height : 400,
layout : "fit",
buttonAlign : "center",
closeAction : "hide",
modal:true,
selectSingle:true,
callback : Ext.emptyFn,
choice : function(grid,rowIndex,e) {
var records = this.list.grid.getSelections();
if (!records || records.length < 1) {
Ext.Msg.alert("提示","请选择一张单据!",this.focus,this);
return false;
}
var datas = [];
for (var i = 0; i < records.length; i++) {
datas[i] = records[i].data;
}
this.hide();
this.fireEvent('select', datas[0], this,e);
this.list.grid.store.remove(records[0]);
},
initComponent : function() {
this.keys = [{
key : Ext.EventObject.ENTER,
fn : this.choice,
stopEvent:true,
scope : this
},{
key : Ext.EventObject.ESC,
fn : function(){this.hide()},
scope : this
}];
this.buttons = [{
text : "确定",
handler : this.choice,
scope : this
}, {
text : "取消",
handler : function() {
this.hide();
},
scope : this
}];
HangBillSelectWin.superclass.initComponent.call(this);
this.list = new HangBillGridList();
this.list.grid.on("rowdblclick", this.choice, this);
this.add(this.list);
this.addEvents("select");
}
});
PosPanel=Ext.extend(BaseStockOutcomeWearBillPanel,{
id:"posPanel",
baseQueryParameter:{types:3,vdate3:new Date().format("Y-m-d")},
types:3,
singleWindowMode:true,
printData:true,
baseUrl:"retailBill.ejf",
autoLoadGridData:true,
disable_operators:["btn_edit","btn_remove"],
searchWin : {
width : 550,
height : 220,
title : "高级查询"
},
initColumnDisplay:function(){}, //覆盖该方法. 这里不管理尺码和手
toFixed:function(v){return v&&v.toFixed?v.toFixed(2):v;},
viewWin:{width:738,height:600,title:"Pos收银"},
editEmptyObj:{"id":null,"num7":null,"product":{},residualStoreNum:null,sizeType:null,shoppingGuide:{},productTitle:null,productSn:null,"brand":null, "spec":null, "model":null, "unit":null, "price":null,"num":null, "remark":null, "location":null, "depot":null,"blockSn":null,"totalAmount":null,"vdate":null,"salePrice":null,"discount":null,"saleAmount":null,colorSn:"","other1":null,"other2":null,"other3":null},
searchFormPanel : function(){
var formPanel = new Ext.form.FormPanel({
frame : true,
labelWidth : 80,
labelAlign : "right",
navigationSequences:["productSn","status","snStart","snEnd","vdate1","vdate2","brand","shoppingGuide"],
items : [{
xtype : "fieldset",
title : "查询条件",
height : 140,
layout : 'column',
items : [{
columnWidth : .50,
layout : 'form',
defaultType : 'textfield',
items : [{
fieldLabel : "货 号",
name : "productSn",
anchor : '90%'
}, {
fieldLabel : "流水单号(始)",
name : "snStart",
anchor : '90%'
},{
xtype : "hidden",
name:"advanced",
value:true
}, {
fieldLabel : "制单日期(始)",
name : "vdate1",
anchor : '90%',
xtype : 'datefield',
format : 'Y-m-d'
}
, Ext.apply({},{emptyText:"--请选择--",width:200,anchor : '90%'},Disco.Ext.Util.buildRemoteCombox('brand', '品牌',"brand.ejf?cmd=listSelect", ["id", "name"],"name", "id", true))
]
}, {
columnWidth : .50,
layout : 'form',
defaultType : 'textfield',
defaults : {
width : 130
},
items : [{
xtype : "combo",
anchor : '90%',
name : "status",
hiddenName : "status",
fieldLabel : "状 态",
displayField : "title",
valueField : "value",
value : 0,
store : new Ext.data.SimpleStore({
fields : ['title', 'value'],
data : [ ["正常销售", 0],["质量问题", 1],["客户不满意", 2],["换货", 3],["未知原因", 4]]
}),
disableChoice : true,
editable : false,
mode : 'local',
triggerAction : 'all',
emptyText : '请选择...'
}, {
fieldLabel : "流水单号(末)",
name : "snEnd",
anchor : '90%'
},{
fieldLabel : "制单日期(末)",
name : "vdate2",
anchor : '90%',
xtype : 'datefield',
format : 'Y-m-d'
},Ext.apply({},{anchor:"-1",width:95,fieldLabel : '导购员',hiddenName:'shoppingGuide',name:'shoppingGuide'},ConfigConst.CRM.user)
]
}]
}]
});
return formPanel;
},
initWin : function(width, height, title,callback,autoClose,resizable,maximizable) {
this.winWidth = width;
this.winHeight = height;
this.winTitle = title;
var winName=autoClose?"CrudEditNewWindow":"CrudEditWindow";
if(this.singleWindowMode)winName=winName+this.id;
if(!this.win)
this.win = new Ext.Window({
modal : true,
width : width,
height : height,
title : title,
layout : "fit",
border:false,
items : this.fp,
listeners:{
hide:function(){
if(this.vipWin)this.vipWin.hide();
},
scope:this
}
});
this.win.confirmSave=this.dirtyFormCheck;
return this.win;
},
onCreate:function(){
Ext.EventManager.onWindowResize(this.win.fitContainer, this.win);
this.win.on("show",function(){
var key = this.win.getKeyMap();
key.disable();
this.fp.form.findField("key").focus(false,300);
},this);
this.win.getEl().on("click",this.formFocus,this);
this.win.getEl().on("contextmenu",function(e){
e.stopEvent();
this.formFocus();
},this);
this.tempData.clear("firstShippingGuide");
this.paid = 0.00; //初始化付款金额
this.setAction('shippingGuide');
this.payment=false; //初始化开始付款
this.complete=false; // 初始化付款完成
this.giftsPattern=false;
this.haveProducts = false;
this.append= false;
this.noPrint=false;
/*
this.append= false;//添加货品,为true的时候连续添加货品
this.haveProducts = false; //是否有在EditPanel是否有货品
this.complete=false; // 初始化付款完成
this.noPrint=false;
this.patchOrder = false; //补单
*/ this.editGrid.store.removeAll();
this.paymentGrid.store.removeAll();
this.editGrid.getSelectionModel().on("beforecellselect",function(){
this.customSelectRow(this.selectedRow);
return false;
},this);
this.fp.form.findField("key").enable();
this.fp.form.findField("vdate").setValue("");
var retailType = this.fp.form.findField("retailType");
retailType.el.parent('div.x-form-item').first('label').dom.innerHTML = "销售";
this.fp.form.findField("status").setValue(0);
this.fp.form.findField("remark2").setValue("");
//this.fp.form.findField("key").focus("",200);
this.fp.form.findField("key").reset();
//this.fp.form.find.defer(200);
},
edit:function(){
this.view();
},
showViewWin : function(autoClose) {
if(this.createViewPanel){
this.viewPanel = this.createViewPanel();
}
var win = this.getViewWin(autoClose);
return win;
},
createViewPanel:function(){
var store=new Ext.data.JsonStore({
root : "result",
totalProperty : "rowCount",
fields:this.editStoreMapping
});
var colM=this.getEditColumnModel();
this.viewGrid = new Ext.grid.GridPanel({
//title:"采购入库单详",
cm:colM,
store:store,
border:false,
autoExpandColumn:colM.getColumnCount()-1,
plugins:[new Ext.ux.grid.GridSummary()]
});
if(!this.celldblclickShowPictrue)this.viewGrid.on("celldblclick",this.showPic,this); //查看图片
var formPanel=new Ext.form.FormPanel({
frame:false,
labelWidth:70,
labelAlign:'right',
items:[{
xtype:'panel',
//title:'基本信息',
style:"margin-bottom:5px;margin-top:10px",
border:false,
autoHeight:true,
layout:"form",
items:[
Disco.Ext.Util.columnPanelBuild(
{columnWidth:.2,items:{xtype:"labelfield",fieldLabel:'编号',name:'sn'}},
{columnWidth:.2,items:{xtype:"labelfield",fieldLabel:'时间',name:'vdate',renderer:this.dateRender("Y-m-d")}},
{columnWidth:.3,items:{xtype:"labelfield",fieldLabel:'收银员',name:'cashier',renderer:this.objectRender("trueName")}},
{columnWidth:.3,items:{xtype:"labelfield",fieldLabel:'付款总数',name:'receive',anchor:"-20"}},
{columnWidth:.2,items:{xtype:"labelfield",fieldLabel:'合计',name:'total'}},
{columnWidth:.2,items:{xtype:"labelfield",fieldLabel:'找零',name:'charge'}}
)
]
},{
xtype:'panel',
autoHeight:true,
border:false,
listeners:{render:function(c){
var height=this.viewPanel.el.getBox().height-(this.viewPanel.getComponent(0).el.getBox().height+68);
this.viewGrid.setHeight(height);
},scope:this},
items:this.viewGrid
}]
});
return formPanel;
},
escFunction:function(){
var action = this.getAction();
if(action){
if(action == 'preferential'){
if(this.fp.findSomeThing("preferential").getValue())
this.cancelPreferential();
else if(this.payment)
this.cancelPayment();
}else if(action == 'onMember'){
this.setAction(null);
}
return false;
}
if(this.complete){
this.fp.form.findField("remark1").setValue("取消交易!");
this.complete = false;
}else if(this.payment){
this.cancelPayment();
}else if(this.haveProducts){
this.delProduct();
var count = this.editGrid.store.getCount();
if(count<1){
this.haveProducts = false;
this.append = false;
this.fp.form.findField("remark1").setValue("请先输入编码后按[确认]键选择购员!");
}
}
this.setAction();
},
cancelPayment:function(){
var paymentCount = this.paymentGrid.store.getCount();
if(paymentCount>1){
var record = this.paymentGrid.store.getAt(paymentCount-1);
this.paymentGrid.store.remove(record);
this.countPay();
this.formFocus();
}else{
this.payment = false;
this.fp.form.findField("remark1").setValue("取消付款!");
this.fp.form.findField("received").setValue(null);
this.fp.form.findField("receive").setValue(null);
this.fp.form.findField("unpaid").setValue(null);
this.fp.form.findField("key").setValue(null);
this.paid = 0.00;
this.paymentGrid.store.removeAll();
}
},
createPaymentGrid: function(){
var cms = [new Ext.grid.RowNumberer({header:"<font size='4' color='000000'>编号</font>",width:50}),
{header:"支付类型",dataIndex:"paymentType",width:80,hidden:true},
{header:"卡号",dataIndex:"cardNO",width:80,hidden:true},
{header:"信用卡类型",dataIndex:"cardType",hidden:true},
{header:"<font size='4' color='000000'>付款方式<font>",dataIndex:"paymentTypeTitle",width:80},
{header:"<font size='4' color='000000'>金额<font>",dataIndex:"paymentSum",width:80}
];
var fields = ["paymentType","paymentTypeTitle","paymentSum","cardNO","cardType"];
return new Ext.grid.GridPanel({
viewConfig:{forceFit:true},
cm: new Ext.grid.ColumnModel(cms),
store:new Ext.data.JsonStore({
fields:fields
})
});
},
addRowDataHandler:function(r){
var obj=Ext.apply({},r,this.editEmptyObj);
if(r){
obj.shoppingGuide=r;
}
delete obj.id;
return obj;
},
addRowForProductDataHandler:function(r){
//var obj=Ext.apply({},r,this.editEmptyObj);
var obj={};
if(r){
obj.shoppingGuide=this.tempData.get("firstShippingGuide");
obj.salePrice=this.formatMoney(r.salePrice);
obj.product=r;
obj.product.toString=Disco.Ext.Util.objectToString;
obj.productTitle=r.title;
obj.productSn=r.sn;
obj.spec=r.spec;
obj.stockNO=r.stockNO;
obj.colorSn=r.colorSn;
obj.attributeType = r.attributeType;
obj.encaped = r.encaped;
obj.color = r.colors;
//obj.color.toString=function(){return this.title?this.title:this};
obj.sizeType = r.sizes;
obj.status = r.status;
/*obj.marketPrice=r.marketPrice;
obj.brand=r.brand;
obj.model=r.model;*/
obj.unit=r.unit;
obj.num=1;
obj.style=r.style;
obj.gifts=r.gifts;
if(this.vipUser){
obj['discount'] = parseFloat(this.vipUser['discount']/10) ;
obj['discountPrice'] = this.formatMoney(obj['discount'] * parseFloat(obj['salePrice']));
obj.totalAmount = obj['discountPrice'];
}else{
obj.totalAmount = this.formatMoney(r.salePrice);
obj.discountPrice = this.formatMoney(r.salePrice);
obj.discount = 1.0;
}
}
Ext.del(obj,'id');
return obj;
},
append: false, //连续性加入商品
payment:false,//是否需要付款
paid :0.00,
paymentTypeTitle:"现金",
checkCreditCard:function(){
var index = this.paymentGrid.store.find("paymentTypeTitle","信用卡");
if(index===-1){
return false;
}
return true
},
deleteCreditCard:function(paymentTypeTitle){
var index = this.paymentGrid.store.find("paymentTypeTitle",paymentTypeTitle);
if(index===-1){
return false;
}else{
this.paymentGrid.store.getAt(index).set("paymentSum",0);
}
},
setAction:function(action){
if(action===null || action===window.undefined){
if(!this.editGrid.getStore().getCount())action = 'shippingGuide';
}
this._action = action;
},
getAction:function(){
return this._action;
},
isAction:function(action){
return (this._action==action);
},
//付款
doPayment:function(){
var payments = this.fp.form.findField("key").getValue(); //获得输入的金额
var count = this.editGrid.store.getCount();
var sum = parseFloat(this.fp.form.findField("receivable").getValue());
if(!payments){
Disco.Ext.Util.msg("提示","请输入金额!");
return false;
}else if(!Disco.Ext.Util.isNumber(payments)){
Disco.Ext.Util.msg("提示","请输入数字!");
return false;
}
payments = parseFloat(payments);
var status = this.fp.form.findField("status").getValue();
status = parseInt(status);
if(status==0&&sum<0&&sum-payments!=0){
Disco.Ext.Util.msg("提示","如有退货只能录入和付款相同的金额!");
return false;
}else if(status>0&&sum-payments!=0){
Disco.Ext.Util.msg("提示","在退货模式只能录入和付款相同的金额!");
return false;
}
if(!this.paymentTypeId){
Ext.each(this.paymentTypes,function(o){
if(o.name=="现金"){
this.paymentTypeTitle = "现金";
this.paymentTypeId = o.id;
}
},this);
}
if(this.paymentTypeId){
var index = this.paymentGrid.store.find("paymentType",this.paymentTypeId);
if(index!==-1){
var record = this.paymentGrid.store.getAt(index);
record.set("paymentSum",record.get("paymentSum")+payments);
}else{
this.paymentGrid.store.loadData([{paymentType:this.paymentTypeId,paymentTypeTitle:this.paymentTypeTitle,paymentSum:payments,cardNO:"",cardType:""}],true);
}
}
this.fp.form.findField("key").setValue(null);
this.paid = this.paymentGrid.store.sum("paymentSum");
var p = this.paid - sum;
if(p<0){
Disco.Ext.Util.msg("提示","未付款:"+ -this.toFixed(p));
this.fp.form.findField("unpaid").setValue(-this.toFixed(p));
this.fp.form.findField("receive").setValue(this.toFixed(this.paid));
this.fp.form.findField("received").setValue(this.toFixed(this.paid));
this.paymentTypeId = false;
this.formFocus();
return false;
}else if(p > 0){
if(this.checkCreditCard()){
Ext.Msg.alert("错误提示","有信用卡支付的不能超出应收账款!将取消该现金支付",function(){
if(this.paymentTypeId){ //再把此次输入的金额减掉
var index = this.paymentGrid.store.find("paymentType",this.paymentTypeId);
if(index!==-1){
var record = this.paymentGrid.store.getAt(index);
record.set("paymentSum",record.get("paymentSum")-payments);
}
this.countPay();
this.formFocus();
}
},this);
return false;
}
if(p>=100){
Ext.MessageBox.alert("提示","找零金额不能够大于100,请确认!",function(){this.formFocus()},this);
this.deleteCreditCard("现金");
//this.paid=this.paid-payments;
this.countPay();
/*this.fp.form.findField("charge").setValue(this.toFixed(p));
this.fp.form.findField("total").setValue(this.toFixed(sum));
this.fp.form.findField("received").setValue(this.toFixed(this.paid));
this.fp.form.findField("receive").setValue(this.toFixed(this.paid));*/
return false
}else{
Disco.Ext.Util.msg("提示","     找     零     " + this.toFixed(p));
this.fp.findField("remark2").setValue("找零"+this.toFixed(p))
this.fp.findField("unpaid").setValue(-this.toFixed(0));
this.complete = true;
this.fp.findField("charge").setValue(this.toFixed(p));
this.fp.findField("total").setValue(this.toFixed(sum));
this.fp.findField("receive").setValue(this.toFixed(this.paid));
this.formFocus();
}
}
this.fp.findField("charge").setValue(this.toFixed(p));
this.fp.findField("total").setValue(this.toFixed(sum));
this.fp.findField("receive").setValue(this.toFixed(this.paid));
this.fp.findField("received").setValue(this.toFixed(this.paid));
Disco.Ext.Util.msg("提示","支付成功!请按任意键保存数据并且重新开单!");
this.fp.form.findField("remark1").setValue("支付成功!请按任意键保存数据并且重新开单!按[取消]键取消交易!");
this.complete = true; //标记交易成功
this.formFocus();
return false;
},
enterFunction:function(){
if(this.complete) return false;
var key = this.fp.form.findField("key").getValue();
var action = this.getAction();
if(action){
switch(action){
case 'patchOrder' :
this.onPatchOrder();
break;
case 'reserve' :
this.doReserve();
break;
case 'pay' :
this.doPay();
break;
case 'preferential':
if(!this.fp.findSomeThing("preferential").getValue())
this.doPreferential();
else
this.doPayment();
break;
case 'onMember' :
if(!key){
Ext.MessageBox.alert("提示","请输入会员卡!",this.formFocus,this);
return false;
}
this.getVip(key,this.showVipPanel);
break;
case 'shippingGuide' :
this.seachShippingGuide();
break;
/* case 'gifts' :
if(this.tempData.containsKey("firstShippingGuide")){
if('$!session.COMPANYSETTING_IN_SESSION.productInputType'==2){
this.seachProductByBarCode('productBarCode.ejf?cmd=getProductPosBarCodeByCode',{gifts:true},this.seachProductGiftsByBarCode);
}else{
this.seachProductGifts();
}
}else{
this.setAction("shippingGuide");
this.seachShippingGuide();
}
break;
break;*/
}
return;
}
if(this.payment && !this.complete){
this.doPayment();
}else if (this.tempData.containsKey("firstShippingGuide")){
if(!key){
Disco.Ext.Msg.alert({fn:this.formFocus,scope:this,msg:"请输入货号或条码"});
return false;
}
if('$!session.COMPANYSETTING_IN_SESSION.productInputType'==2){
var args = [] ;
this.seachProductByBarCode('productBarCode.ejf?cmd=getProductPosBarCodeByCode',{})
}else{
this.seachProductWear();
}
return false;
}
},
seachProductByBarCode:function(url,params,formatFn){
var key = this.fp.findField('key').getValue().trim();
if(key&&key.trim().length<2){
Disco.Ext.Util.msg("","输入正确的条码!");
this.formFocus();
return false;
}
Ext.Ajax.request({
scope:this,
url:url,
params:Ext.apply({code:key},{action:'pos'},params),
success:function(response,options){
var data = Ext.decode(response.responseText);
if(data.success==true && data.data){
var obj = data.data;
var dest = Ext.copyTo({},obj,'attributeType brand;sizeType dir;dirTitle,encaped,id,producer,product,salePrice,season,sn,style,theYear,title');
dest.residualStoreNum = obj.num;
dest.sizes = dest.sizeType;
obj.sizeType = obj.size;
if(formatFn)formatFn(obj);
var fn = function(){
var o = this.addRowForProductDataHandler(obj);
Ext.copyTo(o,obj,"color,sizeType");
if(o.color)o.color.value = o.color.id;
if(o.sizeType)o.sizeType.value = o.sizeType.id;
this.editGrid.store.loadData({result:[o]},this.append);
this.append = true;
var lastRow = this.editGrid.store.getCount()-1;
this.editGrid.getSelectionModel().select(lastRow,0);
var m = new Ext.util.MixedCollection();m.addAll([obj.num]);
this.editGrid.store.getAt(lastRow).set("residualStoreNum",obj.num);
this.editGrid.store.getAt(lastRow).stockInfo=m;
this.fp.form.findField("key").reset();
this.countAll(false);
this.autoColumn(lastRow);
this.haveProducts = true;
this.fp.findField('key').focus(true);
}
if(this.giftsPattern){
obj.salePrice = 0 ;
obj.status = 5 ;
this.giftsWin = new Ext.Window({
width:300,height:110,
title:'积分兑换',
layout:'fit',
modal:true,
border:false,
hideBorders:true,
resizable:false,
items:{
layout:'form',
xtype:'form',
items:[{
style:'margin:5px;',
fieldLabel:'积分',
hideLabel:true,
anchor:'96% *',
name:'gifts',
minValue:0,
allowDecimals:false,
autoCreate:{
tag : "input",
type : "text",
autocomplete : "off",
style:"font-weight: bold; font-size: 54px; width: 288px; height: 66px;"
},
xtype:'numberfield',
listeners:{
scope:this,
specialkey:function(field,e){
if(e.getKey()==13){
if(field.getValue()==""){
Disco.Ext.Msg.alert("请输入兑换积分!",false,function(){
field.focus()
});
return ;
}
obj.gifts = field.getValue();
this.giftsWin.close();
fn.call(this);
}
}
}
}]
},
listeners:{
scope:this,
show:function(win){
var form = win.getComponent(0);
form.findField('gifts').focus(true,100);
}
}
});
this.giftsWin.show();
}else{
fn.call(this);
}
}else{
Disco.Ext.Util.msg('','没有找到该条码对应的商品!');
this.fp.findField('key').focus(true);
}
}
});
}
,
buildProductSelectWin:function(){
if(!this.productSelectWin)
this.productSelectWin = new PosProductSelectWin({selectSingle:true});
if(!this.productSelectWin.hasListener('select')){
this.productSelectWin.on("select",function(r){
var data = r[0];
if(this.giftsPattern){
this.giftsWin = new Ext.Window({
width:300,height:110,
title:'积分兑换',
layout:'fit',
modal:true,
border:false,
hideBorders:true,
resizable:false,
items:{
layout:'form',
xtype:'form',
items:[{
style:'margin:5px;',
fieldLabel:'积分',
hideLabel:true,
anchor:'96% *',
name:'gifts',
minValue:0,
allowDecimals:false,
autoCreate:{
tag : "input",
type : "text",
autocomplete : "off",
style:"font-weight: bold; font-size: 54px; width: 288px; height: 66px;"
},
xtype:'numberfield',
listeners:{
scope:this,
specialkey:function(field,e){
if(e.getKey()==13){
if(field.getValue()==""){
Disco.Ext.Msg.alert("请输入兑换积分!",false,function(){
field.focus()
});
return ;
}
data.gifts = field.getValue();
this.giftsWin.close();
this.selectProductDataHandler(data);
}
}
}
}]
},
listeners:{
scope:this,
show:function(win){
var form = win.getComponent(0);
form.findField('gifts').focus(true,100);
}
}
});
this.giftsWin.show();
}else{
this.selectProductDataHandler(data);
}
},this);
}
this.productSelectWin.on("hide",function(){
this.productSelectWin.list.grid.store.removeAll();
this.formFocus();
},this,{single:true});
},
seachProductGifts:function(){
this.buildProductSelectWin();
if(key&&key.trim().length<2){
Disco.Ext.Util.msg("","输入货号的长度至少两个字符!");
this.formFocus();
return false;
}
this.productSelectWin.show();
this.productSelectWin.list.grid.getGridEl().mask("加载库存商品...","x-mask-loading");
Ext.Ajax.request({url:"productStock.ejf?cmd=productGiftsWithStock",
params:{sn:key},
callback :function(ops,success,response){
var map=Ext.decode(response.responseText);
var tag = false;
for (var n in map) {
if(n==="tag")tag = true;
}
if(tag){
Disco.Ext.Util.msg("","请设置零售库,请设置零售库!");
this.productSelectWin.hide();
this.formFocus();
this.productSelectWin.list.grid.getGridEl().unmask();
return false;
}else if(!map || !map.result){
Disco.Ext.Util.msg("","该货品不存在或者是库存中没有了!");
this.productSelectWin.hide();
this.formFocus();
this.productSelectWin.list.grid.getGridEl().unmask();
return false
}else{
this.productSelectWin.list.grid.store.removeAll();
this.productSelectWin.list.grid.store.loadData(map);
}
this.productSelectWin.list.grid.getGridEl().unmask();
},scope:this});
},
onPatchOrder:function(){
var vdate = this.fp.form.findField("key").getValue(); //获得输入的金额
var regular = /^(\d{4})\.(\d|0\d{1}|1[0-2])\.(\d|0\d{1}|[12]\d{1}|3[01])$/;
if(!regular.test(vdate)){
Ext.MessageBox.alert("提示","请确定输入时间的格式!例如:2009.08.08",this.formFocus,this);
}else{
this.fp.form.findField("remark2").setValue("补单时间:"+vdate);
this.fp.form.findField("vdate").setValue(vdate);
this.formFocus();
this.setAction(null);
}
},
getVip:function(key,callback){
this.vipUser = null;
Ext.Ajax.request({
url:'member.ejf?cmd=getMemberByCode',
params:{code:key},
success:callback,
scope:this
});
},
updateVipDiscountPrice:function(){
var storeCount = this.editGrid.getStore().getCount();
if(storeCount){
var sm = this.editGrid.getSelectionModel();
var selectRow = (sm.getSelectedCell()||[0,storeCount-1])[1];
this.editGrid.getStore().each(function(record){
if(record.get('product') && record.get('product').id){
var obj = record.data;
obj['salePrice'] = this.formatMoney(obj['salePrice']);
obj['discount'] = parseFloat(this.vipUser['discount']) / 10 || 1;
obj['discountPrice'] = Ext.num(parseFloat(this.formatMoney(obj['discount']*parseFloat(obj['salePrice']).toFixed(2))),0);
obj.totalAmount = obj['discountPrice'];
record.commit();
}
},this);
sm.select(selectRow,false);
}
this.countAll();
},
showVipPanel:function(response,options){
var data = Ext.decode(response.responseText);
if(!data || !data.success || !data.data){
if(this.vipWin)this.vipWin.hide();
Disco.Ext.Msg.alert('没有找到该会员!',null,this.formFocus,this);
return ;
}
this.vipUser = data.data;
this.vipUser['discount'] = this.vipUser['discount'] || 1;
this.setAction(null);
if(!this.vipWin){
this.vipWin = new Ext.Window({
title:'会员信息',
width:250,
height:120,
//closable:false,
resizable:false,
closeAction:'hide',
collapsible:true,
animCollapse:false,
manager:new Ext.WindowGroup,
autoHeight:true,
x:Ext.getBody().getViewSize().width-255,
y:Ext.getBody().getViewSize().height-125,
hideBorders:true,
moveWindow:function(){
var viewSize = Ext.getBody().getViewSize();
this.vipWin.el.moveTo(viewSize['width']-this.vipWin.getBox().width-5,
viewSize['height']-this.vipWin.getBox().height-5);
},
items:{
xtype:'form',
defaultType:'labelfield',
bodyStyle:'padding-left:20px;',
items:[
{fieldLabel:'会员姓名',name:'name'},
{fieldLabel:'卡  号',name:'cardNumber',renderer:function(v){
return Ext.util.Format.ellipsis(v,10);
}},
{fieldLabel:'折  扣',name:'discount'},
{fieldLabel:'积  分',name:'integration'}
]
}
});
this.vipWin.on('render',function(win){
win.el.on('dblclick',function(){
win.collapsed ? win.expand(false) : win.collapse(false);
},this);
},this);
this.vipWin.on({
scope:this,
hide:function(){
this.vipUser = null;
},
expand:this.vipWin.moveWindow.createDelegate(this,['expand'],0),
collapse:this.vipWin.moveWindow.createDelegate(this,['collapse'],0)
});
this.vipWin.fp = this.vipWin.getComponent(0);
}
this.vipWin.show();
this.vipWin.fp.getForm().setValues(this.vipUser);
this.vipWin.setZIndex(99000);
this.updateVipDiscountPrice();//修改當前貨品的折扣價格
this.formFocus();
},
doChangeCasher:function(){
if(!this.casherSelectWin){
this.casherSelectWin = new ShoppingGuideSelectWin({title:"选择交班收银员"});
this.casherSelectWin.on("select",this.selectCasher,this);
this.casherSelectWin.on("show",function(){
Ext.Ajax.request({url:"dutyInfo.ejf?cmd=listCasher&pageSize=-1&orderBy=sn&orderType=asc&status=0",
callback :function(ops,success,response){
var map=Ext.decode(response.responseText);
this.casherSelectWin.list.grid.store.removeAll();
if(map && map.result.length){
this.casherSelectWin.list.grid.store.loadData(map);
}else{
this.casherSelectWin.hide();
Disco.Ext.Util.msg("","不存在其他收银员!");
}
},scope:this});
},this);
this.casherSelectWin.on("hide",this.formFocus,this);
}
this.casherSelectWin.show();
},
selectCasher:function(d){
if(d && d.id){
if(!this.loginWin){
this.loginWin=new CasherLoginWindow();
this.loginWin.on("hide",this.formFocus(),this);
}
this.loginWin.show();
this.loginWin.fp.findSomeThing("user").setValue(d.id);
this.loginWin.fp.findSomeThing("userName").setValue(d.name);
this.loginWin.fp.findSomeThing("psw").focus("",200);
}
},
doPay:function(){
var key = this.fp.form.findField("key").getValue();
if(!key || isNaN(parseFloat(key))){
Ext.MessageBox.alert("提示","请输入正确的缴款数量!",function(){
this.formFocus();
},this);
return false;
}else{
Ext.Ajax.request({
scope:this,
url:"dutyInfo.ejf",
params:{cmd:"save",pay:key},
success:function(req){
var msg=Ext.decode(req.responseText);
if(msg && msg.msg){
Ext.Msg.alert("提示信息",msg.msg);
}else{
Disco.Ext.Util.msg("提示","缴款完成!");
this.formFocus();
this.pay=false;
}
}
})
}
},
doReserve:function(){
var key = this.fp.form.findField("key").getValue();
if(!key || isNaN(parseFloat(key))){
Ext.MessageBox.alert("提示","请输入正确的备用金数量!",function(){
this.formFocus();
},this);
return false;
}else{
Ext.Ajax.request({
scope:this,
url:"dutyInfo.ejf",
params:{cmd:"save",reserve:key},
success:function(req){
var msg=Ext.decode(req.responseText);
if(msg && msg.msg){
Ext.Msg.alert("提示信息",msg.msg);
}else{
Disco.Ext.Util.msg("提示","备用金输入完成!");
this.formFocus();
this.reserve=false;
}
}
})
}
},
autoPrice:function(record,currentChanges){
var discount = parseFloat(record.get("discount")) || 10;
var price = parseFloat(record.get("salePrice"));
var discountPrice = parseFloat(record.get("discountPrice"));
var num = parseFloat(record.get("num"));
if(currentChanges=="discount"){
record.set("discountPrice",(discount*price).toFixed(0));
}else if(currentChanges=="salePrice"){
record.set("discountPrice",(discount*price).toFixed(0));
}else if(currentChanges=="discountPrice"){
if(price!=0)record.set("discount",(discountPrice/price).toFixed(2));
}
var to=num*parseFloat(record.get("discountPrice"));
record.set("totalAmount",parseFloat(to.toFixed(2)));
},
selectedShippingGuide:function(d,grid,e){
if(this.editGrid.store.getCount()>0){
var selectRecord = this.getSelectedRecord();
d.toString=function(){return this.id};
selectRecord.set("shoppingGuide",d);
}
else {
this.editGrid.store.loadData({result:[this.addRowDataHandler(d)]},true);
this.customSelectLastRow();
}
this.tempData.add("firstShippingGuide",d);//缓存起来
this.fp.form.findField("key").reset();
this.fp.form.findField("remark1").setValue("请先输入货号后按[确认]键选择货品!");
this.setAction(null);
this.formFocus();
},
seachShippingGuide:function(){
if(!this.shoppingGuideSelectWin){
this.shoppingGuideSelectWin = new ShoppingGuideSelectWin();
this.shoppingGuideSelectWin.on("select",this.selectedShippingGuide,this);
this.shoppingGuideSelectWin.on("show",function(){
var key = this.fp.form.findField("key").getValue();
Ext.Ajax.request({url:"employee.ejf?cmd=list&pageSize=-1&orderBy=sn&orderType=asc&status=0",
params:{sn:key},
callback :function(ops,success,response){
var map=Ext.decode(response.responseText);
this.shoppingGuideSelectWin.list.grid.store.removeAll();
if(map.result){
this.shoppingGuideSelectWin.list.grid.store.loadData(map);
}else{
this.shoppingGuideSelectWin.hide();
Disco.Ext.Util.msg("","不存在该导购员!");
}
},scope:this});
},this);
this.shoppingGuideSelectWin.on("hide",this.formFocus.createSequence(function(){this.setAction(null)},this),this);
}
this.shoppingGuideSelectWin.show();
},
autoColumn : function(lastRow){
var record = this.editGrid.store.getAt(lastRow);
var obj = record.get("product");
if(obj.attributeType===0 && obj.encaped){
record.columnSeq = ['color'];
#if(!$!session.COMPANYSETTING_IN_SESSION.useColor)
record.columnSeq = [];
#end
}else if(obj.attributeType===0 && !obj.encaped){
//record.columnSeq = ['color','sizeType'];
record.columnSeq=[];
#if($!session.COMPANYSETTING_IN_SESSION.useColor)
record.columnSeq = record.columnSeq.concat("color");
#end
#if($!session.COMPANYSETTING_IN_SESSION.useSize)
record.columnSeq = record.columnSeq.concat("sizeType");
#end
}else if(obj.attributeType===1 && obj.encaped){
record.columnSeq = ['color'];
#if(!$!session.COMPANYSETTING_IN_SESSION.useColor)
record.columnSeq = [];
#end
}else if(obj.attributeType===1 && !obj.encaped){
record.columnSeq = ['color'];
#if(!$!session.COMPANYSETTING_IN_SESSION.useColor)
record.columnSeq = [];
#end
}else if(obj.attributeType===2 && !obj.encaped){
record.columnSeq = ['sizeType'];
#if(!$!session.COMPANYSETTING_IN_SESSION.useSize)
record.columnSeq = [];
#end
}else{
record.columnSeq = [];
}
if(record.columnSeq[0]){
var column = this.editGrid.getColumnModel().findColumnIndex(record.columnSeq[0]);
/**
(function(){
this.editGrid.startEditing(lastRow,column);
var editor=this.editGrid.getColumnModel().getCellEditor(column,lastRow).field;
if(editor.store.getCount()>0){
var view = this.editGrid.getView();
(function(){
editor.onTriggerClick();
editor.list.alignTo(view.getCell(lastRow,column), 'tl-bl?');
}).defer(1000,this);
this.editGrid.startEditing(lastRow,column,true);
};
}).defer(1000,this);
*/
if('$!session.COMPANYSETTING_IN_SESSION.productInputType'!=2){
this.editGrid.startEditing(lastRow,column,true);
// this.editGrid.view.ensureVisible(lastRow,column,true);
}else{
this.customSelectRow(this.editGrid.store.getCount());
}
//(function(){this.editGrid.getSelectionModel().tryEdit(lastRow,column,true)}).defer(1000,this);//编辑下一行
}else{
this.fp.form.findField("remark1").setValue("当前库存为"+record.stockInfo.get(0));
record.set("residualStoreNum",parseInt(record.stockInfo.get(0)));
this.customSelectRow(this.editGrid.store.getCount());
this.formFocus();
}
},
formatMoney:function(v){
var fm ={1:2,2:1,3:0,4:1,5:0};
var mantissa = parseInt(fm[('$!session.COMPANYSETTING_IN_SESSION.mantissa' || 1)]||2);
if(mantissa>3)
return parseFloat(Ext.formatMoney(v,mantissa).toFixed(2));
else
return isNaN(parseFloat(v)) ? v : parseFloat((parseInt(v*Math.pow(10,mantissa))/Math.pow(10,mantissa).toFixed(2)));
},
selectProductDataHandler:function(data){
if(data && this.giftsPattern){
data.salePrice = 0;
data.status = 5;
}
var o = this.addRowForProductDataHandler(data);
this.editGrid.store.loadData({result:[o]},this.append);
this.append = true;
var lastRow = this.editGrid.store.getCount()-1;
this.editGrid.getSelectionModel().select(lastRow,0);
var status = parseInt(this.fp.form.findField("status").getValue());
var getProductStockWithStockUrl = "productStock.ejf?cmd=getProductStockWithStock"
if(status>0){
getProductStockWithStockUrl = "productStock.ejf?cmd=getProductStockWithStock&comeback=true"
}
Ext.Ajax.request({url:getProductStockWithStockUrl,params:{product:data.id},callback :function(ops,success,response){
var map=Ext.decode(response.responseText);
var m = new Ext.util.MixedCollection();
m.addAll(map);
this.editGrid.store.getAt(lastRow).stockInfo=m;
this.fp.form.findField("key").reset();
this.countAll(false);
this.autoColumn(lastRow);
//this.customSelectRow(lastRow+1);
this.haveProducts = true;
},scope:this});
},
seachProductWear:function(){
this.buildProductSelectWin();
this.productSelectWin.on("hide",function(){
this.productSelectWin.list.grid.store.removeAll();
this.formFocus();
},this,{single:true});
var key = this.fp.form.findField("key").getValue();
if(key&&key.trim().length<2){
Disco.Ext.Util.msg("","输入货号的长度至少两个字符!");
this.formFocus();
return false;
}
this.productSelectWin.show();
this.productSelectWin.list.grid.getGridEl().mask("加载库存商品...","x-mask-loading");
var status = this.fp.form.findField("status").getValue();
var getProductUrl = "productStock.ejf?cmd=productStockWearByDepot"
status = parseInt(status);
if(status>0){
getProductUrl = "productStock.ejf?cmd=productStockWearByDepot&comeback=true"
}
Ext.Ajax.request({url:getProductUrl,
params:{sn:key},
callback :function(ops,success,response){
var map=Ext.decode(response.responseText);
var tag = false;
for (var n in map) {
if(n==="tag")tag = true;
}
if(tag){
Disco.Ext.Util.msg("","请设置零售库,请设置零售库!");
this.productSelectWin.hide();
this.formFocus();
this.productSelectWin.list.grid.getGridEl().unmask();
return false;
}else if(!map || !map.result){
Disco.Ext.Util.msg("","该货品不存在或者是库存中没有了!");
this.productSelectWin.hide();
this.formFocus();
this.productSelectWin.list.grid.getGridEl().unmask();
return false
}else{
this.productSelectWin.list.grid.store.removeAll();
this.productSelectWin.list.grid.store.loadData(map);
}
this.productSelectWin.list.grid.getGridEl().unmask();
},scope:this});
},
formFocus:function(){
this.fp.form.findField("key").focus(false,100);
this.fp.form.findField("key").reset();
},
customSelectRow:function(row){
this.clearRowSelections();
this.selectedRow=row;//从一开始
//this.editGrid.getSelectionModel().select(row-1,0);
this.editGrid.getView().onRowSelect(row-1);
this.editGrid.getView().focusRow(row-1);
var record =this.getSelectedRecord();
if(record&&record.get("product").id){
this.fp.form.findField("remark1").setValue("当前库存为"+record.get("residualStoreNum"));
}
},
customSelectFirstRow:function(){ //down
if(!this.selectedRow)
this.customSelectRow(1);
else{
if(this.selectedRow==this.editGrid.store.getCount()){
this.customSelectRow(1);
}else{
this.customSelectRow(this.selectedRow+1);
}
}
},
customSelectLastRow:function(){ //up
if(!this.selectedRow){
this.customSelectRow(this.editGrid.store.getCount());
}else{
if(this.selectedRow==1){
this.customSelectRow(this.editGrid.store.getCount());
}else{
this.customSelectRow(this.selectedRow-1);
}
}
},
clearRowSelections : function(){
var count = this.editGrid.store.getCount();
for (var index = 0; index < count; index++) {
this.editGrid.getView().onRowDeselect(index);
}
this.editGrid.getSelectionModel().clearSelections();
},
baseEditGridListeners:{
beforerequirededit:function(grid,row,col){
return true;
},
beforeedit : function(e) {
if(e.record.columnSeq.indexOf(e.field)==-1){
return false;
}
if(e.field=="color" ){
var stockInfo = e.record.stockInfo;
var colors = [];
stockInfo.each(function(o){
if(o[0] && colors.indexOf(o[0])<0){
colors.push(o[0]);
}
});
this.colorEditor.store.loadData(colors);
}else if(e.field=="sizeType"){
var stockInfo = e.record.stockInfo;
var sizeTypes = [];
if(e.record.get("color")){
stockInfo= stockInfo.filterBy(function(o){
if(o[0].id==e.record.get("color").value){
return o;
}
},this);
stockInfo.each(function(o){
if(o[1] && sizeTypes.indexOf(o[1])){
sizeTypes.push(o[1]);
}
})
}else{
stockInfo.each(function(o){
if(o[0] && sizeTypes.indexOf(o[0])<0){
sizeTypes.push(o[0]);
}
});
}
this.sizeTypeEditor.store.loadData(sizeTypes);
}
},
afteredit : function(e) {
var s="price,num,salePrice,encapNum";
if (s.indexOf(e.field)>=0 ||e.field.indexOf("size-")>=0) {// 计算合计
this.autoCountData(e.record);
}
if(e.field == "color"){
if(e.record.columnSeq[1]){
var column = this.editGrid.getColumnModel().findColumnIndex(e.record.columnSeq[1]);
this.editGrid.startEditing(e.row,column,true);
}
}
if(e.record.columnSeq.length>0&&e.record.columnSeq.length==1){
var lastField = e.record.columnSeq[e.record.columnSeq.length-1];
if(e.field == lastField){
var stockInfo = e.record.stockInfo;
var index = stockInfo.findIndexBy(function(o){
if(o[0] && o[0].id == e.record.get(lastField).value){
return true;
}
});
if(index>=0){
var o = stockInfo.itemAt(index);
var remark1 = o[1];
this.fp.form.findField("remark1").setValue("当前库存为"+remark1);
e.record.set("residualStoreNum",remark1);
this.formFocus();
}
}
}else if(e.record.columnSeq.length>0&&e.record.columnSeq.length==2){
var lastField = e.record.columnSeq[e.record.columnSeq.length-1];
if(e.field == lastField){
var color = e.record.get("color")?e.record.get("color").value:null;
var sizeType = e.record.get("sizeType")?e.record.get("sizeType").value:null;
if(color||sizeType){
var stockInfo = e.record.stockInfo;
var index = stockInfo.findIndexBy(function(o){
if(o[0] && o[0].id==color && (o[1].id||false)==sizeType){
return true;
}
});
}
var remark1 = "";
if(index>=0){
var o = stockInfo.itemAt(index);
remark1 = o[2];
}else{
if(e.field=='sizeType'){
e.record.set("color",null);
}else{
e.record.set("sizeType",null);
}
}
this.fp.form.findField("remark1").setValue("当前库存为"+remark1);
e.record.set("residualStoreNum",remark1);
this.formFocus();
}
}
/* if(e.field == "sizeType"){
if(!e.record.data.color){
var stockInfo = e.record.stockInfo;
var index = stockInfo.findIndexBy(function(o){
if(o[0].id == e.record.get("sizeType").value){
return true;
}
});
if(index>=0){
var o = stockInfo.itemAt(index);
remark1 = o[1];
this.fp.form.findField("remark1").setValue("当前库存为"+remark1);
e.record.set("residualStoreNum",remark1);
}
}
}*/
if(this.afterEdit) this.afterEdit(e);
}
},
afterEdit:function(e){
this.customSelectRow(e.row+1);
},
onSave:function(form,action){
this.tempData.clear();
var ret = Ext.decode(action.response.responseText);
if(ret.data.yanzhi){
Ext.MessageBox.alert("提示",ret.data.msg,function(){
this.fp.form.findField("key").setDisabled(false);
},this);
this.complete = false;
this.payment = false;
var paymentCount = this.paymentGrid.store.getCount();
this.fp.form.findField("remark1").setValue("取消付款!");
this.fp.form.findField("received").setValue(null);
this.fp.form.findField("receive").setValue(null);
this.fp.form.findField("unpaid").setValue(null);
this.fp.form.findField("key").setValue(null);
this.paid = 0.00;
this.paymentGrid.store.removeAll();
this.countPay();
return false;
}
if(this.win){
(function(){this.create()}).defer(1000,this);
}
if(ret.success&&!this.noPrint)
if(ret.data){
if(!ret.data['xml'] && !Ext.isIE){
window.location.href="Lanyowebprinter://webprint/"+ret.data
}else if(ret.data['xml']){
Ext.Ajax.request({url:this.baseUrl,params:{cmd:"print",id:ret.data.id},callback:function(options,success,response){
Disco.Ext.Util.executeLocalCommand("retailPostPrint",response.responseText);
}});
//Disco.Ext.Util.executeLocalCommand("retailPostPrint",ret.data.xml);
}
}
this.vipUser = null;
if(this.vipWin)this.vipWin.hide();
},
beforeSave:function(){
var o = Disco.Ext.Util.getEditGridData(this.paymentGrid,"payment_");
var charge = this.fp.form.findField("charge").getValue();
o.payment_paymentSum[0]=o.payment_paymentSum[0]-charge;
this.fp.form.baseParams = Ext.applyIf(this.fp.form.baseParams,o);
if(this.vipUser)
Ext.apply(this.fp.form.baseParams,{cardNumber:this.vipUser.cardNumber});
if(this.beforeSaveCheck()===false){
return false;
}
},
comboGetValue:function(obj){
return obj ? Ext.value((obj.id || obj.value),'') : '';
},
//检查销售数量和库存数量
otherCheckNum:function(){
var checkDataMx = new Ext.util.MixedCollection(false);
var store=this.editGrid.store;
store.each(function(record){
var product = this.comboGetValue(record.get("product"));
var color = this.comboGetValue(record.get("color"));
var sizeType = this.comboGetValue(record.get("sizeType"));
var num = record.get("num");
var key = (product+"_"+color+"_"+sizeType).toString();
if(checkDataMx.containsKey(key)){
var previousNum = checkDataMx.key(key);
checkDataMx.replace(key,previousNum+num);
}else{
checkDataMx.add(key,num);
}
},this);
var mc = checkDataMx.getCount();
var o = {};
if(mc>0){
o["item_product"] = [];
o["item_color"] = [];
o["item_sizeType"] = [];
o["item_num"] = [];
}
checkDataMx.eachKey(function(key,item,index){
var param = key.split("_");
var num = checkDataMx.get(key);
o["item_product"][index] = param[0];
o["item_color"][index] = param[1];
o["item_sizeType"][index] = param[2];
o["item_num"][index] =num;
},this);
Ext.Ajax.request({url:"retailBill.ejf?cmd=checkProductStock",
method:"POST",
params:o,
success:function(response){
var ret = Ext.decode(response.responseText);
if(!ret.success){
var errors = "";
Ext.each(ret.data,function(error){
errors+=error.sn;
if(error.color){
errors+=("-"+error.color);
}else{
errors+=";"
}
if(error.sizeType){
errors+=("-"+error.sizeType);
}else{
errors+=";"
}
});
errors+="销售的数量不能够大于库存!请确定销售数量";
Ext.MessageBox.alert("提示",errors,function(){
this.formFocus();
},this);
this.payment=false;
}else{
this.readyPay();
}
},
scope:this
});
},
readyPay : function(){
this.payment=true;
var count = this.editGrid.store.getCount();
var sum = this.editGrid.store.sum("totalAmount",0,count-1);
Disco.Ext.Util.msg("提示","未付款 "+ this.toFixed(sum));
this.fp.form.findField("unpaid").setValue(this.toFixed(sum));
this.fp.form.findField("remark1").setValue("货品输入完毕,请开始付款");
this.formFocus();
},
cancelPreferential:function(){
this.payment=true;
var count = this.editGrid.store.getCount();
var sum = this.editGrid.store.sum("totalAmount",0,count-1);
Disco.Ext.Util.msg("提示","未付款 "+ this.toFixed(sum));
this.fp.form.findField("receivable").setValue(this.toFixed(sum));
this.fp.form.findField("unpaid").setValue(this.toFixed(sum));
this.fp.form.findField("remark1").setValue("货品输入完毕,请开始付款");
this.fp.form.findField("preferential").setValue("");
this.formFocus();
},
onPreferential:function(){
var status = parseInt(this.fp.form.findField("status").getValue());
if(status==0 && this.payment && !this.fp.findSomeThing("preferential").getValue()){
Disco.Ext.Util.msg("提示","请输入整单优惠后价格");
this.setAction("preferential");
this.payment=false;
}
},
doPreferential:function(){
var key = this.fp.form.findField("key").getValue();
if(!key || isNaN(parseFloat(key))){
Ext.MessageBox.alert("提示","请输入正确的金额!",function(){
this.formFocus();
},this);
return false;
}else{
this.payment=true;
Disco.Ext.Util.msg("提示","未付款 "+ key);
this.fp.form.findField("unpaid").setValue(this.toFixed(key));
this.fp.form.findField("receivable").setValue(this.toFixed(key));
this.fp.form.findField("remark1").setValue("开始付款");
var sum = this.editGrid.store.sum("totalAmount",0,this.editGrid.store.getCount()-1);
this.fp.form.findField("preferential").setValue(this.toFixed(sum-key));
this.formFocus();
}
},
beforeSaveCheck:function(otherCheck){
var store=this.editGrid.store;
if(store.getCount()==0 || (store.getCount()==1 && store.getAt(0).get("product") && isNaN(parseInt(store.getAt(0).get("product").id)))){
Ext.Msg.alert("错误提示","没有单据明细,不能保存!");
return false;
}
var sumGifts = 0;
if(store && store.getCount()>=1){
var notNull=[];
var canSave=true;
store.each(function(record,sequence){
if(record.get('status')==5 && record.get('gifts')){
sumGifts+=(isNaN(parseFloat(record.get('gifts'))) ? 0 : parseFloat(record.get('gifts'))) ;
}
if(!isNaN(parseInt(record.get("product")))){
var temp={};
if(record.columnSeq.length>0){
Ext.each(record.columnSeq,function(o){
if(!record.get(o).value){
temp.sequence=sequence+1;
if(0=="sizeType"){
temp.nf = "尺码";
}else{
temp.nf = "颜色";
}
if(canSave) canSave=false;
}
},this)
}
/*if(!r.get("color") && (r.get("product").attributeType==0 ||r.get("product").attributeType==1)){
temp.sequence=sequence+1;
temp.nf=["颜色"];
if(canSave) canSave=false;
}
if(!r.get("num") || r.get("num")==0 || r.get("num")=='0'){
if(temp.sequence){
temp.nf.push("数量");
}else{
temp.sequence=sequence+1;
temp.nf=["数量"];
}
}
*/
if(otherCheck && otherCheck.call(this,record,temp)===false){
temp.sequence=sequence+1;
if(canSave) canSave=false;
}
if(temp.sequence)
notNull.push(temp);
};
},this);
if(notNull.length>0){
if(!canSave){
var s="以下行数据错误,不能保存:<br>";
for(var i=0;i<notNull.length;i++){
var temp=notNull[i];
s+="行 "+temp.sequence+" : "+temp.nf+" 不能为空! <br>";
}
Ext.Msg.alert("错误提示",s,function(){
this.formFocus();
this.fp.form.findField("key").setDisabled(false);
},this);
return false;
}
}
}
if(sumGifts>0){
if(!this.vipUser){
Disco.Ext.Msg.error("表单中存在赠送商品!<br\>请你先选择会员在保存!",false,this.formFocus,this);
return false;
}else{
this.vipUser.integration = parseFloat(this.vipUser.integration) || 0;
if(this.vipUser.integration<sumGifts){
Disco.Ext.Msg.error("会员的积分不足!",false,this.formFocus,this);
return false;
}
}
}
return BaseStockOutcomeWearBillPanel.superclass.beforeSave.call(this);
},
countPay:function(){
var count = this.paymentGrid.store.getCount();
this.paid = this.paymentGrid.store.sum("paymentSum",0,count-1);
var count = this.editGrid.store.getCount();
var sum = parseFloat(this.fp.findSomeThing("receivable").getValue());
if(this.paid>sum){
return false;
}else if(this.paid==sum){ //完成付款了
this.complete = true;
Disco.Ext.Util.msg("提示","支付成功!请按任意键保存数据并且重新开单!");
this.fp.form.findField("remark1").setValue("支付成功!请按任意键保存数据并且重新开单!按[取消]键取消交易!");
}
this.fp.form.findField("receive").setValue(this.toFixed(this.paid));
this.fp.form.findField("received").setValue(this.toFixed(this.paid));
this.fp.form.findField("unpaid").setValue(sum-this.paid);
this.fp.form.findField("total").setValue(this.toFixed(sum));
},
countReceivable:function(){ //计算应售
var receivableTotal = 0.0;
this.editGrid.store.each(function(record){
if(record.get("num")&&record.get("salePrice")){
receivableTotal+=Ext.num(parseFloat(record.get("num")),0)* Ext.num(parseFloat(record.get("salePrice")));
}
},this);
this.fp.form.findField("behoveSell").setValue(this.toFixed(receivableTotal));
},
countRealizedSell:function(){ //计算实售
var count = this.editGrid.store.getCount();
var sum = this.editGrid.store.sum("totalAmount",0,count-1);
this.fp.form.findField("realizedSell").setValue(this.toFixed(sum));
this.fp.form.findField("receivable").setValue(this.toFixed(sum));
},
countNumber : function(){ //计算卖货数量
var count = this.editGrid.store.getCount();
var sum = this.editGrid.store.sum("num",0,count-1);
this.fp.form.findField("number").setValue(sum);
},
countPrivilege:function(){ //计算优惠
var count = this.editGrid.store.getCount();
var receivableTotal = 0.0;
this.editGrid.store.each(function(record){
if(record.get("num")&&record.get("salePrice")){
receivableTotal+=parseFloat(record.get("num"))*parseFloat(record.get("salePrice"));
}
},this)
var factReceivable = this.editGrid.store.sum("totalAmount",0,count-1);
this.fp.form.findField("privilege").setValue(this.toFixed((receivableTotal-parseFloat(factReceivable))));
},
getSelectedRecord:function(){
if(this.selectedRow){
return this.editGrid.store.getAt(this.selectedRow-1);
}
return this.editGrid.getSelectionModel().getEditRowRecord()
},
getDisCount:function(dis){
return ;
},
countAll:function(focus){
this.countNumber();
this.countReceivable();
this.countRealizedSell();
this.countPrivilege();
if(focus)this.formFocus();
},
updateNumber:function(){
if(!this.haveProducts) return false;
if(this.payment) return false;
var selectRecord =this.getSelectedRecord();
var num = this.fp.form.findField("key").getValue();
var status = this.fp.form.findField("status").getValue();
if(!Disco.Ext.Util.isNumber(num)){
Disco.Ext.Util.msg("提示","请输入数字!");
return false;
}
//退货不检查输入的数量
if(parseInt(status)==0&&selectRecord.get("residualStoreNum")<parseInt(num)){
Disco.Ext.Util.msg("提示","输入的数量大于当前库存数量,请重新输入!");
return false;
}else if(parseInt(status)>0&&parseInt(num)<0){
Disco.Ext.Util.msg("提示","在退货模式下面不能录入负数!");
return false;
}
selectRecord.set("num",parseInt(num));
this.autoPrice(selectRecord,"num");
this.countAll(true);
},
delProduct:function(){ //按下Esc时删除
if(!this.haveProducts) return false;
if(this.payment) return false;
/* var selectRecord = this.getSelectedRecord();
this.editGrid.store.remove(selectRecord);*/
this.removeGridRow(this.editGrid);
this.editGrid.getView().refresh();
this.countAll(true);
if(this.editGrid.store.getCount()<1)this.tempData.clear("firstShippingGuide");
},
removeGridRow:function(grid,callback){
if(this.selectedRow){
var r=this.getSelectedRecord();
grid.store.remove(r);
if(grid.store.getCount()<this.selectedRow){
this.selectedRow--;
this.customSelectRow(this.selectedRow);
}
}
else Ext.MessageBox.alert("提示","请选择要删除的记录!");
},
updateColor:function(){
if(!this.haveProducts) return false;
if(this.payment) return false;
var selectRecord = this.getSelectedRecord();
var rowIndex = this.editGrid.store.indexOf(selectRecord);
var column = this.editGrid.getColumnModel().findColumnIndex("color");
this.editGrid.startEditing(rowIndex,column,false);
/**
var colorEditor=this.editGrid.getColumnModel().getCellEditor(column,rowIndex).field;
if(colorEditor.store.getCount()>0){
var view = this.editGrid.getView();
(function(){
colorEditor.onTriggerClick();
colorEditor.list.alignTo(view.getCell(rowIndex,column), 'tl-bl?');
}).defer(1000,this);
}
*/
},
updateSizeType:function(){
if(!this.haveProducts) return false;
if(this.payment) return false;
var selectRecord = this.getSelectedRecord();
var rowIndex = this.editGrid.store.indexOf(selectRecord);
var column = this.editGrid.getColumnModel().findColumnIndex("sizeType");
this.editGrid.startEditing(rowIndex,column,false);
/**
var sizeTypeEditor=this.editGrid.getColumnModel().getCellEditor(column,rowIndex).field;
if(sizeTypeEditor.store.getCount()>0){
var view = this.editGrid.getView();
(function(){
sizeTypeEditor.onTriggerClick();
sizeTypeEditor.list.alignTo(view.getCell(rowIndex,column), 'tl-bl?');
}).defer(1000,this);
}
*/
},
updateDiscount:function(){ //选中一行,按home键修改折扣
if(!this.haveProducts) return false;
if(this.payment) return false;
var selectRecord = this.getSelectedRecord();
var discount = this.fp.form.findField("key").getValue();
if(!Disco.Ext.Util.isNumber(discount)){
Disco.Ext.Util.msg("提示","请输入数字!");
return false;
}
discount = parseFloat(discount);
selectRecord.set("discount",discount.toFixed(2));
this.autoPrice(selectRecord,"discount");
this.countAll(true);
},
updateDiscountPrice:function(){ //选中一行,按End键修改优惠价
if(!this.haveProducts) return false;
if(this.payment) return false;
var selectRecord = this.getSelectedRecord();
var discountPrice = this.fp.form.findField("key").getValue();
if(!Disco.Ext.Util.isNumber(discountPrice)){
Disco.Ext.Util.msg("提示","请输入数字!");
return false;
}
discountPrice = parseFloat(discountPrice);
selectRecord.set("discountPrice",discountPrice.toFixed(0));
this.autoPrice(selectRecord,"discountPrice");
this.countAll(true);
},
updateSalePrice:function(){ },
comeback:function(){
var data=[[1,'质量问题'],[2,'客户不满意'],[3,'换货'],[4,'未知原因']];
var store=new Ext.data.SimpleStore({fields:["id","name"]});
var grid = new Ext.grid.GridPanel({
border:false,
frame:false,
selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
height:130,
width:180,
columns:[{header:"No",dataIndex:"id"},
{header:"退货原因",dataIndex:"name"}],
store:store,
autoExpandColumn:1
});
var choice = function(grid2,rowIndex,e) {
var record = grid.getSelectionModel().getSelected();
if(record){
var retailType = this.fp.form.findField("retailType");
retailType.setValue(record.get("name"));
retailType.el.parent('div.x-form-item').first('label').dom.innerHTML = "退货";
this.fp.form.findField("behoveSell").el.parent('div.x-form-item').first('label').dom.innerHTML = "应收:";
this.fp.form.findField("realizedSell").el.parent('div.x-form-item').first('label').dom.innerHTML = "实收:";
this.fp.form.findField("receivable").el.parent('div.x-form-item').first('label').dom.innerHTML = "应付:";
this.fp.form.findField("received").el.parent('div.x-form-item').first('label').dom.innerHTML = "已付:";
this.fp.form.findField("status").setValue(record.get("id"));
}
win.hide();
};
grid.on("rowdblclick",choice, this);
store.on("load", function() {
(function(){grid.getSelectionModel().selectRow(0);
grid.getView().focusRow(0);}).defer(200);
},this);
if(!win)
var win = new Ext.Window({
width:250,
autoHeight:true,
layout:'fit',
modal: true,
closeAction:"hide",
shim:true,
items:grid,
onEsc : function(){
this[this.closeAction]();
},
keys:[{key : Ext.EventObject.ENTER,
fn : choice,
scope:this,
stopEvent:true}]
});
win.on("show",function(){
win.getEl().setOpacity(0.9);
store.loadData(data);
},this);
return (function(k,e){
if(e.ctrlKey) return false;
//if(!this.tempData.containsKey("firstShippingGuide")) return false;
//如果有了货品就不能够再改变销售或者退货的状态了.
if(this.editGrid.getStore().getCount()>0){
var product = this.editGrid.getStore().getAt(0).get("product");
if(product.id) return false;
}
win.on("hide",function(){
this.formFocus.defer(50,this);
},this)
win.show(this.fp.form.findField("key").getEl());
});
},
createCreditCardTypeWin : function(k,e){
if(e && e.ctrlKey) return false;
if(!this.payment) return false;
var status = this.fp.form.findField("status").getValue();
status = parseInt(status);
if(status>0){
Disco.Ext.Util.msg("提示","在退货模式只能用信用卡!");
return false;
}
Ext.each(this.paymentTypes,function(o){
if(o.name=="信用卡"){
this.paymentTypeTitle = "信用卡";
Disco.Ext.Util.msg("提示","信用卡支付!");
this.paymentTypeId = o.id;
}
},this);
var store=new Ext.data.JsonStore({fields:["id","title"]});
var grid = new Ext.grid.GridPanel({
border:false,
frame:false,
selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
height:130,
width:180,
columns:[
new Ext.grid.RowNumberer({header:"序号",width:33}),
{header:"信用卡类型",dataIndex:"title"},
{header:"id",dataIndex:"id",hidden:true}
],
store:store,
autoExpandColumn:1
});
var choice = function(grid2,rowIndex,e) {
this.cardFormPanel = new Ext.form.FormPanel({
labelWidth:60,
labelAlign:"right",
height:160,
width:180,
autoShow:true,
defaults:{style:"font-size:25px;font-weight:bold;padding-top:3px",labelStyle:"font-weight:bold;font-size:25px;width:65px;"},
items:[{xtype:"hidden",name:"cardTypeId"},
{xtype:"labelfield",fieldLabel:"类型",name:"cardType"},
{xtype:"numberfield",fieldLabel:"卡号",name:"cardNO",enableKeyEvents:true,width:300,height:50,
listeners:{
"keypress":function(field,e){
if(e.getKey() == Ext.EventObject.ENTER){
if(field.getValue()){
this.cardFormPanel.form.findField("cardAmount").focus();
}else{
Ext.MessageBox.alert("提示","信用卡号不能够为空!",function(){
field.focus();
},this);
}
}
},
scope:this
}},
{xtype:"numberfield",fieldLabel:"金额",name:"cardAmount",enableKeyEvents:true,width:300,height:50,
listeners:{
"keypress":function(field,e){
if(e.getKey() == Ext.EventObject.ENTER){
var cardTypeId = this.cardFormPanel.form.findField("cardTypeId").getValue();
var cardNO = this.cardFormPanel.form.findField("cardNO").getValue();
var cardAmount = this.cardFormPanel.form.findField("cardAmount").getValue();
if(cardNO&&cardAmount){
this.paymentGrid.store.loadData([{paymentType:this.paymentTypeId,paymentTypeTitle:this.paymentTypeTitle,paymentSum:cardAmount,cardType:cardTypeId,cardNO:cardNO}],true);
if(this.countPay()===false){
var paymentCount = this.paymentGrid.store.getCount();
var record = this.paymentGrid.store.getAt(paymentCount-1);
this.paymentGrid.store.remove(record);
this.countPay();
Ext.Msg.alert("错误提示","有信用卡支付的不能超出应收账款!将取消该信用卡支付",function(){
this.formFocus();
},this);
win.purgeListeners();
}
this.paymentTypeId = false; //设置为false 是为了再次付款为现金的形式
win.hide();
}else{
return false;
}
}
},
scope:this
}
}]
});
var p=win.remove(0);
win.add(this.cardFormPanel);
win.setHeight(180);
win.setWidth(400);
win.doLayout();
win.mask.on("click",function(){this.cardFormPanel.form.findField("cardNO").focus();},this)
var record = grid.getSelectionModel().getSelected();
if(record){
this.cardFormPanel.form.findField("cardTypeId").setValue(record.get("id"));
this.cardFormPanel.form.findField("cardType").setValue(record.get("title"));
this.cardFormPanel.form.findField("cardNO").focus();
}
};
grid.on("rowdblclick",choice, this);
grid.on("keypress",function(e){
if(e.getKey() == Ext.EventObject.ENTER){
choice.call(this);
}
},this);
store.on("load", function() {
(function(){
grid.getSelectionModel().selectRow(0);
grid.getView().focusRow(0);
}).defer(100);
},this);
if(!win)
var win = new Ext.Window({
width:300,
height:150,
autoHeight:true,
layout:'fit',
modal: true,
closeAction:"hide",
shim:true,
items:grid,
onEsc : function(){
this[this.closeAction]();
}
});
win.on("show",function(){
Ext.Ajax.request({url:"companyDictionary.ejf?cmd=getDictionaryItemBySn",
params:{sn:"creditCardType"},
scope:this,
success:function(response){
var ret = Ext.decode(response.responseText);
win.getEl().setOpacity(0.9);
if(ret&&ret.result&&ret.result.length>0){
store.loadData(ret.result);
}else{
Ext.MessageBox.alert("提示","请设置信用卡的类型!",function(){
this.paymentTypeId = false;
win.hide();
},this)
}
}
})
},this,{single:true});
win.on("hide",function(){
this.paymentTypeId = false;
this.formFocus.defer(50,this);
},this,{single:true});
if(win.getComponent(0).getXType()==="form"){
win.remove(0);
win.setHeight(180);
win.setWidth(130);
win.add(this.cardFormPanel);
win.doLayout();
}
win.show();
var xy = win.el.getAlignToXY(win.container, 'c-r',[-260, -130]);
win.setPagePosition(xy[0], xy[1]);
},
getEditColumnModel:function(){
this.productEditor=new ProductComboBox(Ext.apply({},{
returnObject:true,
name:"productInput",
hiddenName:"productInput",
displayField:"sn",
valueField:"id",
width:300,
selectSingle:true,
mode:"local", //禁止远程调用,
choiceValue:this.selectRowData.createDelegate(this)
},ConfigConst.CRM.product));
/*this.depotLocationEditor=new Disco.Ext.SmartCombox({
returnObject:true,
name : "depotLocationInput",
hiddenName : "depotLocationInput",
fieldLabel : "depotLocationInput",
displayField : "title",
valueField : "id",
store : new Ext.data.JsonStore({
fields : ["id",'title']
}),
editable : false,
mode : 'local',
triggerAction : 'all',
emptyText : '请选择...'
}
); */
this.colorEditor=new Disco.Ext.SmartCombox({
returnObject:true,
name : "colorInput",
hiddenName : "colorInput",
fieldLabel : "colorInput",
displayField : "title",
valueField : "id",
allowBlank:false,
store : new Ext.data.JsonStore({
fields : ["id","sn","title"]
}),
editable : false,
mode : 'local',
triggerAction : 'all',
emptyText : '请选择...'
});
this.sizeTypeEditor=new Disco.Ext.SmartCombox({
returnObject:true,
name : "sizeTypeInput",
hiddenName : "sizeTypeInput",
fieldLabel : "sizeTypeInput",
displayField : "title",
valueField : "id",
allowBlank:false,
typeAhead:true,
store : new Ext.data.JsonStore({
fields : ["id","sn","title"]
}),
editable : false,
mode : 'local',
triggerAction : 'all',
emptyText : '请选择...',
listeners:{"blur":function(){
this.formFocus();
},scope:this}
});
var cms=[
new Ext.grid.RowNumberer({header:"<font size='3' color='000000'>序号</font>",dataIndex:"sequence",width:40}),
{header:"Id",dataIndex:"id",width:1,hidden:true,hideable:false},
{dataIndex:"status",width:1,hidden:true,hideable:false},
{dataIndex:"gifts",width:1,hidden:true,hideable:false},
{header:"<font size='3' color='000000'>导购员</font>",dataIndex:"shoppingGuide",width:60,hidden:false,renderer:this.objectRender("trueName")},
{header:"<font size='3' color='000000'>产品</font>",dataIndex:"product",width:0,hidden:true,hideable:false},
// {header:"<font size='3' color='000000'>货品编号</font>",dataIndex:"stockNO",width:70,editor:this.productEditor,summaryType: 'count',summaryRenderer: function(v){return "合计("+v+")";}},
{header:"<font size='3' color='000000'>货号</font>",dataIndex:"productSn",width:80},
{header:"<font size='3' color='000000'>产品名称</font>",dataIndex:"productTitle",width:80},
{header:"<font size='3' color='000000'>款型</font>",dataIndex:"product",width:80,renderer:this.objectRender("style")},
{header:"<font size='3' color='000000'>颜色</font>",dataIndex:"color",width:70,editor:this.colorEditor,renderer:Disco.Ext.Util.comboxRender},
{header:"<font size='3' color='000000'>尺码</font>",dataIndex:"sizeType",width:50,editor:this.sizeTypeEditor,renderer:Disco.Ext.Util.comboxRender}
]
Ext.each([{header:"<font size='3' color='000000'>单价</font>",dataIndex:"price",width:50,hidden:true,renderer:this.readOnlyRender(function(v){return v&&v.toFixed?v.toFixed(2):v;})},
{header:"<font size='3' color='000000'>数量</font>",dataIndex:"num",width:50,editor:new Ext.form.NumberField({selectOnFocus:true}),renderer:this.numEditRender,summaryType: 'sum',summaryRenderer: function(v){return v?v.toFixed(2):"";}},
{header:"<font size='3' color='000000'>零售价</font>",dataIndex:"salePrice",width:70,renderer:function(v){return v&&v.toFixed?v.toFixed(2):v;}},
{header:"<font size='3' color='000000'>折扣</font>",dataIndex:"discount",width:50,editor:new Ext.form.NumberField({selectOnFocus:true})},
{header:"<font size='3' color='000000'>实售价</font>",dataIndex:"discountPrice",width:70,editor:new Ext.form.NumberField({selectOnFocus:true})},
{header:"<font size='3' color='000000'>金额</font>",dataIndex:"totalAmount",width:70,renderer:function(v){return v&&v.toFixed?v.toFixed(2):v;},summaryType:'sum',summaryRenderer: function(v, params, data){return v?v.toFixed(2):"";}},
{header:"<font size='3' color='000000'>剩余库存</font>",dataIndex:"residualStoreNum",width:70,hidden:true,summaryType: 'sum',summaryRenderer: function(v){return v?v.toFixed(2):"";}},
{header:"<font size='3' color='000000'>备注</font>",renderer:function(v,m,r){
if(r.get('status')==5){
return String.format("<font style='font-weight:bold;color:orangered;'>赠品(积分{0}兑换)</font>",!isNaN(parseInt(r.get('gifts'))) ? parseInt(r.get('gifts')) : 0);
}
},dataIndex:"remark",editor:new Ext.form.TextField()}],function(o){
cms[cms.length]=o;
});
return new Ext.grid.ColumnModel(cms);
},
createEditGrid:function(){
PosPanel.superclass.createEditGrid.call(this);
this.paymentGrid = this.createPaymentGrid.call(this);
this.paymentGrid.width = 300;
this.paymentGrid.border = false;
this.paymentGrid.height=95;
},
otherKeyFn:function(action){
switch(action){
case 'vipCard':
this.setAction('onMember');
break;
}
},
onHotKeySrowClick:function(grid,row,e){
var record = grid.getStore().getAt(row);
var action = record.get('action');
if(typeof this[action] == 'function'){
this[action]();return;
}else{
this.otherKeyFn(action);
}
},
createForm:function(){
this.createEditGrid();
var hotkeysInfo = new HotkeysInfo();
hotkeysInfo.grid.on('rowclick',this.onHotKeySrowClick,this);
this.editGrid.anchor="* -95";
this.editGrid.selModel = new Ext.grid.CellSelectionModel({singleSelect:true,
getEditRowRecord:function(){
return this.selection? this.selection.record : null;
},
moveEditorOnEnter:false});
this.editGrid.selModel.on("cellselect",function(sm,row,colum){
if(colum==0){
this.editGrid.getView().onRowSelect(row);
this.editGrid.getView().focusRow(row);
}
},this);
this.editGrid.on("cellclick",function(grid,rowIndex,columnIndex){
if(columnIndex == 0){
this.customSelectRow(rowIndex + 1);
}
},this);
var formPanel=new Ext.form.FormPanel({
//frame:true,
labelWidth:20,
labelAlign:'right',
layout:"border",
items:[{xtype:"hidden",name:"saveAndPrint",value:"true"},{xtype:"hidden",name:"preferential"},{xtype:"hidden",name:"vdate"},{xtype:"hidden",name:"id"},{xtype:"hidden",name:"total"}/*,{xtype:"hidden",name:"paymentType"}*/,{xtype:"hidden",name:"charge"},{xtype:"hidden",name:"receive"},{xtype:"hidden",name:"status",value:0},
{xtype:"hidden",name:"types"},hotkeysInfo,{region:"center",layout:"border",border:false,items:[{region:"center",layout:"fit",items:[this.editGrid]},
{border:false,region:"south",height:280,items:[{xtype:'panel',layout:"column",items:[{
columnWidth: .7,
layout:"column",
height:150,
border:false, //有两种状态, 一种是退货, 一种是售出
items:[{columnWidth:0.33,layout:"form",height:145,items:[
{xtype:"labelfield",fieldLabel:"销售",name:"retailType",anchor:"100%",labelStyle:"font-weight:bold;font-size:30px;color:#00F",labelSeparator:""},
{xtype:"labelfield",fieldLabel:"VIP",name:"vip",anchor:"100%",labelStyle:"font-weight:bold;font-size:25px",style:"font-size:25px;padding-top:3px"},
{xtype:"labelfield",fieldLabel:"数量",name:"number",anchor:"100%",labelStyle:"font-weight:bold;font-size:25px",style:"font-size:25px;padding-top:3px"}]},
{columnWidth:0.33,layout:"form",height:145,defaults:{anchor:"100%",labelStyle:"font-weight:bold;font-size:25px;width:65px;",style:"font-size:25px;padding-top:3px"},items:[{xtype:"labelfield",fieldLabel:"应售",name:"behoveSell",anchor:"100%"},
{xtype:"labelfield",fieldLabel:"实售",anchor:"100%",name:"realizedSell"},
{xtype:"labelfield",fieldLabel:"优惠",anchor:"100%",name:"privilege"}]},
{columnWidth:0.34,layout:"form",defaults:{anchor:"100%",labelStyle:"font-weight:bold;font-size:25px;width:65px;",style:"font-size:25px;padding-top:3px"},height:145,items:[
{xtype:"labelfield",fieldLabel:"应收",name:"receivable"},
{xtype:"labelfield",fieldLabel:"已收",name:"received"},
{xtype:"labelfield",fieldLabel:"未付",name:"unpaid"}
]}]
},{
height:145,
columnWidth: .3,
layout:"fit",
items:this.paymentGrid
}]},
{height:100,xtype:'panel',bodyStyle:"padding-buttom:17px;padding-top:17px;padding-left:50px",items:[
Disco.Ext.Util.columnPanelBuild(
{columnWidth:.4,items:new Ext.form.TextField({name:"key",
width:250,height:70,
allowBlank: false,
hideLabel:true,
anchor:"-2",
enableKeyEvents:true,
style:"font-weight:bold;font-size:55px",
listeners:{keyup:function(field,event){
if(field.getValue()){
field.setValue(field.getValue().trim().toUpperCase());
}
if(this.complete&&event.getKey()!=Ext.EventObject.ESC){
field.setDisabled(true);
this.save();
/*Ext.MessageBox.confirm("请确认","你确定要提交该次交易吗?",function(ret){
if(ret=="yes"){
field.setDisabled(true);
this.save();
}else{
field.setDisabled(false);
this.formFocus();
}
},this);
if(event.getKey()==Ext.EventObject.ENTER){
field.setDisabled(true);
this.save();
}*/
}
},render:this.bindQuickKeys,scope:this}
})},
{columnWidth:.4,items:{xtype:"labelfield",anchor:"-2",name:'remark1',value:"请先输入编码后按[确认]键选择购员!",style:"font-size:18px;padding-top:3px",hideLabel:true}},
{columnWidth:.2,items:{xtype:"labelfield",anchor:"-2",name:'remark2',value:"",hideLabel:true}}
)]}]}]}
]
});
return formPanel;
},
onDiscount:function(e){
if(!this.haveProducts) return false;
if(this.payment) return false;
this.updateDiscount();
this.formFocus();
},
onOffers:function(){
if(!this.haveProducts) return false;
if(this.payment) return false;
this.updateDiscountPrice();
this.formFocus();
},
onSelShippingGuide:function(){
if(this.payment) return false;
this.setAction('shippingGuide');
this.seachShippingGuide();
},
onPayment:function(){
if(!this.haveProducts) return false;
if(this.payment) return false;
var count = this.editGrid.store.getCount();
if(count<0){
Disco.Ext.Util.msg("提示","请先选择商品再结账!");
return false;
}
if(this.beforeSaveCheck()===false){
return false;
}else{
var status = this.fp.form.findField("status").getValue();
status = parseInt(status);
if(status>0){ //说明是退货,不用判断库存!
this.readyPay();
}else{
this.otherCheckNum();
}
}
},
onNoPrint:function(){
this.noPrint=true;
Disco.Ext.Util.msg("提示","不需要打印了!");
},
onPrint:function(){
this.noPrint=false;
Disco.Ext.Util.msg("提示","不需要打印了!");
},
onPay:function(){
this.pay = true;
Disco.Ext.Util.msg("提示","请输入缴款金额");
},
onPaymentCheck:function(){
if(!this.payment) return false;
Ext.each(this.paymentTypes,function(o){
if(o.name=="支票"){
this.paymentTypeTitle = "支票";
Disco.Ext.Util.msg("提示","支票支付!");
this.paymentTypeId = o.id;
}
},this);
},
onPaymentMoney:function(){
if(!this.payment) return false;
Ext.each(this.paymentTypes,function(o){
if(o.name=="现金"){
this.paymentTypeTitle = "现金";
Disco.Ext.Util.msg("提示","现金支付!");
this.paymentTypeId = o.id;
}
},this);
},
bindQuickKeys:function(textfield){
var keys=[{
key: Ext.EventObject.LEFT,
fn: function(e){
// alert("left");
}},
{
key: Ext.EventObject.RIGHT,
fn: function(e){
// alert("right");
}},
{
key: Ext.EventObject.UP,
fn: function(e){
if(!this.haveProducts) return false;
this.customSelectLastRow();
this.formFocus.defer(50,this);
}},
{
key: Ext.EventObject.DOWN,
fn: function(e){
if(!this.haveProducts) return false;
this.customSelectFirstRow();
this.formFocus.defer(50,this);
}},
{key: Ext.EventObject.ENTER,fn: this.enterFunction},
{
key: Ext.EventObject.PAGE_DOWN,
fn:this.onPayment
},
{
key: Ext.EventObject.PAGE_UP,
fn: function(e){
if(!e.shiftKey)this.onSelShippingGuide();
}
},
{
key: Ext.EventObject.ESC,
fn: this.escFunction},
{
key: Ext.EventObject.END,
fn: function(e){
if(!e.shiftKey){
this.onOffers();
}else{
var key = this.fp.form.findField("key").getValue();
this.fp.form.findField("key").setValue(key+"#");
}
}
},
{
key: Ext.EventObject.HOME,
fn: this.onDiscount,
scope:this
},
{
key: Ext.EventObject.INSERT, // or Ext.EventObject.ENTER
fn: this.updateNumber,
scope: this
},{key: Ext.EventObject.F11,
fn: this.updateColor
},{key: Ext.EventObject.F12,
fn: this.updateSizeType
},{key: Ext.EventObject.F1,
fn: this.onPaymentMoney
},{key: Ext.EventObject.F2,
fn:this.onPaymentCheck
},{key: Ext.EventObject.F3,
fn: this.createCreditCardTypeWin
},{key: Ext.EventObject.F12,
fn: this.onPreferential
},{
key: Ext.EventObject.F3,
ctrl:true,
fn: function(){
this.setAction('reserve');
Disco.Ext.Util.msg("提示","请输入备用金额");
}
},{
key: Ext.EventObject.F5,
ctrl:true,
fn: this.onPay
},{
key: Ext.EventObject.F9,
ctrl:true,
fn: this.doChangeCasher,
scope:this
},{key: Ext.EventObject.F4,
fn: function(k,e){
if(!this.payment || e.ctrlKey) return false;
Ext.each(this.paymentTypes,function(o){
if(o.name=="购物券"){
this.paymentTypeTitle = "购物券";
Disco.Ext.Util.msg("提示","购物券支付!");
this.paymentTypeId = o.id;
}
},this)
}
},{key: Ext.EventObject.DELETE,
//fn: this.updateSalePrice,
fn: function(){return false}
},{key: Ext.EventObject.F5,
fn: function(k,e){
if(!this.payment || e.ctrlKey) return false;
Ext.each(this.paymentTypes,function(o){
if(o.name=="会员卡"){
this.paymentTypeTitle = "会员卡";
Disco.Ext.Util.msg("提示","会员卡支付!");
this.paymentTypeId = o.id;
}
},this);
}
},{key: Ext.EventObject.F6,
fn: this.hangBill
},{key: Ext.EventObject.F7,
fn: function(){
//window.location.href="Lanyowebprinter://webprint/65536"
// //window.external.LanyoWebPrint("196608");
this.formFocus();
}
},{
key: Ext.EventObject.F9,
fn: this.comeback()
},{
key: Ext.EventObject.F10,
scope:this,
fn: function(k,e){
if(!e.ctrlKey){
this.onNoPrint();
}else{
Disco.Ext.Util.msg("提示","请输入会员卡号!");
this.setAction('onMember');
}
}
},{
key: Ext.EventObject.B, //补货快捷键
ctrl:true,
fn: function(){
//this.patchOrder = true;
this.setAction('patchOrder');
this.fp.form.findField("remark2").setValue("该单为补单");
Disco.Ext.Util.msg("提示","该单为补单");
}
},{
key: Ext.EventObject.F8,
fn: function(k,e){
if(e.ctrlKey && this.giftsPattern){
this.giftsSelectWin();
}else{
if(this.giftsPattern){
this.giftsPattern=false;
this.fp.form.findField("retailType").setValue("销售模式");
}else{
this.giftsPattern=true;
this.fp.form.findField("retailType").setValue("赠品模式");
}
}
}
}
];
for(var i=0;i<keys.length;i++)Ext.apply(keys[i],{ stopEvent : true,scope: this});
var map = new Ext.KeyMap(textfield.el,keys);
},
giftsSelectData:function(){
var records = this.giftsProductWin.grid.getSelections();
if(records && records.length){
var data = Ext.apply({},records[0].data);
data.id = data.product;
this.selectProductDataHandler(data);
this.giftsProductWin.hide();
}else{
Disco.Ext.Msg.alert('请选择赠品!',false,function(){
this.giftsProductWin.grid.getSelectionModel().selectRow(0);
},this);
}
},
giftsSelectWin:function(){
if(!this.giftsProductWin){
var store = new Ext.data.JsonStore({
url :"productGifts.ejf?cmd=list",
totalProperty:'rowCount',
root:'result',
fields:["id", "sn", "title","gifts","brand","stockNO","num","dir","product","dirTitle","salePrice","attributeType","style","theYear","season","encaped"],
listeners:{
load:function(){
this.giftsProductWin.grid.getSelectionModel().selectRow(0);
this.giftsProductWin.grid.getView().focusRow(0);
},
scope:this
}
});
this.giftsProductWin = new Ext.Window({
title:'赠品列表',
closeAction:'hide',
hideBorders:true,
layout:'fit',
modal:true,
resizable:false,
width:500,
height:300,
items:{
xtype:'grid',sm:new Ext.grid.RowSelectionModel({singleSelect:true}),
loadMask:true,
store:store,
columns:[new Ext.grid.RowNumberer({header:"序号",width:40}),{header: "ID", hidden:true,width: 100, dataIndex:"id"},
{header: "货号", sortable:true,width: 100, dataIndex:"sn"},
{sortable:true,hidden:true,width: 120, dataIndex:"product"},
{header: "货品编码", sortable:true,width: 120, dataIndex:"stockNO"},
{header: "货品名称", sortable:true,width: 120, dataIndex:"title"},
{header: "库存量", sortable:true,width: 80, dataIndex:"num"}
],
keys:[{
key:13,
fn:this.giftsSelectData,
scope:this
}]
},
buttonAlign:'center',
listeners:{
scope:this,
hide:this.formFocus,
show:function(){
this.giftsProductWin.grid.getStore().removeAll();
this.giftsProductWin.grid.getStore().load();
}
},
buttons:[{text:'确定',handler:this.giftsSelectData,scope:this},
{text:'取消',handler:function(){
this.giftsProductWin.hide();
},scope:this}
]
});
this.giftsProductWin.grid = this.giftsProductWin.findByType('grid')[0];
}
this.giftsProductWin.show();
},
hangBill:function(){
if(!this.haveProducts && this.hangBills && this.hangBills.length){
if(!this.hangBillWin){
this.hangBillWin=new HangBillSelectWin();
this.hangBillWin.on("select",function(r, win,e){
this.editGrid.store.add(r.items);
this.hangBills.removeKey(r.time);
//设置this.haveProducts\this.append及导购员的值
this.haveProducts=true;
this.append=true;
this.tempData.add("firstShippingGuide",r.items[0].get("shoppingGuide"));//缓存起来
this.countAll(true);
},this);
this.hangBillWin.on("hide",this.formFocus,this);
}
this.hangBillWin.show();
this.hangBillWin.list.grid.store.loadData({result:this.hangBills.items});
}
else {
Ext.Msg.confirm("挂单提示!","确认要挂起当前单据,录入另外一张订单吗?",function(btn){
if(btn=="yes"){
if(!this.hangBills)this.hangBills=new Ext.util.MixedCollection();
//time表示挂单时间,num表示总数量,product表示代表产品,totalAmount表示总金额,items:表示record数据
var records=this.editGrid.store.data.items;
var nums =0;
Ext.each(records,function(record){
nums += record.get("num");
},this);
var totalAmounts = 0.00;
Ext.each(records,function(record){
totalAmounts += record.get("totalAmount");
},this);
var obj={time:new Date(),num:nums,totalAmount:totalAmounts,product:records[0].get("product"),items:records};
this.hangBills.add(obj.time,obj);
this.create();
}
else {
this.formFocus();
}
},this)
}
},
loadProductStock:function(grid,row,col){},
createWin:function(callback,autoClose){
return this.initWin(Ext.getBody().getViewSize().width,Ext.getBody().getViewSize().height,"Pos收银",callback,autoClose);
},
storeMapping:["id","sn","cashier","paymentType","vdate","receive","total","charge"],
initComponent : function(){
this.viewWin={width:Ext.getBody().dom.offsetWidth-20,height:Ext.getBody().dom.offsetHeight-20,title:"零售详细"};
var chkM=new Ext.grid.CheckboxSelectionModel();
this.gridConfig={sm:chkM};
this.cm=new Ext.grid.ColumnModel([
chkM,
{header: "流水编号",sortable:true,width: 80, locked:true,dataIndex:"sn"},
{header: "收银员", sortable:true,width: 90,locked:true, dataIndex:"cashier",renderer:this.objectRender("trueName")},
//{header:"支付方式",sortable:true,width: 100,dataIndex:"paymentType",renderer:this.objectRender("name")},
{header:"金额", sortable:true,width: 80,dataIndex:"total"},
{header:"日期", sortable:true,width: 120,dataIndex:"vdate",renderer:this.dateRender()}
]);
if(Global.WearEditStoreMapping ){
Ext.apply(PosPanel.prototype,Global.WearEditStoreMapping);
}else{
var response=Ext.lib.Ajax.syncRequest("POST", "stockOutcome.ejf",{cmd:"getGroupFieldMapping"});
var map=Ext.decode(response.conn.responseText);
Ext.apply(PosPanel.prototype,map);
}
if(this.editStoreMapping.indexOf("shoppingGuide")<0){
this.editStoreMapping=this.editStoreMapping.concat(["shoppingGuide","gifts","status","stockNO","totalAmount","sizeType","discount","discountPrice","residualStoreNum"]);
}
PosPanel.superclass.initComponent.call(this);
Ext.Ajax.request({url:"paymentType.ejf",params:{cmd:"list"},callback :function(ops,success,response){
var map=Ext.decode(response.responseText);
this.paymentTypes = map.result;
},scope:this});
this.tempData = new Ext.util.MixedCollection(false);
},
quickSearch : function() {
var d1 = this.search_vdate1.getValue() ? this.search_vdate1.getValue().format("Y-m-d") : "";
var d2 = this.search_vdate2.getValue() ? this.search_vdate2.getValue().format("Y-m-d") : "";
this.store.baseParams = Ext.apply({}, {
vdate1 : d1,
vdate2 : d2
},this.baseQueryParameter);
if("defaultStatus" in this.store.baseParams) delete this.store.baseParams.defaultStatus
if("advanced" in this.store.baseParams) delete this.store.baseParams.advanced
this.refresh();
},
printRecord:function(){
var record = this.grid.getSelectionModel().getSelected();
if (!record) {
Ext.Msg.alert("提示",
"请先选择要操作的数据!");
return false;
}
Ext.Ajax.request({url:this.baseUrl,params:{cmd:"print",id:record.get("id")},callback:function(options,success,response){
Disco.Ext.Util.executeLocalCommand("retailPostPrint",response.responseText);
}});
//window.location.href="Lanyowebprinter://webprint/"+record.get("id");
},
afterList:function(){
this.store.baseParams.defaultStatus=0;
this.btn_refresh.hide();
this.searchField.hide();
this.search_vdate1=new Ext.form.DateField({fieldLabel:"开始时间",emptyText:"开始时间",width:90,format:"Y-m-d"});
this.search_vdate2=new Ext.form.DateField({fieldLabel:"结束时间",emptyText:"结束时间",width:90,format:"Y-m-d"});
/* this.btn_remove.hide();
this.btn_edit.hide();*/
this.btn_print.setHandler(this.printRecord,this);
this.grid.on("render",function(){
this.grid.getTopToolbar().insert(10,["-",this.search_vdate1,this.search_vdate2,"-",{text:"查询",cls : "x-btn-text-icon",icon:"images/icons/page_find.png",handler:this.quickSearch,scope:this},
{id:"btn_refresh",text : "重置",iconCls : 'f5',handler : function(){
this.search_vdate1.setValue("");
this.search_vdate2.setValue("");
}}
]);
//得到服务器
/* Ext.TaskMgr.start({
run: function(){
Ext.Ajax.request({url:this.baseUrl,params:{cmd:"getService"},callback :function(ops,success,response){
var map=Ext.decode(response.responseText);
},scope:this});
},
interval: 600000,
scope:this
}); */
},this);
this.create();
}
});
CasherLoginWindow=Ext.extend(Ext.Window,{
title : '收银员登录',
width : 265,
height : 140,
collapsible : true,
closable:false,
modal:true,
defaults : {
border : false
},
buttonAlign : 'center',
createFormPanel :function() {
return new Ext.form.FormPanel({
bodyStyle : 'padding-top:6px',
defaultType : 'textfield',
labelAlign : 'right',
labelWidth : 55,
labelPad : 0,
frame : true,
defaults : {
allowBlank : false,
width : 158,
selectOnFocus:true
},
items : [{name:"user",xtype:"hidden"},{
cls : 'user',
name : 'userName',
fieldLabel : '帐号',
blankText : '帐号不能为空'
}, {
cls : 'key',
name : 'psw',
fieldLabel : '密码',
blankText : '密码不能为空',
inputType : 'password'
}]
});
},
login:function() {
Ext.Ajax.request({
waitTitle:"请稍候",
waitMsg : '正在登录......',
url : '/dutyInfo.ejf?cmd=casherLogin',
params:{user:this.fp.findSomeThing("user").getValue(),psw:this.fp.findSomeThing("psw").getValue()},
scope:this,
success:function(req){
try{
var ret=Ext.decode(req.responseText);
if(ret && ret.errors){
Ext.MessageBox.alert('警告', ret.errors.msg,function(){
this.fp.findSomeThing("psw").focus('200',true);
},this);
}else{
Disco.Ext.Util.executeLocalCommand("printhandover",req.responseText);
window.location.href="manage.ejf";
}
}catch(err){
Disco.Ext.Util.executeLocalCommand("printhandover",req.responseText);
window.location.href="manage.ejf";
}
}
});
/**
this.fp.form.submit({
waitTitle:"请稍候",
waitMsg : '正在登录......',
url : '/dutyInfo.ejf?cmd=casherLogin',
success : function(form, action) {
Disco.Ext.Util.executeLocalCommand("dutyInfoPrint",action.response.responseText,function(){
window.location.href="manage.ejf";
});
},
failure : function(form, action) {
if (action.failureType == Ext.form.Action.SERVER_INVALID)
Ext.MessageBox.alert('警告', action.result.errors.msg);
form.findField("psw").focus(true);
},
scope:this
});
*/
},
initComponent : function(){
this.keys={
key: Ext.EventObject.ENTER,
fn: this.login,
scope: this};
CasherLoginWindow.superclass.initComponent.call(this);
this.fp=this.createFormPanel();
this.add(this.fp);
this.addButton('登陆',this.login,this);
this.addButton('取消',function(){
Ext.Msg.confirm("提示","确认要取消交班吗?",function(btn){
if(btn=="yes"){
this.hide();
}
},this)
},this);
}
});
|
// -----------------------------------------------------------------------------------------------------------
// ========================== FUNCTIONs FOR ENQUIRY FORM VALIDATION =====================================
// -----------------------------------------------------------------------------------------------------------
function checkEmail() {
var emailData = $('#custEmail').val();
var mailformat = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (emailData.match(mailformat)) {
$('#custEmail').css('color', 'green');
$('#custEmail').css('border', '');
$('#enquiryButton').attr('disabled', false);
}else if(emailData.length == 0){
$('#custEmail').css('border', '');
$('#enquiryButton').attr('disabled', false);
}
else {
$('#custEmail').css('color', 'red');
$('#custEmail').css('border', '1px solid red');
$('#enquiryButton').attr('disabled', true);
}
}
// -----------------------------------------------------------------------------------------------------------
// ========================== FUNCTIONs FOR ENQUIRY FORM SUBMISSION =====================================
// -----------------------------------------------------------------------------------------------------------
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function send_enquiry(thisTxt){
var productID = $(thisTxt).attr('productID')
// console.log(productID);
var customerName = $('#customerName').val().trim();
var customerContact= $('#customerContact').val().trim();
var customerEmail = $('#custEmail').val().trim();
var customerRemark = $('#customerRemark').val().trim();
var customerAddress = $('#customerAddress').val().trim();
var custCity = $('#custCity').val().trim();
var custState = $('#custState').val().trim();
if(customerName.length == 0){
alert('Enter Customer Name');
return false;
}
if(customerContact.length == 0 ){
alert('Enter Customer Contact');
return false;
}
if(customerContact.length != 10 ){
alert('Enter valid 10 digit Customer Contact');
return false;
}
if(custState.length == 0){
alert('Select Customer State');
return false;
}
if(custCity.length == 0){
alert('Select Customer City');
return false;
}
if(customerAddress.length == 0){
alert('Select Customer Address');
return false;
}
// 'customerAddress': customerAddress,
else{
$('#enquiryButton').css('display','none');
$('#spinnerbtn').css('display','');
// --------------- AJAX Call ---------------------
const csrftoken = getCookie('csrftoken');
// swal.showLoading();
$.ajax({
type: 'POST',
url: "/create_enquiry",
headers: { 'X-CSRFToken': csrftoken },
data: {
'customerName': customerName, 'customerContact': customerContact,
'customerEmail': customerEmail, 'customerRemark': customerRemark,
'productID': productID, 'customerAddress': customerAddress,
'custCity': custCity,'custState': custState
},
success: function (response) {
console.log(response);
// window.location.href = "/batch_list";
$('#enquiryButton').css('display','');
$('#spinnerbtn').css('display','none');
if(response == 'Success'){
alert('Your enquiry send successfully to our team.They will reach you in some time.');
location.reload();
}else{
alert('Your enquiry failed.Try Again!');
return false;
}
}
});
// ---------------------------------------------------
}
}
// -----------------------------------------------------------------------------------------------------------
// ===========================================================================================================
function CheckContactUsEmail(){
var emailData = $('#cusEmail').val();
var mailformat = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (emailData.match(mailformat)) {
$('#cusEmail').css('color', 'green');
$('#cusEmail').css('border', '');
$('#submitBtn').attr('disabled', false);
}else if(emailData.length == 0){
$('#cusEmail').css('border', '');
$('#submitBtn').attr('disabled', false);
}
else {
$('#cusEmail').css('color', 'red');
$('#cusEmail').css('border', '1px solid red');
$('#submitBtn').attr('disabled', true);
}
}
function contactUs(thisTxt){
var customerName = $('#customerName').val().trim();
var customerEmail = $('#cusEmail').val().trim();
var Subject= $('#subjectName').val().trim();
var review = $('#customerReview').val().trim();
if(customerName.length == 0){
alert('Enter Customer Name');
return false;
}
if(customerEmail.length == 0){
alert('Enter Customer Email');
return false;
}
if(Subject.length == 0){
alert('Enter Subject');
return false;
}
else{
$('#submitBtn').css('display','none');
$('#spinnerbtn').css('display','');
// --------------- AJAX Call ---------------------
const csrftoken = getCookie('csrftoken');
// swal.showLoading();
$.ajax({
type: 'POST',
url: "/contact",
headers: { 'X-CSRFToken': csrftoken },
data: {
'customerName': customerName, 'customerEmail': customerEmail, 'Subject': Subject,
'review': review
},
success: function (response) {
console.log(response);
// window.location.href = "/batch_list";
$('#submitBtn').css('display','');
$('#spinnerbtn').css('display','none');
if(response == 'Success'){
alert('Your enquiry send successfully to our team.They will reach you in some time.');
location.reload();
}else{
alert('Your enquiry failed.Try Again!');
return false;
}
}
});
// ---------------------------------------------------
}
}
// -----------------------------------------------------------------------------------------------------------
// ===========================================================================================================
|
let buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
var inputPattern = [];
var gameStatus = 0;
function generateRandom(min , max) {
var random = Math.random() * (max - min) + min;
random = Math.floor(random);
return random;
}
function nextSequence() {
var rdnColourIndex = generateRandom(0,4);
gamePattern.push(rdnColourIndex);
flashButton(buttonColors[rdnColourIndex]);
}
function flashButton(color) {
$(`div.btn.${color}`).fadeOut(100).fadeIn(100);
}
function showError() {
console.log(`Game Over`);
$("body").toggleClass("game-over");
setTimeout(() => {
$("body").toggleClass("game-over");
gameStatus = 0;
}, 200);
}
function checkSequence(color) {
console.log(`Checking Sequence ${color}`);
var index = buttonColors.indexOf(color);
inputPattern.push(index);
var lastGeneratedIndex = gamePattern[gamePattern.length-1];
if (!lastGeneratedIndex || lastGeneratedIndex != index) showError();
else nextSequence();
}
$(document).ready(function () {
$(document).keydown(function (e) {
// $(document).unbind("keydown");
if (gameStatus == 0) gamePattern = [];
nextSequence();
});
$("div.btn").click(function (e) {
checkSequence($(this).attr("id"));
$(this).fadeOut(100).fadeIn(100);
});
});
|
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { get } from '../Data';
import { NavigationEvents } from "react-navigation";
import PieChart from 'react-native-pie-chart';
import StatCard from '../ui-items/statCard';
import { ScrollView } from 'react-native-gesture-handler';
export default class Statistics extends Component {
constructor(props) {
super(props);
console.disableYellowBox = true;
this.state = {
parsed: [],
DataNames: [],
DataNumbers: [],
DataColors: [],
DataNotify: [],
DataShow: [],
DataCorrect: []
}
}
componentDidMount(){
this.loadData();
}
// refresh Flatlist ( get data from local saved )
async loadData() {
this.setState({
parsed: await get()
})
this.setChart();
}
// set chart data
setChart(){
let dataNames = [];
let dataColors = [];
let dataNumbers = [];
let dataNotify = [];
let dataShow = [];
let dataCorrect = [];
let colorid=0
colors = ['#FF9800','#2196F3','#F44336','#673AB7','#009688','#3F51B5','#4CAF50','#E64A19','#607D8B','#C2185B']
this.state.parsed.list.forEach(element => {
if(element.liste.length>0){
let tempNotify=0;
let tempShow=0
dataNames.push(element.name)
dataNumbers.push(element.liste.length)
dataColors.push(colors[colorid])
for(i=0; i<element.liste.length; i++){
tempShow = element.liste[i].showed + tempShow
}
dataShow.push(tempShow)
if(element.notification){
dataNotify.push(element.notification)
}
else{
dataNotify.push(0)
}
if(element.correct){
dataCorrect.push(element.correct)
}
else{
dataCorrect.push(0)
}
colorid += 1
colorid = colorid % 10
}
});
this.setState({
DataNames: dataNames,
DataNumbers: dataNumbers,
DataColors: dataColors,
DataNotify: dataNotify,
DataShow: dataShow,
DataCorrect: dataCorrect
})
}
_renderCards(){
if(this.state.DataNames.length>0){
let cards = []
for(i=0; i<this.state.DataNames.length; i++){
txt1=this.state.DataNotify[i]
txt2=this.state.DataCorrect[i]+"/"+this.state.DataShow[i]
cards.push(
<View style={{flexDirection:'row'}}>
<StatCard sayi={this.state.DataNumbers[i]} listName={this.state.DataNames[i]} color={this.state.DataColors[i]} text1={txt1} text2={txt2} />
</View>
);
}
return cards
}
else{
return(
<View style={{alignItems:'center'}}>
<Text style={{fontSize:22}}>Can't find info.</Text>
<Text style={{fontSize:22}}>Try to add list and words.</Text>
</View>
)
}
}
render() {
return (
<View style={{ flex:1, justifyContent:'center' }}>
<NavigationEvents
onWillFocus={() => {
//Trigger when this navigation screen on focus
this.loadData()
}}
/>
<ScrollView>
<View style={{flex:2, alignItems:'center'}}>
<Text style={{ margin:10, fontSize: 30 }}>Statistics</Text>
<PieChart
chart_wh={200}
series={this.state.DataNumbers}
sliceColor={this.state.DataColors}
/>
</View>
<View style={{flex:2, marginTop:20, alignItems:'center'}}>
{this._renderCards()}
</View>
</ScrollView>
</View>
);
}
}
|
const mapnik = require("mapnik");
const mercator = require("./utils/sphericalmercator");
const config = require("./config");
mapnik.register_default_input_plugins()
const mercatorProj4 = `+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs`;
const xmlConfig = `
<?xml version="1.0" encoding="utf-8"?>
<Map minimum-version="2.0.0">
<Layer name="taifeng" status="on" srs="${mercatorProj4}">
<Datasource>
<Parameter name="type">postgis</Parameter>
<Parameter name="host">${config.db.host}</Parameter>
<Parameter name="port">${config.db.port}</Parameter>
<Parameter name="dbname">${config.db.database}</Parameter>
<Parameter name="user">${config.db.user}</Parameter>
<Parameter name="password">${config.db.password}</Parameter>
<Parameter name="simplify_geometries">true</Parameter>
`;
const xmlConfigTail = `
<Parameter name="estimate_extent">false</Parameter>
<Parameter name="extent">-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892</Parameter>
</Datasource>
</Layer>
</Map>
`;
async function tile(ctx, next) {
return new Promise((resolve, reject) => {
let z = parseInt(ctx.params.z);
let x = parseInt(ctx.params.x);
let y = parseInt(ctx.params.y);
const xml = parseParams(ctx.query);
let map = new mapnik.Map(256, 256, mercator.proj4);
map.fromString(xml, {}, (err, res) => {
if (err) {
console.error('style error', err)
}
let vt = new mapnik.VectorTile(z, x, y);
map.render(vt, (err, vt) => {
if (err) {
console.error('render error', err);
}
ctx.set('Content-Type', 'application/x-protobuf');
ctx.response.status = 200;
vt.getData((err, data) => {
if (err) {
console.log('err', err);
}
ctx.body = data;
resolve();
});
});
});
})
}
function parseParams(params) {
let sql = '';
if (params) {
sql += `<Parameter name="table">${params.table}</Parameter>`;
sql += `<Parameter name="geometry_field">${params.geometry_field}</Parameter>`;
}
return xmlConfig + sql + xmlConfigTail;
}
module.exports = {
tile
}
|
//import * as divs from './vueComponents.js';
import * as components from './vueComponents.js';
import {
convertToTime
} from './utils.js';
import * as audioUtils from './audio-utils.js';
const controls_v = new Vue({
el: '#controls',
components: {
'controlSection': components.controlSection
},
data: {
//
sections: {
audio: components.audioDiv,
visual: components.visualDiv
},
uiShowing: false,
lyricsShowing: false,
search: true,
loading: false,
audioLoaded: false,
results: [],
searchTerms: {},
searchTerm: 'Welcome to the black parade',
video: {
id: 0,
url: ` `,
title: "Nothing",
channel: " ",
channelLink: ` `
},
songLyrics: "",
screenWidth: 0,
// Audio Controls
//audio: components.audioDiv,
audio: {},
numSamples: 128,
playing: false,
checkedAudioSettings: [],
currentAudioTime: "",
currentAudioLength: "",
audioTime: "0:00 / 3:43",
selectedSong: "audio/glass%20animals%20flip.mp3",
selectedVideo: '',
songs: [
{
name: "Glass Animals - Flip",
src: "audio/glass%20animals%20flip.mp3"
},
{
name: "Apashe - Lacrimosa",
src: "audio/Apashe%20-%20Lacrimosa.mp3"
},
{
name: "Confetti - Rob A Bank",
src: 'audio/Confetti%20-%20Rob%20A%20Bank.mp3'
}
],
audioEffects: {
sliders: [{
name: "Distortion",
sliderLabel: "Amount:",
enabled: false,
amount: 0,
min: 0,
max: 100,
polls: true,
toggle: audioUtils.toggleDis,
update: audioUtils.updateDis
}, {
name: "Low Shelf Filter",
sliderLabel: "Frequency Amount:",
enabled: false,
amount: 0,
min: 0,
max: 1000,
polls: true,
toggle: audioUtils.toggleLS,
update: audioUtils.updateLS
}, {
name: "High Shelf Filter",
sliderLabel: "Frequency Amount:",
enabled: false,
amount: 1000,
min: 1000,
max: 2000,
polls: true,
toggle: audioUtils.toggleHS,
update: audioUtils.updateHS
}]
},
audioOptions: {},
// Visual Controls
checkedVisualSettings: [],
selectedBlendMode: "xor",
blendModes: ["source-atop", "destination-over", "destination-out", "lighter", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"],
includeBackground: false,
backgroundColor: '#ffffff',
quadCurves: false,
visualEffects: {
blendMode: {
name: "Blend Mode",
enabled: true,
selected: "xor",
selections: ["source-atop", "destination-over", "destination-out", "lighter", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"],
},
gradients: {
name: "Color Gradient",
current: 'rainbow',
selections: ["Rainbow", 'RGB', 'Custom'],
custom: {
amount: 3,
colors: ['#4fdeed', '#593daa', '#0ff09f']
}
}
},
visualOptions: {
colorPicker: {
name: "Include Background",
label: "Background Color",
polls: false,
enabled: false,
color: '#ffffff',
picker: {}
},
quadCurves: {
name: "Quadratic Curve",
enabled: false
}
}
},
created() {
this.screenWidth = window.innerWidth;
window.onresize = _ => this.screenWidth = window.innerWidth;
},
mounted() {
let controls = this.$refs.ui;
let downArrow = this.$refs.downArrow;
this.audio = audioUtils.createAudioElement(this.$refs.video, this.numSamples);
controls.style.transform = `translate(0, ${-controls.offsetHeight}px)`;
downArrow.style.transform = `translate(0, ${-controls.offsetHeight - 1}px)`;
},
methods: {
async find() {
this.audioLoaded = false;
this.playing = false;
this.loading = true;
let load = await Promise.all([
this.getYoutube(),
this.getLyrics()
])
},
play() {
if (!this.audioLoaded)
return;
if (this.audio.ctx.state == "suspended") {
this.audio.ctx.resume();
}
this.playing = !this.playing;
console.log(this.playing);
if (this.playing) {
this.$refs.video.play();
} else {
this.$refs.video.pause();
}
},
unhideControls() {
this.showControls = !this.showControls;
},
loaded(e) {
if (e.target.readyState >= 2) {
this.audioLoaded = true;
this.loading = false;
this.currentAudioLength = `${convertToTime(this.audio.element.duration)}`;
this.play();
};
},
updateTime() {
if (!this.audioLoaded) {
this.audioTime = '--:-- / --:--';
return;
}
let ct = convertToTime(this.audio.element.currentTime);
this.audioTime = `${ct} / ${this.currentAudioLength}`;
},
showUI(e) {
let downArrow = e.target;
let controls = this.$refs.ui;
this.uiShowing = !this.uiShowing;
if (this.uiShowing) {
downArrow.style.transform = "translate(0, -1px)";
controls.style.transform = `translate(0, 0)`;
} else {
downArrow.style.transform = `translate(0, ${-controls.offsetHeight - 1}px)`;
controls.style.transform = `translate(0, ${-controls.offsetHeight}px)`;
}
},
async getYoutube() {
// Youtube
let yt = await fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&q=${this.searchTerm}&type=video&maxResults=10&key=AIzaSyDNoaU5HfiTlQLbMIi8_zwDpP560120zzE`)
.then(response => response.json())
.then(json => {
//this.result = json.data;
let firstResult = json.items[0];
this.video.id = firstResult.id.videoId;
this.video.url = `https://www.youtube.com/watch?v=${this.video.id}`;
this.video.title = firstResult.snippet.title;
this.video.channel = firstResult.snippet.channelTitle;
this.video.channelLink = `https://www.youtube.com/channel/${firstResult.snippet.channelId}`;
});
// Youtube-dl
let ytd = await fetch(`https://visualizer-util.herokuapp.com/api/info?url=${this.video.url}&format=bestaudio`)
.then(response => {
if (!response.ok) {
throw Error(`ERROR: ${response.statusText}`);
}
return response.json();
})
.then(json => this.selectedVideo = `https://cors-anywhere.herokuapp.com/${json.info.url}`);
},
async getLyrics() {
// iTunes
let iTunes = await fetch(`https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=${this.searchTerm}&limit=10&entity=song`)
.then(response => {
if (!response.ok) {
throw Error(`ERROR: ${response.statusText}`);
}
return response.json();
})
.then(json => {
this.results = json.results.map(result => {
return {
artist: result.artistName,
track: result.trackName
}
});
this.searchTerms = this.results[0];
});
// Lyrics
let lyrics = await fetch(`https://orion.apiseeds.com/api/music/lyric/${this.searchTerms.artist}/${this.searchTerms.track}?apikey=t0fQtQW56iJKDN85vC3lrI1y3m0hooWfCieVWRcJz7GNg72lhZVCPrjEG1RxWDKk`)
.then(response => {
if (!response.ok) {
this.songLyrics = "Could Not Find Lyrics";
//throw Error(`ERROR: ${response.statusText}`);
throw Error(`ERROR: Lyrics Could Not Be Found`);
}
return response.json();
})
.then(json => this.songLyrics = json.result.track.text);
}
}
})
export let audio = controls_v.audio,
blendMode = controls_v.visualEffects.blendMode,
gradient = controls_v.visualEffects.gradients,
backgroundColor = controls_v.visualOptions.colorPicker,
quadCurves = controls_v.visualOptions.quadCurves,
songLength = controls_v.currentAudioLength,
songTime = controls_v.currentAudioTime,
updateTime = controls_v.updateTime,
screenWidth = controls_v.screenWidth
|
require("dotenv").config();
const {
askStartQuestions,
askGetPasswordQuestions,
askSetPasswordQuestions,
CHOICE_GET,
CHOICE_SET,
askForNewMasterPassword,
} = require("./lib/questions");
const {
readPassword,
writePassword,
readMasterPassword,
writeMasterPassword,
} = require("./lib/passwords");
const { encrypt, decrypt, createHash, verifyHash } = require("./lib/crypto");
const { MongoClient } = require("mongodb");
const client = new MongoClient(process.env.MONGO_URI);
async function main() {
try {
await client.connect();
const database = client.db(process.env.MONGO_DB_NAME);
const originalMasterPassword = await readMasterPassword();
if (!originalMasterPassword) {
const { newMasterPassword } = await askForNewMasterPassword();
const hashedMasterPassword = createHash(newMasterPassword);
await writeMasterPassword(hashedMasterPassword);
console.log("Master Password set!");
return;
}
const { masterPassword, action } = await askStartQuestions();
if (!verifyHash(masterPassword, originalMasterPassword)) {
console.log("Master Password is incorrect!");
return;
}
console.log("Master Password is correct!");
if (action === CHOICE_GET) {
console.log("Now Get a password");
const { key } = await askGetPasswordQuestions();
try {
const encryptedPassword = await readPassword(key, database);
const password = decrypt(encryptedPassword, masterPassword);
console.log(`Your ${key} password is ${password}`);
} catch (error) {
console.error("Something went wrong 😑", error);
// What to do now?
}
} else if (action === CHOICE_SET) {
console.log("Now Set a password");
try {
const { key, password } = await askSetPasswordQuestions();
const encryptedPassword = encrypt(password, masterPassword);
await writePassword(key, encryptedPassword, database);
console.log(`New Password set`);
} catch (error) {
console.error("Something went wrong 😑");
// What to do now?
}
}
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
main();
|
import React from 'react';
import { Link } from 'react-router-dom';
import { Grid } from 'react-bootstrap';
import { Meteor } from 'meteor/meteor';
import { year } from '../../../modules/dates';
import Styles from './styles';
const { productName, copyrightStartYear } = Meteor.settings.public;
const copyrightYear = () => {
const currentYear = year();
return currentYear === copyrightStartYear
? copyrightStartYear
: `${copyrightStartYear}-${currentYear}`;
};
const Footer = () => (
<Styles.Footer>
<Grid>
<p className="pull-left">
©
{` ${copyrightYear()} ${productName}`}
</p>
<ul className="pull-right">
<li>
<Link to="/terms">
Terms
<span className="hidden-xs"> of Service</span>
</Link>
</li>
<li>
<Link to="/privacy">
Privacy
<span className="hidden-xs"> Policy</span>
</Link>
</li>
</ul>
</Grid>
</Styles.Footer>
);
Footer.propTypes = {};
export default Footer;
|
import BaseGrouper from "./BaseGrouper";
import { Group } from "../timeline/Group";
export default class YearGrouper extends BaseGrouper {
constructor (maxGroups) {
super();
this.maxGroups = maxGroups;
}
canGroup(lastGroup) {
return lastGroup.startTime.getFullYear() != lastGroup.endTime.getFullYear()
}
getGroups(lastGroup) {
let startYear = lastGroup.startTime.getFullYear();
let endYear = lastGroup.endTime.getFullYear();
let totalYears = endYear - startYear + 2 // + 2 because we want to include both, start and end year, as well
var step = Math.ceil(totalYears / this.maxGroups);
console.log("Step: " + step);
let timelineStart = new Date(startYear, 0, 1).getTime();
let timelineEnd = new Date(endYear + 1, 0, 1).getTime();
//let timelineDelta = timelineEnd - timelineStart;
let startOffset = (totalYears % step);
if (startOffset == 0) {
startOffset = step;
}
console.log("totalYears = " + totalYears + " | start offset: " + startOffset + " | startYear: " + startYear);
let groups = [];
let lastYear = startYear;
let lastEndYear = lastYear + startOffset;
let group = new Group(this.getNameByYears(lastYear, lastEndYear), [], new Date(lastYear, 0, 1), new Date(lastEndYear - 1, 11, 31));
groups.push(group);
lastGroup.events.forEach(event => {
let year = event.time.getFullYear();
console.log('year: ' + year + ' | Lastyear: ' + lastYear + " | LastEndYear: " + lastEndYear);
if (year >= lastEndYear) {
let tempYear = lastEndYear;
let tempEndYear = lastEndYear + step;
// If empty years in between, add them as empty groups
console.log('Checking if empty ');
while (year > tempEndYear) {
console.log('Next group would be empty. Filling it up... ');
groups.push(new Group(this.getName(tempYear, step), [], new Date(tempYear, 0, 1), new Date(tempEndYear - 1, 11, 31)));
lastYear = tempEndYear;
lastEndYear = tempEndYear;
tempYear += step;
tempEndYear += step
}
lastYear = lastEndYear;
lastEndYear = lastYear + step;
group = new Group(this.getName(lastYear, step), [], new Date(lastYear, 0, 1), new Date(lastEndYear - 1, 11, 31));
groups.push(group);
}
group.events.push(event);
});
// Add the end year
//groups.push(new Group(lastYear + step, [], new Date(lastYear + step, 0, 1), new Date(lastYear + step - 1, 11, 31)));
return groups;
}
getName(startYear, step) {
if (step > 1) {
return startYear + ' - ' + (startYear + step - 1);
} else {
return startYear;
}
}
getNameByYears(startYear, endYear) {
return this.getName(startYear, endYear - startYear);
}
}
|
import React from "react";
import {Navbar , Nav ,Form,FormControl,Button ,NavDropdown} from 'react-bootstrap';
import { Link } from "react-router-dom";
import 'bootstrap/dist/css/bootstrap.css';
class Naav extends React.Component {
render() {
return (
<div>
<Navbar bg="light" expand="lg">
<Navbar.Brand className="Name" href="Home">Home</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Link to="/Home">
<a className="nav-link">Home</a>
</Link>
<Link to="/Contact">
<a className="nav-link">Contact</a>
</Link>
<Link to="/About">
<a className="nav-link">About</a>
</Link>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
)
}
}
export default Naav;
|
/// routes.js
/// https://medium.com/@thejasonfile/basic-intro-to-react-router-v4-a08ae1ba5c42
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import React, { Component } from 'react';
import Title from './Title';
import Tab from './tabs/Tab';
import Tabs from './tabs/Tabs';
import HeadlineBlock from './HeadlineBlock';
import Home from './Home';
import SearchResult from "./SearchResult";
import history from './history';
// I have the <Router> component with a child div since that component can only have one child.
const routes = (
<Router history={history}>
<div>
<Route path="*" component={Home} />
<Route exact path="/" component={HeadlineBlock}/>
<Route path="/search" component={SearchResult}/>
</div>
</Router>
);
export default routes;
|
import React from 'react';
const SortCategories =()=>{
return (
<div>
<span><h4>Order by</h4></span>
<select name="options" className="select">
<option selected>Select</option>
<option value="first">1</option>
<option value="second">2</option>
<option value="third">3</option>
</select>
</div>
)
}
export default SortCategories;
|
let colors = [];
let brush = { x:0, y:0, px:0, py:0 }
let seed;
let link;
let link2;
let Insta;
let telegram;
let myFont;
let img;
function setup() {
createCanvas(windowWidth, windowHeight);
// img = createImg('stroke.png');
// img.position(0, 0);
myFont = loadFont('OpenSans-Regular.ttf');
noStroke();
link = createA('https://www.dropbox.com/s/7uni55lucnv1z0j/CV_Dima_Sugatov.pdf?dl=0', 'My CV','_blank');
link.style('color', '#080FF6');
link.style('font-size', '50px');
link.position(50,377);
link2 = createA('https://vimeo.com/dimasugatov', 'Motion-design portfolio','_blank');
link2.style('color', '#080FF6');
link2.style('font-size', '50px');
link2.position(50,436);
insta = createA('https://www.instagram.com/dima_sugatov/', 'instagram','_blank');
insta.style('color', '#080FF6');
insta.style('font-size', '50px');
insta.position(50,652);
telegram = createA('http://tlgg.ru/dimasugatov', 'telegram','_blank');
telegram.style('color', '#080FF6');
telegram.style('font-size', '50px');
telegram.position(50,704);
seed = random(1000);
colors = [
color(112,112,74), //green
color(245,198,110), //yellow
color(242,229,194), //cream
color(115,106,97), //light grey
color(215,90,34), //orange
color(235,61,0)] // red-orange
let base = floor(random(colors.length));
background(colors[base]);
colors.splice(base,1);
}
function draw() {
push();
textFont(myFont);
textSize(50);
fill(0);
text("Hello World!\nMy name is Dima\nI'm a designer and creative coder",50,100);
textSize(40);
fill(0);
text("Contact me:",50,640 );
pop();
brush.x+=(mouseX-brush.x)/12;
brush.y+=(mouseY-brush.y)/12;
if(frameCount>40){
drizzle();
}
brush.px=brush.x;
brush.py=brush.y;
}
function mouseMoved(){
if(frameCount%7==0){
splatter(mouseX, mouseY);
splatter(width-mouseX, height-mouseY);
stipple(mouseX, mouseY, 0);
stipple(width-mouseX, height-mouseY, 255);
}
}
function drizzle(){
let s = 1+30/dist(brush.px, brush.py, brush.x, brush.y);
s=min(15,s);
strokeWeight(s);
stroke(0);
line(brush.px, brush.py, brush.x, brush.y);
stroke(255);
line(width-brush.px, height-brush.py, width-brush.x, height-brush.y);
}
function splatter(bx,by){
let c = colors[floor(random(colors.length))];
bx += random(-15,15);
by += random(-15,15);
let mx = 10*movedX;
let my = 10*movedY;
for(let i=0; i<80; i++){
seed+=.01;
let x = bx+mx*(0.5-noise(seed+i));
let y = by+my*(0.5-noise(seed+2*i));
let s = 150/dist(bx, by, x, y);
if(s>20) s=20;
let a = 255-s*5;
noStroke();
c.setAlpha(a);
fill(c);
ellipse(x,y,s);
seed+=.01;
}
}
function stipple(bx, by, c){
noStroke();
fill(c);
let radius = random(3, 12);
ellipse(bx+random(-30,30), by+random(30,-30), radius);
radius = random(3, 12);
ellipse(bx+random(-30,30), by+random(30,-30), radius);
}
function keyPressed(){
if(keyCode==32){
background(180);
}
}
|
class ResolveService {
login($q, AccountApi) {
'ngInject';
const isLoggedIn = AccountApi.$isLoggedIn();
if (!isLoggedIn) {
return $q.reject('requireLogin');
}
return true;
}
}
export default ResolveService;
|
/*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
*/
import React from 'react';
import { Link } from 'react-router-dom';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles(() => ({
root: {
width: '100vw',
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
formWrapper: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
height: 350,
border: '1px solid black',
borderRadius: 25,
padding: 80,
},
}));
export default function Home() {
const classes = useStyles();
return (
<div className={classes.root}>
<h1>
You are now connected and can go to the <Link to="/cats">Cats</Link>{' '}
page
</h1>
</div>
);
}
|
import React, { Component } from 'react';
import { Row, Col, Card } from 'antd';
import { withRouter } from 'react-router-dom'
class Login extends Component {
render() {
if (localStorage.getItem("github_token")) {
this.props.history.push('/');
}
return (
<Row>
<Col sm={{ span: 12, offset: 0 }} lg={{ span: 12, offset: 6 }}>
<h1 style={{ textAlign: 'center' }}>
Welcome to Source Control <span aria-label="Star" role="img">⭐</span>
</h1>
<Card
title="Star your repos!"
extra={<a href="https://github.com/misterpoloy/github-auth-react-apollo">Source code</a>}
style={{ width: 300, margin: 'auto' }}
>
Stack:
<ul>
<li><a target="blank" href="https://github.com/facebook/create-react-app">React</a></li>
<li><a target="blank" href="https://www.apollographql.com/">Apollo</a></li>
<li><a target="blank" href="https://graphql.org/">GraphQL</a></li>
<li><a target="blank" href="https://www.apollographql.com/docs/link/links/state.html">Apollo link (instead of redux)</a></li>
<li><a target="blank" href="https://github.com/prose/gatekeeper#deploy-on-heroku">Gatekeeper</a></li>
<li><a target="blank" href="https://ant.design/">Ant.design</a></li>
<li><a target="blank" href="https://jestjs.io/index.html">Jest for testing</a></li>
<li><a target="blank" href="https://prettier.io/docs/en/eslint.html">Eslint and Prettier</a></li>
</ul>
Helpful documentation:
<ul>
<li><a target="blank" href="https://developer.github.com/v4/guides/forming-calls/#authenticating-with-graphql">Github API</a></li>
<li><a target="blank" href="https://www.graphql.college/implementing-github-oauth-flow/">Github Auth flow</a></li>
</ul>
</Card>
</Col>
</Row>
);
}
}
export default withRouter(Login);
|
import React, { useEffect, useRef } from 'react'
import parse from 'html-react-parser'
import { makeDraggable } from '../utils/functions'
const Notepad = (props) => {
useEffect(() => {
makeDraggable('notepad')
}, [])
return (
<div
id="notepad"
className="sm:ml-12 sm:items-center absolute flex flex-col w-2/3 top-0 mt-10 bg-white text-black"
>
<div id="title" className="flex items-start w-full justify-stretch pb-2">
<div className="flex w-full">
<img className="icon h-8 mr-1" src="./images/icons/notepad.ico"></img>
<span className="pl-2 pr-2 flex items-center">{props.project.title} - Notepad</span>
</div>
<div className="flex w-full justify-end">
<img
className="icon hover:bg-red-600"
src="./images/icons/icon-close.svg"
onClick={props.setShowDescription}
></img>
</div>
</div>
<div id="toolbar" className=" sm:w-full flex w-1/4 sm:p-0 justify-between p-2">
<span className="notepadToolbarItem sm:pl-0 sm:pr-0">File</span>
<span className="notepadToolbarItem sm:pl-0 sm:pr-0">Edit</span>
<span className="notepadToolbarItem sm:pl-0 sm:pr-0">Format</span>
<span className="notepadToolbarItem sm:pl-0 sm:pr-0">View</span>
<span className="notepadToolbarItem sm:pl-0 sm:pr-0">Help</span>
</div>
<div id="textArea" className="flex border-t flex-1">
<span className="p-4">{parse(props.project.description)}</span>
</div>
<div id="notepadFooter" className="bg-gray-100 border-t-2 flex w-full justify-around ">
<span className="p-0">Ln 1, Col 1</span>
<span className="p-0">100%</span>
<span className="p-0">UTF-GR8</span>
</div>
</div>
)
}
export default Notepad
|
// get model
const User = require('../../models/user');
const { onPostSuccess, onPostFailure, onGetSuccess, onGetFailure, onGetNotFound, onUpdateSuccess, onUpdateNotFound, onUpdateFailure, onDeleteFailure, onDeleteNotFound, onDeleteSuccess } = require('../../types/service-return');
const { File, UserImage, UserImageChunk, FileChunk } = require('../../models/file');
module.exports = class UserService {
// constructor
constructor() { }
/**
* @function updateBinaryProperty
* update binary files to object
* @param {Object} res
* @param {Object} updatedRes
*/
updateBinaryProperty = async (res) => {
// find imageChunk and portfolio chunk
const { image, portfolio } = res;
// #1 find image binary
if (image != null) {
// search in files collection
const searchImage = await UserImage.findOne({ filename: image });
if (searchImage != null) {
// search in chunks collection
const searchImageChunk = await UserImageChunk.find({ files_id: searchImage._id });
var buffer = '';
searchImageChunk.map((doc) => buffer += Buffer.from(doc.data, 'binary').toString('base64'));
res['imageChunk'] = buffer;
}
}
// #2 find file binary
if (portfolio != null) {
// search in files collection
const searchFile = await File.findOne({ filename: portfolio });
if (searchFile != null) {
// search in chunks collection
const searchFileChunk = await FileChunk.find({ files_id: searchFile._id });
var buffer = '';
searchFileChunk.map((doc) => buffer += Buffer.from(doc.data, 'binary').toString('base64'));
res['portfolioChunk'] = buffer;
}
}
return res;
}
/**
* functions
* 1) user profile upload -> POST
* 2) user profile read -> GET
* - get by id
* - get all
* 3) user profile update -> PATCH
* - texture : top of the screen
* - file : upload / update
* 4) user profile delete -> DELETE
* - expire user info -> DELETE ALL INFO in _id
* - delete uploaded portfolio file
*/
// 1) POST : new User to application [ SIGN-UP ]
post = async (body) => {
try {
// from data
const {
id, pw, info
} = body;
const {
name, phoneNumber, roles
} = info;
console.log('roles : ' + JSON.stringify(roles))
// create object
const uploadData = await User.create({
id: id,
pw: pw,
info: {
name: name,
phoneNumber: phoneNumber,
roles: roles != null ? JSON.parse(roles) : [],
// set null leftovers
nickname: null,
programs: [],
location: null,
desc: null,
genres: [],
career: null
},
/**
* @param portfolio init null : pdf, docx, ...
* @param image init null : profile image
* @param hasSigned init null : true, if user has signed digital autography
*/
portfolio: null,
image: null,
hasSigned: false
});
// db query
const res = await uploadData.save();
return onPostSuccess(res);
} catch (error) {
console.error(error);
return onPostFailure(error);
}
}
// 2-1) GET : read by id
readOne = async (id) => {
try {
let res = await User.findById(id);
if (!res) return onGetNotFound;
else {
res = await this.updateBinaryProperty(res);
return onGetSuccess(res);
}
} catch (error) {
console.error(error);
return onGetFailure(error);
}
}
// 2-2) GET : read all users
readAll = async () => {
try {
// need to send chunks to client
let res = await User.find();
const updateRes = async () => {
for (let document of res) {
const { image, portfolio } = document;
// imageChunk update
if (image != null) {
const searchImage = await UserImage.findOne({ filename: image });
if (searchImage != null) {
// get chunks
const searchImageChunk = await UserImageChunk.find({ files_id: searchImage._id });
var buffer = '';
searchImageChunk.map((doc) => buffer += Buffer.from(doc.data, 'binary').toString('base64'));
document['imageChunk'] = buffer;
}
}
if (portfolio != null) {
const searchFile = await File.findOne({ filename: portfolio });
if (searchFile != null) {
// get chunks
const searchFileChunk = await FileChunk.find({ files_id: searchFile._id });
var buffer = '';
searchFileChunk.map((doc) => buffer += Buffer.from(doc.data, 'binary').toString('base64'));
document['portfolioChunk'] = buffer;
}
}
}
}
await updateRes();
if (!res) return onGetNotFound;
return onGetSuccess(res);
} catch (error) {
console.log(error);
return onGetFailure(error);
}
}
/**
* [ NOTICE ]
* all files are recommended to be uploaded up to 256KB
* if the file is over 256KB, more than 1 chunks will be generated
* and need operation to wrap up all chunks from n:0 to n:k
* more codes are in services/article at line 80
* @author seunghwanly - 2021-05-26
*/
// get image from mongodb
getImage = async (filename) => {
try {
// mongoose - model
const findResult = await UserImage.findOne({ filename: filename });
// console.log(findResult)
const { _id } = findResult;
// convert to ObjectID
const res = await UserImageChunk.findOne({ files_id: _id });
if (!res) return onGetNotFound;
return { status: 200, result: res.data };
} catch (error) {
console.log(error);
return onGetFailure(error);
}
}
// get file from mongodb
getFile = async (filename) => {
try {
// mongoose - model
const findResult = await File.findOne({ filename: filename });
const { _id } = findResult;
const res = await FileChunk.findOne({ files_id: _id });
if (!res) return onGetNotFound;
return { status: 200, result: res.data };
} catch (error) {
console.error(error);
return onGetFailure(error);
}
}
// 3-1) PATCH : update only texture
updateText = async (id, body, img) => {
try {
console.log('received data \n>>' + JSON.stringify(body));
// retrieve data
const { info } = body;
// updates are in info
const { roles, genres, nickname, phoneNumber, desc, career, name } = info;
// update data
var updateData;
if (img === undefined || !img) {
updateData = {
info: {
roles: roles,
genres: genres,
nickname: nickname,
phoneNumber: phoneNumber,
desc: desc,
career: career,
name: name
},
};
}
else {
updateData = {
image: img,
info: {
roles: roles,
genres: genres,
nickname: nickname,
phoneNumber: phoneNumber,
desc: desc,
career: career,
name: name
},
};
}
// db query
const res = await User.findByIdAndUpdate(id, updateData, {
new: true
});
if (!res) return onUpdateNotFound;
return onUpdateSuccess(body);
} catch (error) {
console.error(error);
return onUpdateFailure(error);
}
}
// 3-2) PATCH : update only portfolio file
/**
* @function updateFile
* @param {ObjectId} id
* @param {String} filepath
* @returns res
*
* @todo remove previous data then update the files and files-chunks
* #1 @function findById
* find the right user document then retrieve portfolio name
* #2 @function findOne
* find the same filename with retrieved portfolio name
* then find the ObjectId of chunk's file_id
* #3 @function find
* find the same file_id with result._id
* #4 remove the items which are stored already
* - remove from files.collection
* - remove from files-chunks.collction
* #4 @function findByIdAndUpdate
* use 'id' and 'filepath' to update
* cause previous data has removed, now it's available to update with our new data
* @author seunghwanly -06-02-2021
*/
updateFile = async (id, filepath) => {
try {
const res = await User.findByIdAndUpdate(id,
{ portfolio: filepath }, { new: true });
if (!res) return onUpdateNotFound;
return onUpdateSuccess(res);
} catch (error) {
console.error(error);
return onUpdateFailure(error);
}
}
// 4-1) DELETE : user data
deleteUser = async (id) => {
try {
const res = await User.findByIdAndDelete(id);
if (!res) return onDeleteNotFound;
return onDeleteSuccess(res);
} catch (error) {
console.error(error);
return onDeleteFailure(error);
}
}
// 4-2) DELETE : user portfolio
deletePortfolio = async (id) => {
// 1. find the file name
const resUser = await User.findById(id);
// check user id
if (!resUser) return onGetNotFound;
else {
const { portfolio } = resUser;
if (!portfolio) return {
status: 404, result: {
message: "User Portfolio is None"
}
}
// 2. find the file in files.files
const resFile = await File.findOne({ filename: portfolio });
if (!resFile) return {
status: 404, result: {
message: `Cannot find filename with ${portfolio}`
}
};
// 3. find the file in files.chunks
const { _id } = resFile;
const resChunk = await FileChunk.findOneAndDelete({ files_id: _id })
.then((value) => File.findByIdAndDelete(_id))
.catch((err) => onDeleteNotFound);
if (!resChunk) return onDeleteFailure(resChunk);
return onDeleteSuccess(resChunk);
}
}
/** @function signIn check id and pw */
signIn = async (id, pw) => {
let res = await User.findOne({ id: id });
if (!res) return onGetNotFound;
else {
if (res.pw === pw) {
res = await this.updateBinaryProperty(res);
return onGetSuccess(res);
}
else return {
status: 400,
result: 'wrong password'
};
}
}
}
|
const gulp = require('gulp'),
htmlMin = require('gulp-htmlmin'), // 压缩html
cleanCss = require('gulp-clean-css'), // 压缩css
babel = require('gulp-babel'), // 把es6转换为es5
uglify = require('gulp-uglify'), // 压缩js
gulpSequence = require('gulp-sequence'), // 处理异步任务
rev = require('gulp-rev'), // 生成hash值
revCollector = require('gulp-rev-collector'); //
del = require('del'),
gulp.task('default', function (cb) {
gulpSequence(['miniJs', 'miniCss'], 'miniHtml')(cb)
})
gulp.task('miniHtml', function (){
return gulp.src(['rev/**/*.json', 'app/**/*.html'])
.pipe( revCollector({
replaceReved: true,
dirReplacements: {}
}) )
.pipe(htmlMin({
minifyJS: true,//压缩页面JS
minifyCSS: true,//压缩页面CSS
collapseWhitespace: true,//压缩HTML
}))
.pipe(gulp.dest('dist'))
})
gulp.task('miniCss', function() {
return gulp.src('app/**/*.css')
.pipe(cleanCss({compatibility: 'ie8'}))
.pipe(rev())
.pipe(gulp.dest('dist'))
.pipe(rev.manifest())
.pipe(gulp.dest('rev/css'))
})
gulp.task('miniJs', function () {
return gulp.src('app/**/*.js')
.pipe(babel({
presets: ['@babel/env']
}))
.pipe(uglify())
.pipe(rev())
.pipe(gulp.dest('dist'))
.pipe(rev.manifest())
.pipe(gulp.dest('rev/js'))
})
gulp.task('del', function() {
del(['dist']);
})
|
/**
* @author GE40
*/
function register() {
var fname = document.f1.name.value;
var femail = document.f1.email.value;
var fpass=document.f1.pass.value;
var frepass=document.f1.repass.value;
if (name_validate(fname))
{
if (email_validate(femail))
{
if(password_validate(fpass))
{
if(repass_validate(frepass))
{
return true;
}
}
}
}
return false;
}
function name_validate(fname) {
if (fname == "") {
alert("Enter full name");
document.f1.name.focus();
document.f1.name.select();
return false;
} else {
for (var i = 0; i < fname.length; i++) {
if (fname.charAt(i) == " ") {
} else if (!isNaN(fname.charAt(i))) {
alert("Please enter alphabetical character only in name");
document.f1.name.focus();
document.f1.name.select();
return false;
}
}
return true;
}
}
function email_validate(femail) {
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (femail == "") {
alert("Enter email address.");
document.f1.email.focus();
document.f1.email.select();
return false;
}
if (femail.match(mailformat)) {
return true;
} else {
alert("Invalid email address. Type (username@gmail.com)");
document.f1.email.focus();
document.f1.email.select();
return false;
}
}
function password_validate(fpass) {
if (fpass == "") {
alert("Enter password");
document.f1.pass.focus();
document.f1.pass.select();
return false;
}
var count=fpass.length;
if(count>10){
alert("Password field cannot contain more than 10 letters.");
document.f1.pass.focus();
document.f1.pass.select();
return false;
}
else return true;
}
function repass_validate(frepass) {
if (frepass == "") {
alert("Enter confirm password");
document.f1.repass.focus();
document.f1.repass.select();
return false;
}
if(document.f1.pass.value!=document.f1.repass.value)
{
alert("Confirm password doesn't match!");
document.f1.repass.focus();
document.f1.repass.select();
return false;
}
else {
//alert("Successfully registered");
//window.location="index.php";
return true;
}
}
|
import React, { PureComponent, createRef } from 'react'
import { compose, withProps } from "recompose";
import { GoogleMap, withScriptjs, withGoogleMap } from "react-google-maps";
import MapContents from './contents/MapContents';
import { actions as mapActions } from "../../store/map/actions";
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
const apiKey = process.env.REACT_APP_GMAPS_API_KEY;
const gmapsApiUrl = process.env.REACT_APP_GMAPS_URL.replace("|key|", apiKey);
const options = {
fullScreenControl: false
};
class PropertyMap extends PureComponent {
constructor(props) {
super(props);
this.mapRef = createRef();
}
onCenterChanged = () => {
const map = this.mapRef.current;
const center = map.getCenter();
const position = {
lat: center.lat(),
lng: center.lng()
};
this.props.actions.setCenter(position);
};
onZoomChanged = () => {
const map = this.mapRef.current;
const zoom = map.getZoom();
this.props.actions.setZoom(zoom);
}
render() {
const { center, zoom } = this.props;
return (
<GoogleMap
ref={this.mapRef}
center={center}
zoom={zoom}
onCenterChanged={this.onCenterChanged}
onZoomChanged={this.onZoomChanged}
options={options}
>
<MapContents />
</GoogleMap>
);
}
}
const containerStyle = {
display: "flex",
flexGrow: 1, flexShrink: 0, flexBasis: 0
}
const mapState = ({ map }) => map;
const mapDispatch = (dispatch) => ({
actions: bindActionCreators({
setCenter: mapActions.setCenter,
setZoom: mapActions.setZoom
}, dispatch)
});
export default compose(
withProps({
googleMapURL: gmapsApiUrl,
loadingElement: <div>Loading...</div>,
containerElement: <div style={containerStyle} />,
mapElement: <div style={{ flex: "1 1 auto" }} />
}),
withScriptjs,
withGoogleMap,
connect(mapState, mapDispatch)
)(PropertyMap); //(PropertyMap);
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.ui.dialog.DialogText');
/**
* Enumerates text related to dialogs.
* @enum {string}
*/
audioCat.ui.dialog.DialogText = {
ACKNOWLEDGED: 'acknowledged',
CANCEL: 'cancel',
CLOSE: 'close',
GOT_IT: 'got it'
};
|
module.exports = function(){
return function(data, callback){
callback(null, {});
};
};
|
// 1 : tạo thư mục quản lý source code .git
// git init
// 2 : kiểm tra sự thay đổi của folder
// git status
// 3 : lưu trữ sự thay đổi
// git add tenfile (lưu sự thay đổi 1 file)
// git add . (lưu tất cả sự thay đổi)
// 4 : Commit vào repository
// git commit -m "lưu file buoi1"
// git config --global user.name "nguyen van A"
// git config --global user.email "nguyenvana@gmail.com"
// git init
// tạo file mới
// git add . (lưu file mới)
// git commit -m "message" (đóng gói lưu trữ cho phiên làm việc)
// ctrl + ~ : mở terminal nhanh
// 1 - Khai báo biến (dynamic type)
// var a = 5
// re create
// var a = 10
// let b = 10
// let b = 15
// console.log(a)
// 2 : Kiểu dữ liệu
// let a
// console.log(a)
// let a = 5
// console.log(typeof(typeof(a)))
// 3 : object
// mutable , immutable
// const teo = {
// name : "Nguyen Van Teo",
// age : 10
// }
// console.log(teo.name)
// console.log(teo['name'])
// ctrl + /
// 4 : Array
// const arrNames = ["tèo","tí","tủn"]
// console.log(arrNames[0])
// 5 : Toan tu
// let a = 5
// let b = 10
// let c = a++ - b++ - --a - --b + --b - --a + a-- + b--
// 5 - 10 - --a - --b + --b - --a + a-- + b-- (a = 6 , b = 11)
// 6 - 11 - 5 - 10 + --b - --a + a-- + b-- (a = 5 , b = 10)
// 6 - 11 - 5 - 10 + 9 - 4 + a-- + b-- (a = 4 , b = 10)
// 6 - 11 - 5 + 9 (a = 3 , b = 8)
// -2
// console.log(a , b ,c)
// 6 : function
// function showName(name){
// console.log(name)
// return
// }
// function tinhTong(a , b){
// return a + b
// }
// console.log(showName("Teo"))
// const ketQua = tinhTong(5,4)
// console.log(ketQua)
// 7 : Object method
// const teo = {
// name : "Nguyen Van Teo",
// age : 10,
// showInfo : function (){
// console.log("Ten : " + this.name + " , Tuoi : " + this.age)
// }
// }
// teo.showInfo()
// 8 : Phep so sanh
// 6 gia tri bang false : false , null , '' , NaN , undefined , 0
// a > b = 1
// a < b = -1
// a == b = 0
// Toan tu ba ngoi
// bieuthuc ? true : false
// if (a < b){
// console.log(-1)
// }else if (a == b){
// console.log(0)
// }else{
// console.log(1)
// }
// let a = 5
// let b = 5
// a > b ? console.log("A lon hon b") : console.log("a be hon hoac bang b")
// 9 : Vong lap
// const arrNames = ["Teo","Ti","Tun","Tuan"]
// for(let i = 0 ; i < arrNames.length ; i++){
// console.log(arrNames[i])
// }
// viet 1 phuong thuc kiem tra so nguyen to
// So input la so nguyen to , so input khong la so nguyen to
function kiemTraSoNguyenTo(number){
let count = 0
if (number < 2){
console.log("Khong phai so nguyen to")
return
}
for (let i = 2 ; i <= number ; i++ ){
if (number % i == 0){
count++
}
}
if (count == 1){
console.log("La so nguyen to")
}else{
console.log("Khong phai la so nguyen to")
}
}
|
function admin() {
$('.name-circle').remove();
var form = document.getElementById('form');
if (state.form === false) {
state.form = true;
form.removeAttribute('class');
var group1 = document.createElement('li');
group1.setAttribute('class', 'groupName');
group1.setAttribute('onclick', 'loadGroup(0)');
var group2 = document.createElement('li');
group2.setAttribute('class', 'groupName');
group2.setAttribute('onclick', 'loadGroup(1)');
var group3 = document.createElement('li');
group3.setAttribute('class', 'groupName');
group3.setAttribute('onclick', 'loadGroup(2)');
var group4 = document.createElement('li');
group4.setAttribute('class', 'groupName');
group4.setAttribute('onclick', 'loadGroup(3)');
group1.innerHTML = 'group1 - 8 members';
group2.innerHTML = 'group2 - 12 members';
group3.innerHTML = 'group3 - 20 members';
group4.innerHTML = 'group4 - 30members';
form.innerHTML = 'These are Demo Groups';
form.appendChild(group1);
form.appendChild(group2);
form.appendChild(group3);
form.appendChild(group4);
} else {
form.setAttribute('class', 'hideform');
state.form = false;
}
}
function loadGroup(id) {
if (state.form === true) {
form.setAttribute('class', 'hideform');
state.form = false;
users = userGroups[id]
console.log(users);
init();
}
}
|
import React, { Component } from 'react'
import { Container } from 'react-bootstrap'
// import { characterList } from '../../character'
import Search from './search/search'
import Cards from '../cards/cards'
import './home.css'
class Home extends Component {
state = {
list: [],
loader: false
}
componentDidlMount() {
document.title = 'Home page - Marvel'
window.scrollTo(0, 0)
}
updateList = (results) => {
this.setState({list: results})
}
render() {
const {list} = this.state
return (
<section className="home-section">
<Container>
<h1 className="site-title">
COMICS COLLECTION
</h1>
<Search updateList={this.updateList} />
<Cards list={list} />
</Container>
</section>
)
}
}
export default Home
|
class Contract {
constructor(abi, address) {
this.address = address
this.abi = abi
this.options = {
defaultGasPrice: '2000000000'
}
this.instance = new window.web3.eth.Contract(this.abi, this.address, this.options)
}
pay(orderId) {
return this.instance.methods.pay(orderId)
}
}
export default Contract
|
/* eslint-disable require-jsdoc */
// initialize userId/roomId
$('#userId').val('user_' + parseInt(Math.random() * 100000000));
$('#roomId').val('889988');
let rtc = null;
const userId = 'user_' + parseInt(Math.random() * 100000000)
const roomId = '889988'
$(document.body).ready(function(){
$('#startLoop').show()
})
let isStart = false
const start = ()=>{
if (isStart) {
isStart = false
rtc.leave();
rtc.unpublish();
rtc = null;
$('#startLoop').text('开始视频')
return
}
isStart = true
$('#startLoop').text('关闭视频')
const config = genTestUserSig(userId);
rtc = new RtcClient({
userId,
roomId,
sdkAppId: config.sdkAppId,
userSig: config.userSig
});
rtc.join().then(function(){
// rtc.publish();
})
}
$('#startLoop').on('click', function (e) {
e.preventDefault();
start()
})
$(document.body).ready(function(){
// start()
})
// $('#settings').on('click', function (e) {
// e.preventDefault();
// $('#settings').toggleClass('btn-raised');
// $('#setting-collapse').collapse();
// });
|
import { combineReducers } from "redux";
import * as types from "./types";
import * as utils from "./utils";
const initialState = {
product : null,
quantity : 0,
totalProducts : null,
isProductExists : false
}
let newProuduct = [];
let changedItem = {};
let newCartItems = [];
let selectedProducts = [];
let changedSelectedItem = {};
let selectedCartItems = [];
const cartReducer = ( state = initialState, action ) => {
switch( action.type ) {
case types.ADD:
const p = {...action.payload.product, quantity : action.payload.quantity}
const isProductExists = utils.productExistsInCart(newProuduct, p);
if(isProductExists == false) {
newProuduct = newProuduct.concat(p);
}
return {
...state,
product : p,
totalProducts : newProuduct,
isProductExists : isProductExists
};
case types.CHANGE_QUANTITY:
const {selected_quantity, cart, product}= action.payload;
const item = cart.find(e => e.id == product.id);
if(item.id == product.id){
const price = parseFloat(item.price) * parseFloat(selected_quantity)
const updatedItem = {total : price, quantity : selected_quantity}
changedItem = {...item, ...updatedItem};
newCartItems = cart.map(el => el.id == changedItem.id ? {...el, quantity : changedItem.quantity, total : changedItem.total} : el)
}
return {
...state,
totalProducts : newCartItems
}
case types.SELECT_PRODUCTS_TO_REMOVE_FROM_CART:
const {prd, cartProducts}= action.payload;
const prditem = cartProducts.find(el => el.id == prd.id);
const removeItem = {remove : prd.remove}
changedSelectedItem = {...prditem, ...removeItem}
newProuduct = cartProducts.map(el => el.id == changedSelectedItem.id ? {...el, remove : changedSelectedItem.remove} : el)
return {
...state,
totalProducts : newProuduct
}
default: return state;
}
}
const reducer = combineReducers({
cart: cartReducer
});
export default reducer;
|
export const multimedia_data = [
{
id: '010',
title: 'Игры',
options: [
{
id: '011',
title: 'World of..'
},
{
id: '012',
title: 'Angry Bird'
},
{
id: '013',
title: 'Clash of...'
},
{
id: '014',
title: 'Genshin ...'
}
]
},
{
id: '020',
title: 'Фильмы',
options: [
{
id: '021',
title: 'Inception'
},
{
id: '022',
title: 'Pulp Fi...'
},
{
id: '023',
title: 'Dune'
},
{
id: '024',
title: 'Requiem f...'
}
]
},
{
id: '030',
title: 'Книги',
options: [
{
id: '031',
title: 'Посторонний',
bookAuthor: 'Альбер Камю'
},
{
id: '032',
title: 'Идиот',
bookAuthor: 'Достоевский Ф. М.'
},
{
id: '033',
title: 'Старик и море',
bookAuthor: 'Эрнест Хемнгуэй'
},
{
id: '034',
title: 'Превращение',
bookAuthor: 'Франц Кафка'
}
]
},
// {
// id: '040',
// title: 'Музыка',
// options: [
// {
// id: '041',
// title: 'Umbrella',
// musicAuthor: 'Rhianna'
// },
// {
// id: '042',
// title: 'Ain`t no rest for the wicked',
// musicAuthor: 'Cage the Elephant'
// },
// {
// id: '043',
// title: 'Blood Gets Thin',
// musicAuthor: 'Pete & The Pirates'
// },
// {
// id: '044',
// title: 'good 4 u',
// musicAuthor: 'Olivia Rodrigo'
// }
// ]
// }
]
|
/*$.mynamespace ={
row : null,
rowCount : 65536
}; */
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else{
return false;
}
}
//$.get(url[,data][,function()]);
function sendMail(){
$.get("/tripcaddie/forgetPassword.do",{
email : $('#email').val()
},
function(data){
if(data=="fail"){
$('#emailError').text("Email is invalid");
}else{
jQuery('#forgetPasswordPopup').dialog('close');
}
});
}
$(document).ready(function(){
$("#email").focusout(function(){
var email=$('#email').val();
if ($.trim(email).length == 0) {
$('#emailError').text("Email address is not valid");
}
else if (!validateEmail(email)) {
$('#emailError').text("Email address is not valid");
}else{
$('#emailError').text("");
}
});
});
function logout(){
$.get("/tripcaddie/logout.do",function(){
window.location.href="/tripcaddie/";
});
}
function registration(){
//alert('hi');
//$.get("./registration.do");
window.location.href="/tripcaddie/registration.do";
}
function displayLoginForm(){
jQuery("#loginPopup").dialog({
resizable: false,
autoOpen: false,
height:350,
width: 500,
top:-535,
borderWeight:15,
borderColor:'0059ff',
backgroundColor:'FFA500',
left:'50%',
open: function () {
$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").addClass("ui-state-error");
}
/* open:function(){ $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();$('.ui-widget-overlay').remove();} */
});
jQuery('#loginPopup').dialog('open');
$('#forgetPasswordinPopup').click(function(){
jQuery('#loginPopup').dialog('close');
displaypasswordPopup();
});
}
function displaypasswordPopup(){
jQuery("#forgetPasswordPopup").dialog({
resizable: false,
autoOpen: false,
height:450,
width: 500,
top:-535,
borderWeight:15,
borderColor:'0059ff',
backgroundColor:'FFA500',
left:'50%',
open: function () {
$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").addClass("ui-state-error");
}
/* open:function(){ $(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar-close").remove();$('.ui-widget-overlay').remove();} */
});
jQuery('#forgetPasswordPopup').dialog('open');
$('#close').click(function(){
jQuery('#forgetPasswordPopup').dialog('close');
});
}
|
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/acid-test', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
// db.on('error', console.error.bind(console, 'connection error:'));
// db.once('open', function () {
// console.log('Connected...');
// });
const itemSchema = new mongoose.Schema({
name: String,
qty: Number,
});
const Item = mongoose.model('Item', itemSchema);
const newItem = new Item({ name: 'Ruler', qty: 2 });
newItem.save();
|
module.exports = {
async details(req, res){
const { id } = req.params;
const cube = await req.storage.getById(id);
if(cube == undefined){
return res.redirect('/404');
} else {
const ctx = {
title: 'Cube Details',
cube
}
res.render('details', ctx);
}
},
async attach(req, res) {
const { cubeId } = req.params;
const cube = await req.storage.getById(cubeId);
if(cube == undefined){
return res.redirect('/404');
} else {
const accessories = await req.storage.getAccessories(cube.accessories);
const ctx = {
title: 'Cube Details',
cube,
accessories
}
res.render('attachAccessory', ctx);
}
},
async attachPost(req, res) {
const { cubeId } = req.params;
const accessoryId = req.body.accessory;
try{
await req.storage.attachAccessory(cubeId, accessoryId);
} catch (err) {
// Handle error -> res.render with error message
}
res.redirect(`/details/${cubeId}`);
}
}
|
import React, {Component} from 'react';
import { ImageBackground } from 'react-native';
var bg = require('../../img/Logi.jpeg');
export default class Splash extends Component {
constructor(props)
{
super(props);
setTimeout(() =>
{
this.props.navigation.navigate("First")
},1500)
}
render()
{
return(
<ImageBackground
source = {bg}
style = {{height: '100%' , width: '100%',resizeMode: "cover" , backgroundColor: '#000000'}}
>
</ImageBackground>
)
}
}
|
export const MODEL_AUTHORITY = {
userAuthentication: {
name: "-"
}
}
|
var fs = require('fs')
var heroList = require('./heroList.json')
function fetchHeroPortraits() {
for (i=0; i<heroList.heroes.length; i++) {
heroList.heroes[i].portrait = 'http://cdn.dota2.com/apps/dota2/images/heroes/' + heroList.heroes[i].name + '_vert.jpg'
}
}
fetchHeroPortraits()
fs.writeFile('./src/assets/heroListNew.json', JSON.stringify(heroList, null, 2), function (err) {
if (err) return console.log(err);
console.log(JSON.stringify(heroList, null, 2));
console.log('writing to ' + './heroListNew.json');
});
|
jQuery(document).ready(function(){
jQuery('.ingredient:not(:has(.sinStock))').click(function(){
if($(this).hasClass('enabled')){
$(this).removeClass('enabled')
.find('.ingredientValue')
.removeClass('enabled')
.val(0);
$(this).find('.descuento')
.removeClass('enabled');
$(this).find('.descuentoInput')
.val(0)
.change();
if($('.ingredient.enabled').size() <= 0){
$('#buttonAdd').attr('disabled','true');
}
}else{
$(this).addClass('enabled')
.find('.ingredientValue')
.addClass('enabled');
$(this).find('.descuento')
.addClass('enabled');
$('#buttonAdd').removeAttr('disabled');
}
}).find('.ingredientValue').click(function(e) {
return false;
});
jQuery('.ingredient:not(:has(.sinStock))')
.find('.descuento').click(function(e) {
return false;
});
jQuery('.descuentoInput')
.change(function() {
console.log('a');
var pId = $(this).attr('id');
var valueD = $(this).val();
if(valueD>0 && valueD<=100){
$('.ingredient:has(#'+pId+') .precio-ingrediente')
.addClass('tachado');
$('.ingredient:has(#'+pId+') .precio-descuento')
.addClass('enabled')
.text('-$'+(valueD*parseFloat($('.ingredient:has(#'+pId+') .precio-ingrediente').text())/100));
}else{
$('.ingredient:has(#'+pId+') .precio-ingrediente')
.removeClass('tachado');
$('.ingredient:has(#'+pId+') .precio-descuento')
.removeClass('enabled')
.text('');
}
});
});
|
const https = require("https")
const fs = require("fs");
const request = require("request");
function get_html(file) {
return new Promise((resolve, reject) => {
request(`${file}`, (error, response, body) => {
if (error) {
reject(error)
}
else if (response && response.statusCode != 200) {
reject("invalid status code")
}
else {
resolve(body)
}
})
})
}
function download_file(url, filename) {
request.head(url, function(err, res, body){
request(url).pipe(fs.createWriteStream(filename)).on('close', () => {return true;});
})
}
function get_extension_from_url(url) {
let pattern = /.*\.(.*)/g
const match = pattern.exec(url)
if (match) {
return match[1]
} else {
return ""
}
}
async function download_luigis() {
try {
//const luigi_page = "https://www.mariowiki.com/Gallery:Luigi_artwork_and_scans"
const luigi_page = "https://www.mariowiki.com/Gallery:Mario_artwork_and_scans"
let preview_urls = []
let pat1 = /href="(\/File:[^"]*)"/g
let html = await get_html(luigi_page)
let found = pat1.exec(html)
while (found != null) {
preview_urls.push(`https://www.mariowiki.com${found[1]}`)
found = pat1.exec(html)
}
console.log(preview_urls)
let pat2 = /a href="(https:\/\/mario.wiki.gallery\/images\/[^"]*)"/g
let image_urls = preview_urls.map(async(url) => {
try {
console.log(url)
let new_html = await get_html(url)
let found = pat2.exec(new_html)
if (found) {
return found[1];
} else {
return null
}
} catch (err) {
return null
}
})
Promise.all(image_urls).then((val) => {
console.log(val)
let n = 0
for (let file of val) {
if (file != null) {
let extension = get_extension_from_url(file)
console.log(`mario/${n}.${extension}`)
download_file(file, `mario/${n}.${extension}`)
n++
}
}
}).catch((err) => {
(() => {return true;})();
})
} catch (err) {
console.error(err)
}
}
download_luigis()
|
function(e, v, m) {
var name = $(m.e).attr('name');
var $inputs = $('input[name="' + name + '"]');
var m_id = $(m.e).attr('id');
var e_id = $(e).attr('id');
var input_i = 0;
if(e_id.lastIndexOf('_F') > 0) {
input_i = parseInt(e_id.substr(e_id.lastIndexOf('F') + 1, e_id.length));
}
var label_i = $inputs.length - 2;
var $label = $('.MultiFile-label:eq(' + label_i + ')', $('#' + m_id + '_wrap_list'));
if(e.files) {
if(e.files.length > 1) {
$('.MultiFile-title', $label).text(e.files.length + ' images');
}
$.each(e.files, function(index, value) {
if(value) {
if(value.size < 16 * 1024) {
alert('The file "' + value.name + '" is too small. Its size cannot be smaller than ' + (16 * 1024) + ' bytes.');
$('.MultiFile-remove', $label).trigger('click');
}
if(value.size > 3 * (1024 * 1024)) {
alert('The file "' + value.name + '" is too large. Its size cannot exceed ' + (3 * (1024 * 1024)) + ' bytes.');
$('.MultiFile-remove', $label).trigger('click');
}
}
});
var length = 0;
$inputs.each(function() {
length += $(this).get(0).files.length;
});
if(length >= 5) {
setTimeout(function() {
$('#' + m_id + '_F' + (input_i + 1)).attr('disabled', true);
}, 0);
}
if(length > 5) {
alert('Image(s) cannot accept more than 5 files.');
$('.MultiFile-remove', $label).trigger('click');
setTimeout(function() {
$('#' + m_id + '_F' + (input_i + 1)).attr('disabled', false);
}, 0);
}
}
}
|
var $ = require('jquery')
// Función para el menu derecha
$('#trig').on('click', function () {
$('#col1').toggleClass('col-0');
$('#col2').toggleClass('col-md-12');
});
// Función para activar los tooltips
$(document).ready(function() {
$('[data-toggle=tooltip]').tooltip();
});
|
import { get } from '../utils/http';
/**
* 获取通讯录
* @param data
* @param successCb
* @param failCb
*/
export const getAddressBooks = (data, successCb, failCb) => {
get('/api/contact/query', data, successCb, failCb);
}
/**
* 删除通讯录
* @param data
* @param successCb
* @param failCb
*/
export const deletesAddressBookByName = (data, successCb, failCb) => {
get('/api/contact/delete', data, successCb, failCb);
}
/**
* 提交通讯录
* @param data
* @param successCb
* @param failCb
*/
export const postAddressBook = (data, successCb, failCb) => {
get('/api/contact/add', data, successCb, failCb);
}
|
export default {
'edit': 'Modifiez src/page/home.js et enregistrez pour recharger.',
'learn': 'Apprendre React',
'something-went-wrong': 'Oups, quelque chose s\'est mal passé',
'back': 'Retour',
};
|
'use strict';
require('./main.css');
require('./directive.css');
require('./template.css');
require('../../../../../../asset/js/xxt.ui.http.js');
require('../../../../../../asset/js/xxt.ui.page.js');
require('./directive.js');
var ngApp = angular.module('app', ['ngSanitize', 'ui.bootstrap', 'http.ui.xxt', 'page.ui.xxt', 'directive.enroll']);
ngApp.config(['$controllerProvider', '$locationProvider', function ($cp, $locationProvider) {
ngApp.provider = {
controller: $cp.register
};
$locationProvider.html5Mode(true);
}]);
ngApp.factory('Round', ['tmsLocation', 'http2', function (LS, http2) {
var Round = function () {};
Round.prototype.list = function () {
return http2.get(LS.s('round/list', 'scenario', 'template'));
};
return Round;
}]);
ngApp.controller('ctrlRounds', ['$scope', 'Round', function ($scope, Round) {
var facRound, onDataReadyCallbacks;
facRound = new Round();
facRound.list().then(function (rounds) {
$scope.rounds = rounds;
angular.forEach(onDataReadyCallbacks, function (cb) {
cb(rounds);
});
});
onDataReadyCallbacks = [];
$scope.onDataReady = function (callback) {
onDataReadyCallbacks.push(callback);
};
$scope.match = function (matched) {
var i, l, round;
for (i = 0, l = $scope.rounds.length; i < l; i++) {
round = $scope.rounds[i];
if (matched.rid === $scope.rounds[i].rid) {
return $scope.rounds[i];
}
}
return false;
};
}]);
ngApp.factory('Record', ['tmsLocation', 'http2', '$q', function (LS, http2, $q) {
var _ins, _running, Record;
Record = function () {
this.current = {
data: {},
enroll_at: 0
};
};
_running = false;
Record.prototype.get = function (config) {
if (_running) return false;
_running = true;
var _this, url, deferred;
_this = this;
deferred = $q.defer();
url = LS.j('record/get', 'scenario', 'template');
http2.post(url, config).then(function (rsp) {
var record;
record = rsp.data;
_this.current = record;
deferred.resolve(record);
_running = false;
});
return deferred.promise;
};
Record.prototype.list = function (owner, rid) {
var _this, url, deferred;
_this = this;
deferred = $q.defer();
url = LS.j('record/list', 'scenario', 'template');
rid !== undefined && rid.length && (url += '&rid=' + rid);
owner !== undefined && owner.length && (url += '&owner=' + owner);
http2.get(url).then(function (rsp) {
var records, record;
records = rsp.data.records;
if (records && records.length) {
for (var i = 0; i < records.length; i++) {
record = records[i];
record.data.member && (record.data.member = JSON.parse(record.data.member));
}
}
deferred.resolve(records);
});
return deferred.promise;
};
return {
ins: function () {
if (_ins) {
return _ins;
}
_ins = new Record();
return _ins;
}
};
}]);
ngApp.controller('ctrlRecord', ['$scope', 'Record', function ($scope, Record) {
var facRecord = Record.ins(),
schemas = [];
facRecord.get($scope.CustomConfig);
$scope.Record = facRecord;
if ($scope.page.dataSchemas) {
$scope.page.dataSchemas.forEach(function (oSchemaWrap) {
schemas.push(oSchemaWrap.schema);
});
}
$scope.value2Label = function (key) {
var val, i, j, s, aVal, aLab = [];
if (schemas && facRecord.current.data) {
val = facRecord.current.data[key];
if (val === undefined) return '';
for (i = 0, j = schemas.length; i < j; i++) {
s = schemas[i];
if (schemas[i].id === key) {
s = schemas[i];
break;
}
}
if (s && s.ops && s.ops.length) {
aVal = val.split(',');
for (i = 0, j = s.ops.length; i < j; i++) {
aVal.indexOf(s.ops[i].v) !== -1 && aLab.push(s.ops[i].l);
}
if (aLab.length) return aLab.join(',');
}
return val;
} else {
return '';
}
};
}]);
ngApp.controller('ctrlRecords', ['$scope', 'tmsLocation', 'Record', function ($scope, LS, Record) {
var facRecord, options, fnFetch, rid;
rid = LS.s().rid;
facRecord = Record.ins(LS.s().scenario, LS.s().template);
options = {
owner: 'A',
rid: rid
};
fnFetch = function () {
facRecord.list(options.owner, options.rid).then(function (records) {
$scope.records = records;
});
};
$scope.$on('xxt.app.enroll.filter.rounds', function (event, data) {
options.rid = data[0].rid;
fnFetch();
});
$scope.$on('xxt.app.enroll.filter.owner', function (event, data) {
options.owner = data[0].id;
fnFetch();
});
$scope.fetch = fnFetch;
$scope.options = options;
}]);
ngApp.controller('ctrlOwnerOptions', ['$scope', function ($scope) {
$scope.owners = {
'A': {
id: 'A',
label: '全部'
},
'U': {
id: 'U',
label: '我的'
}
};
$scope.match = function (owner) {
return $scope.owners[owner.id];
}
}]);
ngApp.controller('ctrlOrderbyOptions', ['$scope', function ($scope) {
$scope.orderbys = {
time: {
id: 'time',
label: '最新'
},
score: {
id: 'score',
label: '点赞'
},
remark: {
id: 'remark',
label: '留言'
}
};
}]);
ngApp.controller('ctrlMain', ['$scope', 'tmsLocation', 'http2', '$timeout', '$q', function ($scope, LS, http2, $timeout, $q) {
function renew(page, config) {
$scope.CustomConfig = config;
http2.post(LS.j('pageGet', 'scenario', 'template') + '&page=' + page, config).then(function (rsp) {
var params;
params = rsp.data;
$scope.params = params;
$scope.page = params.page;
$scope.User = params.user;
(function setPage(page) {
if (page.ext_css && page.ext_css.length) {
angular.forEach(page.ext_css, function (css) {
var link, head;
link = document.createElement('link');
link.href = css.url;
link.rel = 'stylesheet';
head = document.querySelector('head');
head.appendChild(link);
});
}
if (page.ext_js && page.ext_js.length) {
angular.forEach(page.ext_js, function (js) {
$.getScript(js.url);
});
}
if (page.js && page.js.length) {
(function dynamicjs() {
eval(page.js);
})();
}
})(params.page);
});
};
window.renew = function (page, config) {
var phase;
phase = $scope.$root.$$phase;
if (phase === '$digest' || phase === '$apply') {
renew(page, config);
} else {
$scope.$apply(function () {
renew(page, config);
});
}
};
$scope.data = {
member: {}
};
$scope.CustomConfig = {};
$scope.gotoPage = function (event, page, ek, rid, newRecord) {};
$scope.addRecord = function (event) {};
$scope.editRecord = function (event, page) {};
$scope.likeRecord = function (event) {};
$scope.remarkRecord = function (event) {};
$scope.openMatter = function (id, type) {};
$scope.$on('xxt.app.enroll.filter.rounds', function (event, data) {
if (event.targetScope !== $scope) {
$scope.$broadcast('xxt.app.enroll.filter.rounds', data);
}
});
$scope.$on('xxt.app.enroll.filter.owner', function (event, data) {
if (event.targetScope !== $scope) {
$scope.$broadcast('xxt.app.enroll.filter.owner', data);
}
});
window.renew(LS.s().page, {});
}]);
|
const router = require('koa-router')()
router.prefix('/limits')
const limitModel=require('../model/limitModel')
const common=require('../model/common.js')
//获取权限
router.get('/',async ctx=>{
await common.check(ctx,limitModel)
})
//新增权限
router.post('/', async ctx=> {
await common.add(ctx,limitModel)
})
//删除权限
router.delete('/',async ctx=>{
await common.del(ctx,limitModel)
})
//修改权限
router.put('/',async ctx=>{
await common.change(ctx,limitModel)
})
module.exports = router
|
const ENDPOINT_LOGOUT = 'http://localhost:3000/api/logout'
const LOGIN_URL = 'http://localhost:3000/api/login'
function logOut(cy){
cy.request({
method: "POST",
url: ENDPOINT_LOGOUT,
headers: {
'X-User-Auth': JSON.stringify(Cypress.env().loginToken),
'Content-Type': 'application/json'
},
}).then((response =>{
expect(response.status).to.eq(200)
}))
}
function logInAndLogOut(cy){
cy.authenticateSession().then((response =>{
cy.request({
method: "POST",
url: ENDPOINT_LOGOUT,
headers: {
'X-User-Auth': JSON.stringify(Cypress.env().loginToken),
'Content-Type': 'application/json'
},
}).then((response =>{
expect(response.status).to.eq(200)
}))
}))
}
function logInWithWrongCredentials(cy, username, password){
cy.request({
method: "POST",
url: LOGIN_URL,
failOnStatusCode: false,
headers: {
'Content-Type': 'application/json'
},
}).then((response =>{
cy.log(response.body)
cy.log(response.status)
expect(response.status).to.eq(401)
const responseAsString = JSON.stringify(response)
cy.log(responseAsString)
}))
}
module.exports = {
logOut,
logInAndLogOut,
logInWithWrongCredentials
}
|
import { Box, Table, Tbody, Td, Th, Thead, Tr } from "@chakra-ui/react";
import { useCallback } from "react";
import SimpleTable from "../../components/SimpleTable";
import getPairList from "../../services/getPairList";
function ChainDetails({ tokenList }) {
const renderEmpty = useCallback(() => tokenList.length == 0 && <Box>No associated token yet.</Box>, [tokenList]);
const renderTable = useCallback(
() =>
tokenList.length > 0 && (
<SimpleTable
header={[
"#",
"Name",
"Liquidity Pair Token Address",
"Token Address",
"Stable Token Address",
"Decentralize Exchange Router Address",
]}
body={tokenList}
renderData={["name", "pair", "token", "stable", "router"]}
/>
),
[tokenList]
);
return (
<Box m={5} overflowX="scroll" p={5}>
{renderEmpty()}
{renderTable()}
</Box>
);
}
export default ChainDetails;
export async function getServerSideProps(context) {
let tokenList = [];
if (context.params.chainId) {
tokenList = await getPairList(context.params.chainId);
}
return {
props: { tokenList },
};
}
|
"use strict";
var win = false;
var attempts = 0;
// using a function contructor form to create an object
function MyApp()
{
var numb1 = document.getElementById("input").value;
var numb2 = document.getElementById("input2").value;
if(parseInt (numb2) == numb1){
attempts++;
alert("YOU WON!!! IT TOOK YOU " + attempts + " attempts");
win = true;
}
if (parseInt (numb2) > numb1){
attempts++;
alert("Try again to high");
}
if (parseInt (numb2) < numb1){
attempts++;
alert("Try again to low");
}
}
var version = "v1.0";
// creating a private function
function setStatus(message)
{
$("#app>footer").text(message);
}
// creating a public function
this.start = function()
{
$("#app>header").append(version);
setStatus("ready");
};
// end MyApp
/* JQuery's shorthand for the document ready event handler
could be written: $(document).ready(handler);
When this page loads, we'll create a global variable
named "app" by attaching it to the "window" object
(part of the BOM - Browser Object Model)
*/
$(function() {
window.app = new MyApp();
window.app.start();
});
|
console.log('Loading event');
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB();
exports.handler = function(event, context) {
var vote = event.vote.toUpperCase().trim();
if (['GOOD', 'OK', 'BAD'].indexOf(vote) >= 0) {
voteHash = vote + "." + Math.floor((Math.random() * 10) + 1).toString();
var tableName = 'VoteApp';
dynamodb.updateItem({
'TableName': tableName,
'Key': { 'VotedFor' : { 'S': voteHash }},
'UpdateExpression': 'add #vote :x',
'ExpressionAttributeNames': {'#vote' : 'Votes'},
'ExpressionAttributeValues': { ':x' : { "N" : "1" } }
}, function(err, data) {
if (err) {
console.log(err);
context.fail(err);
} else {
context.done(null, {
message: "Thank you for casting a vote for " + vote
});
console.log("Vote received for %s", vote);
}
});
} else {
console.log("Invalid vote received (%s)", vote);
context.fail("Invalid vote received");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.