Commit 070c44af authored by 刘松's avatar 刘松

init

parents
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-vue-jsx", "transform-runtime"]
}
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
/build/
/config/
/dist/
/*.js
/server/
/api/
/test/
/src/tests/
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
extends: ['plugin:vue/essential', 'airbnb-base'],
// required to lint *.vue files
plugins: [
'vue'
],
// check if imports actually resolve
settings: {
'import/resolver': {
webpack: {
config: 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
rules: {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
js: 'never',
vue: 'never'
}],
'no-console': 'off',
'no-underscore-dangle': 'off',
'no-only-if': 'off',
'consistent-return': 'off',
// disallow reassignment of function parameters
// disallow parameter object manipulation except for specific exclusions
'no-param-reassign': ['error', {
props: true,
ignorePropertyModificationsFor: [
'state', // for vuex state
'acc', // for reduce accumulators
'e' // for e.returnvalue
]
}],
// allow optionalDependencies
'import/no-extraneous-dependencies': ['error', {
optionalDependencies: ['test/unit/index.js']
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
.DS_Store
node_modules/
/dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {}
}
}
### Health check 'curl /ping'
FROM node:latest
WORKDIR /app
ADD ./package.json /app/
#front end
ADD ./dist /app/dist
#server
ADD ./server.js /app/
#api
ADD ./api /app/api
RUN \
rm /etc/localtime && \
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN npm i --only=production --registry https://registry.npm.taobao.org
ENV SERVICE_PORT=8080
ENV PROJECT_LEVEL=production
ENV MONGO='mongodb://mongo-adpro-ssp-v2-rs-1.localhost:1301/remarketing'
ENV NODE_ENV='production'
EXPOSE 8080
CMD node server.js
image: clean
@echo "building statics"
@npm run build
@echo "building docker image"
@docker build -t reg.yunpro.cn/adpro/remarketing/androidui:latest ./
push:
@docker push reg.yunpro.cn/adpro/remarketing/androidui:latest
clean:
@echo "cleanning"
\ No newline at end of file
# remarketing-ui
> A Vue.js project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
const router = require("express").Router();
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
const crypto = require("crypto");
const axios = require("axios");
const _ = require("lodash");
const moment = require('moment');
const adminID = process.env.NODE_ENV === 'production' ? '5a9f9e6b46da1176a40e1082' : '5ab083b1f6134d82b40d95f2';
let db = {};
const dbpath = process.env.MONGO || "mongodb://localhost:27017/remarketing";
const salt = ",tom";
// TODO ! put into init
MongoClient.connect(dbpath, (err, conn) => {
if (err) return console.log(err);
console.log("#### DB CONNECTED");
db = conn.db("remarketing");
db
.collection("tokenSession")
.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 * 24 });
});
router.post('/job/call',function (req,res) {
const { pubID, slotID, phone, expiration = 60 * 30, unikey } = req.body;
if(!notEmpty(req.body)) res.sendStatus(500);
else {
const host = "http://remarketing-job-yh.yoo.yunpro.cn/bind/" + pubID + '/' + slotID + '?caller=' + phone + '&unikey=' + unikey + '&expiration=' + expiration+ '&test=true';
axios(host, {
method: "GET",
headers: { "Content-Type": "application/json" },
timeout: 30000
})
.then(rep => {
if(rep.data && rep.data.called){
res.send({ status: "ok", called: rep.data.called });
}
else{
res.sendStatus(500);
}
})
.catch(err => {
if (err) return res.sendStatus(500);
});
}
});
router.post('/login',async function (req,res) {
//token phone sessionID
checkSession(req.body, (err, rep) => {
if (err) return res.sendStatus(500);
if (!rep) {
//没有符合的session
return authorize(req.body, (err, rep) => {
if (err) return res.sendStatus(500);
if (!rep) return res.sendStatus(403);
//验证通过
const token = _.merge(rep, { sessionID: genSessionID(rep._id) });
delete token.token;
res.send({ status: "ok", token });
});
} else {
db
.collection("tokens")
.findOne({ _id: OID(rep.tokenID) }, (err, rep) => {
if (err || !rep) return res.sendStatus(500);
const token = _.merge(rep, { sessionID: req.body.sessionID });
delete token.token;
res.send({ status: "ok", token });
});
}
});
});
router.post("/logout",function(req,res) {
let { sessionID } = req.body;
db
.collection('tokenSession')
.remove({ _id: OID(sessionID) }, (err, rep) => {
if (err || !rep) return res.sendStatus(500);
res.send({ status: "ok", rep });
});
});
router.get("/recognitions",function(req,res) {
let { sessionID, limit = 10, skip = 0, date, called = 'false' } = req.query;
checkSession(req.query, async (err, rep) => {
if (err || !rep) return res.sendStatus(500);
else {
const tokenID = rep.tokenID;
let qs = { updateTimestamp: { '$gt': parseInt(moment(date, 'YYYYMMDD').startOf('day').format('x')), '$lte': parseInt(moment(date, 'YYYYMMDD').endOf('day').format('x')) }, tokenID };
_.merge(qs, (called === 'true' ? { called:true } : { called: { $ne: true} }));
const count = await db.collection('numbers').count(qs);
db
.collection('numbers')
.find(qs)
.sort({ updateTimestamp: -1 })
.skip(parseInt(skip * limit))
.limit(parseInt(limit))
.toArray(async (err, rep) => {
if (err) return res.sendStatus(500);
const arrs = await getStars(rep);
const _arrs = await getSlots(arrs);
res.send({ status: "ok", recognitions: _arrs, page: { skip: skip, total: count } })
});
}
});
});
async function getStars(arrays) {
let tasks = [];
arrays.forEach((x) => {
tasks.push(new Promise(async (r,e) => {
const score = x.slotID && x.pubID && x.unikey ? await db
.collection("score")
.findOne({ slotID: x.slotID , pubID: x.pubID, unikey: x.unikey },{ score: 1 }) : { score: -1 };
r(_.merge(x,{ score: (score ? score : { score: -1 }) }));
}));
});
const arrs = await Promise.all(tasks);
return arrs;
}
async function getSlots(arrays) {
let tasks = [];
arrays.forEach((x) => {
tasks.push(new Promise(async (r,e) => {
const slot = x['slotID'] ? await db
.collection("slotTemps")
.findOne({ _id: OID(x.slotID), accountID: OID(x.pubID) },{ slotName: 1 }) : { slotName: '未知' };
r(_.merge(x,{ slot: (slot ? slot : { slotName: '未知' }) }));
}));
});
const arrs = await Promise.all(tasks);
return arrs;
}
function md5token(str) {
const salt = ",tom";
const hash = crypto
.createHash("md5")
.update(str + salt)
.digest()
.toString("hex");
return hash;
}
function checkSession(data, callback) {
if (!data.sessionID) return callback(null);
db
.collection("tokenSession")
.findOne({ sessionID: OID(data.sessionID) }, (err, rep) => {
if (err || !rep) return callback(err, null);
callback(null, rep);
});
}
function exsists(ID) {
return ID !== undefined && ID !== null && ID !== 'all' && ID !== 'undefined';
}
function notEmpty(data) {
let temp = true;
Object.keys(data).forEach((key) => {
temp = temp && data[key] && exsists(data[key]);
})
return temp;
}
function authorize(data, callback) {
db.collection("tokens").findOne({ phone: data.phone }, (err, rep) => {
if (err || !rep) return callback(err, null);
if (md5token(data.token) !== rep.token)
return callback("password wrong", null);
callback(null, rep);
});
}
function genSessionID(tokenID) {
const sessionID = mongodb.ObjectID();
db.collection("tokenSession").insert(
{
createdAt: new Date(),
sessionID,
tokenID
},
(err, rep) => {
if (err) console.log(err);
}
);
return sessionID;
}
function OID(str) {
return typeof str === 'string' ? mongodb.ObjectID(str) : str;
}
module.exports = router;
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
'use strict'
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
const versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version),
versionRequirement: packageConfig.engines.node
}
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
const warnings = []
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (let i = 0; i < warnings.length; i++) {
const warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options)
for (const extension in loaders) {
const loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
exports.createNotifierCallback = () => {
const notifier = require('node-notifier')
return (severity, errors) => {
if (severity !== 'error') return
const error = errors[0]
const filename = error.file && error.file.split('!').pop()
notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
}
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" },
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8081, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>remarketing-ui</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
This diff is collapsed.
{
"name": "remarketing-ui",
"version": "1.0.0",
"description": "A Vue.js project",
"author": "phyllis <liusong@goyoo.com>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"lint": "eslint --ext .js,.vue src",
"build": "node build/build.js",
"api": "npm run build; node server.js"
},
"dependencies": {
"allco": "0.0.16",
"axios": "^0.18.0",
"body-parser": "^1.18.2",
"chart.js": "^2.7.1",
"cookie-parser": "^1.4.3",
"element-ui": "^2.2.0",
"express": "^4.16.2",
"font-awesome": "^4.7.0",
"lodash": "^4.17.5",
"mint-ui": "^2.2.13",
"moment": "^2.21.0",
"mongodb": "^3.0.4",
"vue": "^2.5.2",
"vue-chartjs": "^3.2.1",
"vue-router": "^3.0.1",
"vuex": "^3.0.1"
},
"devDependencies": {
"FontAwesome-webpack": "0.0.2",
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-eslint": "^8.2.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"chalk": "^2.0.1",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.0",
"eslint": "^4.15.0",
"eslint-config-airbnb-base": "^11.3.0",
"eslint-friendly-formatter": "^3.0.0",
"eslint-import-resolver-webpack": "^0.8.3",
"eslint-loader": "^1.7.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-vue": "^4.0.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"font-awesome": "^4.7.0",
"font-awesome-webpack": "0.0.5-beta.2",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^2.30.1",
"node-notifier": "^5.1.2",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-loader": "^13.3.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"webpack": "^3.6.0",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-server": "^2.9.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
var express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
var fs = require('fs');
var http = require('http');
var app = express();
const api = require('./api');
var server = http.Server(app);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(__dirname + '/dist'));
app.use('/api', api);
server.listen(8081, function() {
console.log('server started');
});
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
};
</script>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
}
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #23292e;
display: block;
width: 100%;
height: 100%;
}
</style>
<script>
import { mapGetters, mapActions } from 'vuex';
import { Toast } from 'mint-ui';
import logo from '../assets/toplogo.png';
export default {
computed: {
...mapGetters([
'loginUser',
]),
imgUrl() {
return logo;
},
},
data() {
return {
form: {
phone: '',
token: '',
}
};
},
methods: {
onSubmit() {
const { phone, token } = this.form;
if(/[0-9]{11}$/.test(phone) && /[a-z0-9]{9}$/.test(token)) {
this.login({ phone, token, callback: this.reqCallback });
} else {
Toast({
message: '手机号或授权码格式错误',
position: 'top',
duration: 5000
});
}
},
reqCallback(err) {
const self = this;
if (err) {
return Toast({
message: '手机号或授权码错误',
position: 'top',
duration: 5000
});
}
return this.$router.push({
path: '/',
});
},
...mapActions([
'login',
]),
},
};
</script>
<template>
<div style="padding:100px 0px;">
<img :src="imgUrl" style="width: 150px;margin: 20px auto;display: flex;background:#9E9E9E" />
<div style="magin:50px 0px">
<mt-field label="手机号" placeholder="请输入手机号" type="tel" v-model="form.phone"></mt-field>
<mt-field label="授权码" placeholder="请输入授权码" type="password" v-model="form.token"></mt-field>
<mt-button type="primary" size="large" @click="onSubmit">登录</mt-button>
</div>
</div>
</template>
<style scoped>
.submit{
margin: 0 aut0;
}
</style>
<template>
<div style="height:100%;">
<mt-header title="再营销客户端" fixed>
<mt-button icon="more" slot="right"><i class="fa fa-sign-out fa-lg"></i></mt-button>
</mt-header>
<a :href="target" id="tocal"></a>
<mt-navbar v-model="selected">
<mt-tab-item id="tasks">待拨打</mt-tab-item>
<mt-tab-item id="called">已拨打</mt-tab-item>
</mt-navbar>
<mt-tab-container v-model="selected">
<mt-tab-container-item id="tasks">
<mt-cell title="日期选择">
<span>{{ currentDate }}</span>
<mt-button type="primary" size="small" @click="dateChange">修改</mt-button>
</mt-cell>
<mt-loadmore :top-method="loadTop" :bottom-method="loadBottom" :bottom-all-loaded="allLoaded" ref="loadmore">
<div v-for="item in getConsumers" v-if="getConsumers.length > 0">
<div class="dia-wrap">
<div class="inner">
<h3>{{ "来源:" + item.slot.slotName }}</h3>
<mt-button type="primary" size="small" @click="call(item)">一键拨打</mt-button>
</div>
<div>
<span><pre>{{ "来访时间:" + item.updateTimestamp }}</pre></span>
<span><pre>{{ "营销指数" + item.score.score < 0 ? 0 : item.score.score }}</pre></span>
</div>
</div>
</div>
</mt-loadmore>
</mt-tab-container-item>
<mt-tab-container-item id="called">
</mt-tab-container-item>
</mt-tab-container>
<mt-datetime-picker
ref="picker"
type="time"
startDate="startDate"
endDate="startDate"
v-model="pickerValue"
:confirm="handleConfirm">
</mt-datetime-picker>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';
import moment from 'moment';
import { Toast } from 'mint-ui';
export default {
methods: {
...mapActions({
getRecongitions: 'GET_RECOGNITIONS',
callBegin: 'CALL_BEGIN',
}),
dateChange() {
this.$refs.picker.open();
},
handleConfirm(date) {
const self = this;
if(this.selected == 'tasks') {
this.currentDate = moment(date.getTime()).format('YYYYMMDD');
this.getRecongitions({
refresh: true,
sessionID: localStorage.getItem('__sessionID'),
limit: 1,
skip: 0,
callback(err, data) {
if(err) {
Toast({
message: '加载错误',
position: 'top',
duration: 3000
});
} else {
self.$date.page.skip = data.page.skip;
self.$data.page.total = data.page.total;
}
},
})
} else {
}
},
call(item) {
const { phone } = this.currentUser;
const { slotID, pubID, unikey, expiration = 30*60 } = item;
this.callBegin({
slotID,
pubID,
unikey,
phone,
expiration,
callback(err, data) {
if(err) {
Toast({
message: '拨打失败',
position: 'top',
duration: 3000
});
} else {
self.target = "tada:tel/" + data.called;
setTimeout(() => {
document.querySelector('#tocal').click();
}, 500);
}
}
})
},
loadTop() {
this.getRecongitions({
sessionID: localStorage.getItem('__sessionID'),
limit: 1,
skip: parseInt(data.page.skip) + 1,
callback(err, data) {
if(err) {
Toast({
message: '加载错误',
position: 'top',
duration: 3000
});
} else {
self.$date.page.skip = data.page.skip;
self.$data.page.total = data.page.total;
}
},
})
}
},
computed: {
...mapGetters([
"currentUser",
"getConsumers",
"getCalledConsumers",
"allLoaded",
"allCalledLoaded"
]),
accountShow() {
return this.$store.state.session.currentUser.role === 1;
},
startDate () {
var pre = new Date();
pre.setFullYear(pre.getFullYear()-1);
return pre;
},
endDate () {
var tgo = new Date();
tgo.setFullYear(pre.getFullYear()+1);
return tgo;
}
},
mounted() {
this.getBills({
accountID: this.$store.state.session.currentUser._id,
skip: this.pageCurrent - 1,
limit: this.pageSize,
page: this.page,
});
},
data() {
return {
selected: 'tasks',
currentDate: '20180130',
target: '',
page: {
skip: 0,
total: 0,
}
};
},
};
</script>
\ No newline at end of file
<template>
<el-container>
not found
</el-container>
</template>
<template>
<div class="wap">
<el-card class='todo'>
<p>
功能未开放,敬请期待!
</p>
</el-card>
</div>
</template>
<style>
.wap{
display:flex;
align-items: center;
justify-content: center;
height: 100%;
}
.todo p{
font-size: 14px;
color: #555;
}
</style>
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import 'font-awesome-webpack';
import Vue from 'vue';
import Mint from 'mint-ui';
import 'mint-ui/lib/style.min.css';
import store from './store';
import App from './App';
import router from './router';
Vue.config.productionTip = false;
Vue.use(Mint);
// check session
store.dispatch('login', {
sessionID: localStorage.getItem('__sessionID'),
callback(err) {
if (err) console.log(err);
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!store.state.session.authed) {
next({ path: '/login', query: { redirect: to.fullPath } });
} else {
console.log(to, from);
next();
}
} else {
console.log(to, from);
if (to.path === '/login' && store.state.session.authed) {
next({ path: '/' });
} else {
next(); // 确保一定要调用 next()
}
}
});
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: {
App,
},
template: '<App/>',
});
},
});
import Vue from 'vue';
import Router from 'vue-router';
const Main = () => import('@/components/Main');
const NotFound = () => import('@/components/NotFound');
const Login = () => import('@/components/Login');
const ToDo = () => import('@/components/Todo');
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
component: Main,
meta: { requiresAuth: process.env.NODE_ENV !== 'development' },
children: [
{ name: 'TelJob', path: '/jobs/tel', component: ToDo },
],
},
{
path: '/login',
meta: { requiresAuth: false },
component: Login,
},
{
path: '*',
meta: { requiresAuth: false },
component: NotFound,
},
],
});
import vuex from 'vuex';
import Vue from 'vue';
// import msgTemp from './store/modules/msgTemp';
import session from './store/modules/session';
import numbers from './store/modules/numbers';
import pagination from './store/modules/pagination';
// jobs
import jobs from './store/modules/jobs';
Vue.use(vuex);
export default new vuex.Store({
strict: process.env.NODE_ENV !== 'production',
modules: {
session,
pagination,
numbers,
jobs
},
});
/* eslint-disable */
import moment from 'moment';
const statusArray = ['定时任务时间已过', '审核未通过', '其他错误', '准备发送', '审核中', '审核通过准备发送', '正在发送', '发送完成'];
const types = {
SEND_JOB: 'SEND_JOB',
GET_JOBS: 'GET_JOBS',
JOB_LOADING: 'JOB_LOADING',
};
const state = {
jobs: [],
jobLoading: false,
createdJob: null,
};
const getters = {
getJobs(state) {
return state.jobs;
},
getJobsLoading(state) {
return state.jobLoading;
},
};
const actions = {
[types.SEND_JOB]({ commit }, { templateId, unikeyArray, sendTime, accountID, callback }) {
fetch('/api/job/msg', { //短信任务
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
body: JSON.stringify({ templateId, unikeyArray, sendTime, accountID }),
}).then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.status);
}).then((data) => {
commit(types.SEND_JOB, data || []);
callback(null, data);
}).catch((err) => {
callback(err);
});
},
[types.GET_JOBS]({ commit }, { accountID, skip = 0, limit = 50, callback, page }) {
commit(types.JOB_LOADING, true);
fetch(`/api/jobs?accountID=${accountID}&skip=${skip}&limit=${limit}`).then((res) => { //短信任务获取
if (res.ok) {
return res.json();
}
return Promise.reject(res.status);
}).then((data) => {
console.dir(' in jobs');
if(page) {
page({
total: data.page.total,
current: parseInt(data.page.skip, 10) + 1,
size: data.page.limit,
});
}
data.jobs.map( x => {
const statusInfo = statusArray[ parseInt(x.status) + 2 ];
const time = moment(x.startTimestamp,'x').format('YYYY-MM-DD HH:mm');
return _.merge(x,{ time, statusInfo })
});
commit(types.GET_JOBS, data.jobs);
commit(types.JOB_LOADING, false);
}).catch((err) => {
console.log(err);
commit(types.JOB_LOADING, false);
});
},
};
const mutations = {
[types.SEND_JOB](state, data) {
state.createdJob = data;
},
[types.GET_JOBS](state, data) {
state.jobs = data;
},
[types.JOB_LOADING](state, loading) {
state.jobLoading = loading;
},
};
export default {
state,
getters,
actions,
mutations,
};
\ No newline at end of file
/* eslint-disable */
import * as _ from 'lodash';
import testDatas from '@/tests/consumers';
import moment from 'moment';
const types = {
GET_RECOGNITIONS: 'GET_RECOGNITIONS',
GET_NUMBERS: 'GET_NUMBERS',
NUMBERS_LOADING: 'NUMBERS_LOADING',
UPDATE_PAGINATION: 'UPDATE_PAGINATION',
CALL_BEGIN: 'CALL_BEGIN',
};
const state = {
numbers: [],
calledNumbers: [],
numbersLoading: false,
total: 0,
totalCalled: 0,
};
const getters = {
recognitions(state) {
return formatNumbers(state.numbers).length;
},
getConsumers() {
return state.numbers;
},
getCalledConsumers() {
return state.calledNumbers;
},
getConsumersLoading() {
return state.numbersLoading;
},
allLoaded() {
return state.numbers.length == state.total;
},
allCalledLoaded() {
return state.calledNumbers.length == state.totalCalled;
},
};
const actions = {
[types.GET_RECOGNITIONS]({ commit }, { sessionID, skip = 0, limit = 50, date, refresh = false, called =false, callback }) {
commit(types.NUMBERS_LOADING, true);
fetch(`/api/recognitions?sessionID=${sessionID}&skip=${skip}&limit=${limit}&date=${date}&called=${called}`, {
}).then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.status);
}).then((data) => {
commit(types.NUMBERS_LOADING, false);
commit(types.GET_NUMBERS, _.merge(data,{ refresh,called }));
callback(null,data);
}).catch((err) => {
commit(types.NUMBERS_LOADING, false);
console.log(err);
callback(err);
});
},
[types.CALL_BEGIN]({ commit }, { slotID, pubID, unikey, phone, expiration= 30*60, callback }) {
fetch('/api/job/call', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
timeout: 30000,
body: JSON.stringify({ slotID, pubID, unikey, phone, expiration }),
}).then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.status);
}).then((data) => {
callback(null, data);
}).catch((err) => {
console.log(err);
callback(err);
});
},
};
const mutations = {
[types.GET_NUMBERS](state, data) {
data.recognitions = data.recognitions.map(x => {
x.updateTimestamp = moment(x.updateTimestamp,'x').format('YYYY/MM/DD HH:mm');
if( x.updateCalledTimestamp )
x.updateCalledTimestamp = moment(x.updateCalledTimestamp,'x').format('YYYY/MM/DD HH:mm');
return x;
});
if(data.called) {
state.totalCalled = data.page.total;
state.calledNumbers = (data.refresh ? data.recognitions : data.recognitions.concat(state.calledNumbers));
} else {
state.total = data.page.total;
state.numbers = (data.refresh ? data.recognitions : data.recognitions.concat(state.numbers));
}
},
[types.NUMBERS_LOADING](state, loading) {
state.numbersLoading = loading;
},
};
export default {
state,
getters,
actions,
mutations,
};
/* eslint-disable no-shadow */
const types = {
UPDATE_PAGINATION: 'UPDATE_PAGINATION',
};
const state = {
size: 10,
total: 0,
current: 1,
};
const getters = {
getTotal(state) {
return state.total;
},
getCurrent(state) {
return state.current;
},
getSize(state) {
return state.size;
},
};
const mutations = {
[types.UPDATE_PAGINATION](state, data) {
console.dir(data);
state.size = data.size;
state.total = data.total;
state.current = data.current;
},
};
export default {
state,
getters,
mutations,
};
/* eslint-disable no-shadow */
const types = {
LOGIN: 'LOGIN',
CHANGE_USER: 'CHANGE_USER',
CHECK_SESSION: 'CHECK_SESSION',
DELETE_SESSION: 'DELETE_SESSION',
};
const state = {
authed: false,
currentUser: {
email: 'test',
id: '',
},
loginUser: {
email: '',
id: '',
sessionID: '',
},
};
const getters = {
currentUser() {
return state.currentUser;
},
loginUser() {
return state.loginUser;
},
sessionID() {
return localStorage.getItem('__sessionID');
},
};
const actions = {
login({ commit }, { phone, token, sessionID, callback }) {
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
body: JSON.stringify({ phone, token, sessionID }),
}).then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.status);
}).then((data) => {
commit(types.LOGIN, data);
callback(null, data);
}).catch((err) => {
console.log(err);
callback(err);
});
},
// check session when fresh
session({ commit }, callback) {
fetch('/api/session', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
body: JSON.stringify({ sessionID: getters.sessionID() }),
}).then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.status);
}).then((session) => {
commit(types.CHECK_SESSION, session);
callback(null, session);
}).catch((err) => {
console.log(err);
callback(err);
});
},
delSession({ commit }, callback) {
fetch('/api/logout', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
body: JSON.stringify({ sessionID: getters.sessionID() }),
}).then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.status);
}).then((session) => {
commit(types.DELETE_SESSION);
callback(null, session);
}).catch((err) => {
console.log(err);
callback(err);
});
},
};
const mutations = {
[types.LOGIN](state, data) {
const { token } = data;
state.loginUser = token;
state.currentUser = token;
state.authed = true;
localStorage.setItem('__sessionID', token.sessionID);
},
[types.CHECK_SESSION](state, data) {
const { token } = data;
state.loginUser = token;
state.currentUser = token;
state.authed = true;
localStorage.setItem('__sessionID', token.sessionID);
},
[types.CHANGE_USER](state, { user, data }) {
state.currentUser = user;
localStorage.setItem('__sessionID', data.session.sessionID);
location.href = '/';
},
[types.DELETE_SESSION](state) {
state.loginUser = {};
state.authed = false;
localStorage.removeItem('__sessionID');
location.href = '/';
},
};
export default {
state,
getters,
actions,
mutations,
};
import moment from 'moment';
const datas = [];
for (let i = 0; i < 100; i++) {
let data = {
unikey: 'key--' + i,
refer: 'baidu',
rate: Math.floor(Math.random() * 5),
updateTimestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
};
datas.push(data);
}
export default datas;
\ No newline at end of file
【美赛思国际教育】恭喜您可免费试听美国硕士课程,美国知名导师在线授课,学习工作两不误。戳http://t.cn/RET8G68试听回T退订
\ No newline at end of file
const moment = require('moment');
const axios = require('axios');
const sendTime = moment().add(30, 'm').format('YYYYMMDDHHmm');
const templateId = '5aa9d965bdac228e8062a045';
const unikeyArray = [
'0100168a20aba1f0754be09a14bf9f0a',
'010016e63e80f921eb42c7b2ea7c56ff',
];
axios('http://remarketing-job.yoo.yunpro.cn/createTask', {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
data: { templateId, unikeyArray, sendTime },
})
.then((res) => {
console.log(res.data);
})
.catch((error) => {
if (error) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
})
const _ = require("lodash");
const foo = [
{ uid: 1, unikey: null, time: 1 },
{ uid: 2, unikey: null, time: 2 },
{ uid: 3, unikey: 1, time: 3 },
{ uid: 4, unikey: 1, time: 4 },
{ uid: 5, unikey: 2, time: 5 }
];
function formatNumbers(numbers) {
return _.chain(numbers)
.map(item => {
item.unikey = item.unikey ? item.unikey : item.uid;
return item;
})
.orderBy('time', 'desc')
.uniqBy('unikey')
.value();
}
console.log(formatNumbers(foo));
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment