Browse Source

init

tags/0.0.1
abbycin 10 months ago
commit
0146d9f9a5

+ 20
- 0
.gitignore View File

@@ -0,0 +1,20 @@
.DS_Store
node_modules/
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.exe
*.db
*.log
server.json
mo/
*.zip

+ 345
- 0
build.js View File

@@ -0,0 +1,345 @@
const archiver = require('archiver');
const fs = require('fs');
const process = require('process');
const path = require('path');
const sys = require('child_process');

function rm(dst) {
if(!fs.existsSync(dst)) {
return;
}
let stat = fs.statSync(dst);
if(stat.isDirectory()) {
let stack = [];
let files = [];
let dirs = [dst];
let root = fs.readdirSync(dst);

for (let r of root) {
let p = path.join(dst, r);
let stat = fs.statSync(p);
if (stat.isDirectory()) {
stack.push(p);
dirs.push(p);
} else {
files.push(p);
}
}

while (stack.length > 0) {
let p = stack.pop();
let root = fs.readdirSync(p);
for (let r of root) {
let sp = path.join(p, r);
let stat = fs.statSync(sp);
if (stat.isDirectory()) {
stack.push(sp);
dirs.push(sp);
} else if (stat.isFile()) {
files.push(sp);
}
}
}

for(let f of files) {
fs.unlinkSync(f);
}

dirs.sort((l, r) => {
let ll = l.length;
let rl = r.length;
if (ll < rl) {
return 1;
} else if (ll == rl) {
return 0;
} else {
return -1;
}
});

let end = 0;
for (let i = 0; i < dirs.length; ++i) {
if (dirs[end] != dirs[i]) {
dirs[++end] = dirs[i];
}
}
end += 1;
for (let i = 0; i < end; ++i) {
if (fs.readdirSync(dirs[i]).length == 0) {
fs.rmdirSync(dirs[i]);
}
}
}
}

function mv(src, dst) {
if (!fs.existsSync(src)) {
throw `${src} is not exists`;
}

let lstat = fs.statSync(src);

if (lstat.isFile()) {
if (!fs.existsSync(dst)) {
fs.renameSync(src, dst);
return;
}
if(fs.existsSync(dst)) {
let rstat = fs.statSync(dst);
if(rstat.isFile()) {
fs.unlinkSync(dst);
}
else if(rstat.isDirectory()) {
dst = path.join(dst, path.basename(src));
}
else {
throw `unsupport dst type ${dst}`;
}
}
if(fs.existsSync(dst)) {
fs.unlinkSync(dst);
}
fs.renameSync(src, dst);
return;
}

if (lstat.isDirectory()) {
if(!fs.existsSync(dst)) {
fs.mkdirSync(dst, { recursive: true });
}
let rstat = fs.statSync(dst);
if(rstat.isFile()) {
throw `can't move from directory to a file`;
}
if(!rstat.isDirectory()) {
throw `unsupport dst type ${dst}`;
}

let stack = [];
let files = [];
let root = fs.readdirSync(src);

for(let r of root) {
let p = path.join(src, r);
let stat = fs.statSync(p);
if(stat.isDirectory()) {
stack.push(p);
files.push([p, true]);
} else {
files.push([p, false]);
}
}

while(stack.length > 0) {
let p = stack.pop();
let root = fs.readdirSync(p);
for(let r of root) {
let sp = path.join(p, r);
let stat = fs.statSync(sp);
if(stat.isDirectory()) {
stack.push(sp);
files.push([sp, true]);
} else if(stat.isFile()) {
files.push([sp, false]);
}
}
}

let dirs = [];
src = path.join(path.dirname(src), path.basename(src));
dirs.push(src);
for(let f of files) {
let d = path.join(dst, f[0].substr(src.length));
let b = "";
if(f[1]) {
fs.mkdirSync(d, { recursive: true });
dirs.push(f[0]);
b = f[0];
} else {
try {
fs.mkdirSync(path.dirname(d), { recursive: true });
} catch(e) {
// ignore error
}
fs.renameSync(f[0], d);
b = path.dirname(f[0]);
}
}
dirs.sort((l, r) => {
let ll = l.length;
let rl = r.length;
if(ll < rl) {
return 1;
} else if(ll == rl) {
return 0;
} else {
return -1;
}
});

let end = 0;
for(let i = 0; i < dirs.length; ++i) {
if(dirs[end] != dirs[i]) {
dirs[++end] = dirs[i];
}
}
end += 1;
for(let i = 0; i < end; ++i) {
if(fs.readdirSync(dirs[i]).length == 0) {
fs.rmdirSync(dirs[i]);
}
}
return;
}

throw `unsupport src type ${src}`;
}

function cp(src, dst) {
let copy = (src, dst) => {
let from = fs.createReadStream(src);
let to = fs.createWriteStream(dst);
from.pipe(to);
};

if (!fs.existsSync(src)) {
throw `${src} is not exists`;
}

let lstat = fs.statSync(src);

if (lstat.isFile()) {
if(!fs.existsSync(dst)) {
copy(src, dst);
return;
}
if (fs.existsSync(dst)) {
let rstat = fs.statSync(dst);
if(rstat.isFile()) {
fs.unlinkSync(dst);
}
else if(rstat.isDirectory()) {
dst = path.join(dst, path.basename(src));
}
else {
throw `unsupport dst type ${dst}`
}
}
if(fs.existsSync(dst)) {
fs.unlinkSync(dst);
}
copy(src, dst);
return;
}

if (lstat.isDirectory()) {
if (!fs.existsSync(dst)) {
fs.mkdirSync(dst, { recursive: true });
}
let rstat = fs.statSync(dst);
if (rstat.isFile()) {
throw `can't copy from directory to a file`;
}
if (!rstat.isDirectory()) {
throw `unsupport dst type ${dst}`;
}

let stack = [];
let files = [];
let root = fs.readdirSync(src);

for (let r of root) {
let p = path.join(src, r);
let stat = fs.statSync(p);
if (stat.isDirectory()) {
stack.push(p);
} else if (stat.isFile()) {
files.push(p);
}
}

while (stack.length > 0) {
let p = stack.pop();
let root = fs.readdirSync(p);
for (let r of root) {
let sp = path.join(p, r)
let stat = fs.statSync(sp);
if (stat.isDirectory()) {
stack.push(sp);
} else if (stat.isFile()) {
files.push(sp);
}
}
}

src = path.join(path.dirname(src), path.basename(src));
for (let f of files) {
let d = path.join(dst, f.substr(src.length));
try {
fs.mkdirSync(path.dirname(d), { recursive: true });
} catch (e) {
// ignore error
}
copy(f, d);
}
return;
}

throw `unsuppot src type ${src}`;
}

function build_frontend(dst) {
const oldpath = process.cwd();
let d = path.join(oldpath, dst);
process.chdir('web');
sys.execSync('npm install');
sys.execSync('npm run build');
cp('dist', path.join(d, 'dist'));
process.chdir(oldpath);
}

function build_backend(dst) {
const oldpath = process.cwd();
let d = path.join(oldpath, dst);
process.chdir('server');
sys.execSync('go build');
if(process.platform === 'win32') {
mv('server.exe', d);
} else {
mv('server', d);
}
cp('server.toml', d);
process.chdir(oldpath);
}

function build() {
let d = new Date();
let base = `salary-${process.platform}-${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}-${d.getTime()}`;
let dir = 'salary';
let dst = path.join(dir, base)
if(fs.existsSync(dir)) {
rm(dir);
}
fs.mkdirSync(dst, { recursive: true });
build_frontend(dst);
build_backend(dst);

let out = `${base}.zip`;
if(fs.existsSync(out)) {
fs.unlinkSync(out);
}
let zip = fs.createWriteStream(out);
let archive = archiver('zip', {
zlib: {level: 9}
});
zip.on('close', () => {
rm(dir);
});
archive.pipe(zip);
archive.on('error', err => { throw err; });
archive.directory(dst, base);
archive.finalize();
}

build();

+ 61
- 0
server/conf/config.go View File

@@ -0,0 +1,61 @@
package conf

import (
"github.com/BurntSushi/toml"
"path/filepath"
"server/logging"
"strings"
"time"
)

type Logging struct {
FileName string `toml:"filename"`
RollSize int64 `toml:"roll_size"`
RollInterval time.Duration `toml:"roll_interval"`
Level string `toml:"level"`
PanicOnFatal bool `toml:"panic_on_fatal"`
}

type Config struct {
Addr string `toml:"address"`
DBFile string `toml:"db_file"`
Web string `toml:"web"`
Logging Logging `toml:"logging"`
}

func Init(cfg string) *Config {
var res Config
_, err := toml.DecodeFile(cfg, &res)
if err != nil {
logging.Fatal("can't decode configuration file: %s", err)
}
return &res
}

func (c *Config) str2Level() int {
l := strings.ToLower(c.Logging.Level)
switch l {
case "info":
return logging.INFO
case "debug":
return logging.DEBUG
case "warn":
return logging.WARN
case "error":
return logging.ERROR
case "fatal":
return logging.FATAL
default:
panic("invalid level " + c.Logging.Level)
}
}

func (c *Config) GetLogger(cwd string) *logging.Logger {
return &logging.Logger{
RollSize: c.Logging.RollSize * (1 << 20),
RollInterval: c.Logging.RollInterval * time.Hour,
FileName: filepath.Join(cwd, c.Logging.FileName),
Level: c.str2Level(),
PanicOnFatal: c.Logging.PanicOnFatal,
}
}

+ 11
- 0
server/go.mod View File

@@ -0,0 +1,11 @@
module server

go 1.13

require (
github.com/BurntSushi/toml v0.3.1
github.com/gin-contrib/cors v1.3.1
github.com/gin-gonic/gin v1.6.3
github.com/kardianos/service v1.0.0
github.com/mattn/go-sqlite3 v2.0.3+incompatible
)

+ 65
- 0
server/go.sum View File

@@ -0,0 +1,65 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gin-contrib/cors v1.3.1 h1:doAsuITavI4IOcd0Y19U4B+O0dNWihRyX//nn4sEmgA=
github.com/gin-contrib/cors v1.3.1/go.mod h1:jjEJ4268OPZUcU7k9Pm653S7lXUGcqMADzFA61xsmDk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do=
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM=
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY=
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/kardianos/service v1.0.0 h1:HgQS3mFfOlyntWX8Oke98JcJLqt1DBcHR4kxShpYef0=
github.com/kardianos/service v1.0.0/go.mod h1:8CzDhVuCuugtsHyZoTvsOBuvonN/UDBvl0kH+BUxvbo=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw=
github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U=
github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE=
gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

+ 167
- 0
server/logging/logging.go View File

@@ -0,0 +1,167 @@
/***********************************************
File Name: logging
Author: Abby Cin
Mail: abbytsing@gmail.com
Created Time: 10/31/19 7:41 AM
***********************************************/

package logging

import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
)

const (
DEBUG = 0
INFO = 1
WARN = 2
ERROR = 3
FATAL = 4
)

type Logger struct {
FileName string `json:"filename" toml:"filename"`
RollSize int64 `json:"roll_size" toml:"roll_size"`
RollInterval time.Duration `json:"roll_interval" toml:"roll_interval"`
Level int `json:"level" toml:"level"`
PanicOnFatal bool `json:"panic_on_fatal" toml:"panic_on_fatal"`

genName func() string
format func(int, string, int) string
dir string
idx int
roll bool
level [5]string
sizeCounter int64
timePoint time.Time
file *os.File
mtx sync.Mutex
}

var backend = Logger{}

func init() {
backend.roll = false
backend.PanicOnFatal = true
backend.level = [5]string{"DEBUG", "INFO ", "WARN ", "ERROR", "FATAL"}
backend.format = func(level int, file string, line int) string {
// fuck golang
return fmt.Sprintf("[%s %s] %s:%d ", time.Now().Format("2006-01-02 15:04:05.000"), backend.level[level], file, line)
}
backend.file = os.Stdout
}

func Init(cfg *Logger) error {
backend.roll = true
backend.RollSize = cfg.RollSize
backend.RollInterval = cfg.RollInterval
backend.Level = cfg.Level
backend.PanicOnFatal = cfg.PanicOnFatal

backend.dir = filepath.Dir(cfg.FileName)
backend.FileName = filepath.Base(strings.TrimSuffix(cfg.FileName, filepath.Ext(cfg.FileName)))
backend.sizeCounter = 0
backend.timePoint = time.Now()
backend.idx = 0

prefix := fmt.Sprintf("%s-%s", backend.FileName, time.Now().Format("20060102"))
abs, err := filepath.Abs(backend.dir)
if err != nil {
return err;
}

if _, err := os.Stat(abs); os.IsNotExist(err) {
os.Mkdir(abs, 0755)
}

entries, err := ioutil.ReadDir(abs)
if err != nil {
return err
}

// /path/to/prefix-20190617-pid-1.log
for _, e := range entries {
if strings.HasPrefix(e.Name(), prefix) {
tmp, err := strconv.Atoi(strings.Split(strings.TrimSuffix(e.Name(), filepath.Ext(e.Name())), "-")[3])
if err != nil {
return err
}
if backend.idx < tmp {
backend.idx = tmp
}
}
}

backend.genName = func() string {
cur := time.Now().Format("20060102")
backend.idx += 1
return fmt.Sprintf("%s/%s-%s-%d-%d.log", backend.dir, backend.FileName, cur, os.Getpid(), backend.idx)
}

backend.file, err = os.Create(backend.genName())

return err
}

func (b *Logger) dispatch(level int, f string, args ...interface{}) {
b.mtx.Lock()
defer b.mtx.Unlock()
if level < b.Level {
return
}
if b.roll && (b.sizeCounter > b.RollSize || time.Since(b.timePoint) > b.RollInterval) {
b.sizeCounter = 0
b.timePoint = time.Now()
Release()
b.file, _ = os.Create(b.genName())
}

_, file, line, _ := runtime.Caller(2) // golang is horrible
data := []byte(b.format(level, path.Base(file), line) + fmt.Sprintf(f, args...))
n, err := b.file.Write(append(data, '\n'))
if err != nil {
panic(err)
}
b.sizeCounter += int64(n)
}

func Release() {
_ = backend.file.Sync()
_ = backend.file.Close()
}

func Sync() error {
return backend.file.Sync()
}

func Info(f string, args ...interface{}) {
backend.dispatch(INFO, f, args...)
}

func Debug(f string, args ...interface{}) {
backend.dispatch(DEBUG, f, args...)
}

func Warn(f string, args ...interface{}) {
backend.dispatch(WARN, f, args...)
}

func Error(f string, args ...interface{}) {
backend.dispatch(ERROR, f, args...)
}

func Fatal(f string, args ...interface{}) {
backend.dispatch(FATAL, f, args...)
if backend.PanicOnFatal {
panic(fmt.Sprintf(f, args...))
}
}

+ 103
- 0
server/main.go View File

@@ -0,0 +1,103 @@
package main

import (
"database/sql"
"flag"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
srv "github.com/kardianos/service"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
"path/filepath"
"server/conf"
"server/logging"
"server/service"
)

var logger srv.Logger

type Program struct {
}

func (p *Program) run() {
exe, err := os.Executable()
if err != nil {
os.Exit(1)
}
cwd := filepath.Dir(exe)
config := filepath.Join(cwd, "server.toml")
cfg := conf.Init(config)
gin.SetMode(gin.ReleaseMode)
r := gin.Default()

if err := logging.Init(cfg.GetLogger(cwd)); err != nil {
log.Panic(err)
}

db, err := sql.Open("sqlite3", filepath.Join(cwd, cfg.DBFile))
if err != nil {
logging.Error("%s", err)
log.Panic(err)
}
s := service.NewService(db)

r.Use(cors.Default())
r.POST("/api/cal", s.ApiCalculate)
r.POST("/api/update", s.ApiUpdate)
r.POST("/api/new", s.ApiNew)
r.POST("/api/init", s.ApiIint)
r.POST("/api/delete", s.ApiDelete)

r.Static("/static", filepath.Join(cwd, cfg.Web, "static"))
r.StaticFile("/", filepath.Join(cwd, cfg.Web, "index.html"))
_ = r.Run(cfg.Addr)
}

func (p *Program) Start(s srv.Service) error {
logger.Info("start staring")
go p.run()
return nil
}

func (p *Program) Run() {
logger.Info("start running")
}

func (p *Program) Stop(s srv.Service) error {
logger.Info("stop running")
return nil
}

func main() {
srvFlag := flag.String("service", "", "control the service")
flag.Parse()

srvConf := &srv.Config{
Name: "salary",
DisplayName: "salary service",
Description: "record and calculate salary",
}

p := &Program{}
s, err := srv.New(p, srvConf)
if err != nil {
log.Fatal(err)
}
logger, err = s.Logger(nil)
if err != nil {
log.Fatal(err)
}

if len(*srvFlag) != 0 {
err := srv.Control(s, *srvFlag)
if err != nil {
log.Fatalf("error: %v\nvalid actions: %q\n", err, srv.ControlAction)
}
return
}
err = s.Run()
if err != nil {
logger.Error(err)
}
}

+ 10
- 0
server/server.toml View File

@@ -0,0 +1,10 @@
address = ":8888"
db_file = "salary.db"
web = "dist"

[logging]
filename = "log/backend"
roll_size = 10 # MB
roll_interval = 720 # hour
level = "info"
panic_on_fatal = true

+ 258
- 0
server/service/service.go View File

@@ -0,0 +1,258 @@
package service

import (
"database/sql"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"server/logging"
)

func newError(c *gin.Context, code int, msg string) {
c.JSON(http.StatusOK, gin.H {
"code": code,
"msg": msg,
})
}

func newData(c *gin.Context, code int, data interface{}, msg string) {
c.JSON(http.StatusOK, gin.H {
"code": code,
"data": data,
"msg": msg,
})
}

type Service struct {
db *sql.DB
}

type Date struct {
From string `json:"from"`
To string `json:"to"`
Descending bool `json:"descending"`
}

type DbData struct {
Date string `json:"date"`
WorkingHour float64 `json:"working_hour,string"`
Money float64 `json:"money,string"` // fuck golang, you must use this ugly stuff
Remark string `json:"remark"`
}

func NewService(db *sql.DB) *Service {
_, err := db.Exec(`create table if not exists salary(date date unique, working_hour number, money number, remark text)`)
if err != nil {
logging.Fatal("create table: %s", err)
}
res := &Service{db:db}
return res
}

func (s *Service) ApiIint(c *gin.Context) {
var date Date
err := c.BindJSON(&date)
if err != nil {
logging.Error("ApiIinit bindjson: %s", err)
newError(c, -1, err.Error())
return
}

order := "asc"
if date.Descending {
order = "desc"
}
sql := fmt.Sprintf("select * from salary where date >= ? and date <= ? order by date %s", order)
stmt, err := s.db.Prepare(sql)
if err != nil {
logging.Error("ApiInit prepare: %s", err)
newError(c, -1, err.Error())
return
}
defer stmt.Close()

rows, err := stmt.Query(date.From, date.To)
if err != nil {
logging.Error("ApiInit query: %s", err)
newError(c, -1, err.Error())
return
}

res := make([]DbData, 0)

for rows.Next() {
var l DbData
err = rows.Scan(&l.Date, &l.WorkingHour, &l.Money, &l.Remark)
if err != nil {
logging.Error("ApiInit scan: %s", err)
newError(c, -1, err.Error())
return
}
res = append(res, l)
}
newData(c, 0, res, "ok")
}

func (s *Service) ApiNew(c *gin.Context) {
var data DbData
err := c.BindJSON(&data)
if err != nil {
logging.Error("ApiNew bindjson: %s", err)
newError(c, -1, err.Error())
return
}
stmt, err := s.db.Prepare("insert into salary values(?, ?, ?, ?)")
if err != nil {
logging.Error("ApiNew prepare: %s", err)
newError(c, -1, err.Error())
return
}
defer stmt.Close()

tx, err := s.db.Begin()
if err != nil {
logging.Error("ApiNew begin: %s", err)
newError(c, -1, err.Error())
return
}
_, err = tx.Stmt(stmt).Exec(data.Date, data.WorkingHour, data.Money, data.Remark)
if err != nil {
tx.Rollback()
logging.Error("ApiNew exec: %s", err)
newError(c, -1, err.Error())
return
}
err = tx.Commit()
if err != nil {
logging.Error("ApiNew commit: %s", err)
newError(c, -1, err.Error())
return
}
newError(c, 0, "ok")
}

func (s *Service) ApiCalculate(c *gin.Context) {
var date Date
err := c.BindJSON(&date)
if err != nil {
logging.Error("ApiCalculate bindjson: %s", err)
newError(c, -1, err.Error())
return
}
stmt, err := s.db.Prepare("select money from salary where date >= ? and date <= ?")
if err != nil {
logging.Error("ApiCalculate prepare: %s", err)
newError(c, -1, err.Error())
return
}
defer stmt.Close()

rows, err := stmt.Query(date.From, date.To)
if err != nil {
logging.Error("ApiCalculate query: %s", err)
newError(c, -1, err.Error())
return
}

var res float32 = 0
for rows.Next() {
var tmp float32 = 0
err = rows.Scan(&tmp)
if err != nil {
logging.Error("ApiCalculate scan: %s", err)
newError(c, -1, err.Error())
return
}
res += tmp
}
newData(c, 0, res, "ok")
}

func (s *Service) ApiUpdate(c *gin.Context) {
var data DbData
err := c.BindJSON(&data)
if err != nil {
logging.Error("ApiUpdate bindjson: %s", err)
newError(c, -1, err.Error())
return
}
stmt, err := s.db.Prepare("update salary set working_hour = ?, money = ?, remark = ? where date = ?")
if err != nil {
logging.Error("ApiUpdate prepare: %s", err)
newError(c, -1, err.Error())
return
}
defer stmt.Close()

tx, err := s.db.Begin()
if err != nil {
logging.Error("ApiUpdate begin: %s", err)
newError(c, -1, err.Error())
return
}
_, err = tx.Stmt(stmt).Exec(data.WorkingHour, data.Money, data.Remark, data.Date)
if err != nil {
tx.Rollback()
logging.Error("ApiUpdate exec: %s", err)
newError(c, -1, err.Error())
return
}
err = tx.Commit()
if err != nil {
logging.Error("ApiUpdate commit: %s", err)
newError(c, -1, err.Error())
return
}
newError(c, 0, "ok")
}

func (s *Service) ApiDelete(c *gin.Context) {
var data DbData
err := c.BindJSON(&data)
if err != nil {
logging.Error("ApiDelete bindjson: %s", err)
newError(c, -1, err.Error())
return
}

stmt, err := s.db.Prepare("delete from salary where date = ? and working_hour = ? and money = ?")
if err != nil {
logging.Error("ApiDelete prepare: %s", err)
newError(c, -1, err.Error())
return
}
defer stmt.Close()

tx, err := s.db.Begin()
if err != nil {
logging.Error("ApiDelete begin: %s", err)
newError(c, -1, err.Error())
return
}

println(data.Date)
r, err := tx.Stmt(stmt).Exec(data.Date, data.WorkingHour, data.Money)
if err != nil {
tx.Rollback()
logging.Error("ApiDelete exec: %s", err)
newError(c, -1, err.Error())
return
}
n, err := r.RowsAffected()
if n == 0 || err !=nil {
logging.Error("delete not success: %s", err);
if err != nil {
newError(c, -1, err.Error())
} else {
newError(c, -1, "delete not success, maybe condition not satisfied")
}
return
}
err = tx.Commit()
if err != nil {
logging.Error("ApiDelete commit: %s", err)
newError(c, -1, err.Error())
return
}
newError(c, 0, "ok")
}

+ 12
- 0
web/.babelrc View File

@@ -0,0 +1,12 @@
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-vue-jsx", "transform-runtime"]
}

+ 9
- 0
web/.editorconfig View File

@@ -0,0 +1,9 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

+ 14
- 0
web/.gitignore View File

@@ -0,0 +1,14 @@
.DS_Store
node_modules/
/dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln

+ 10
- 0
web/.postcssrc.js View File

@@ -0,0 +1,10 @@
// 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": {}
}
}

+ 21
- 0
web/README.md View File

@@ -0,0 +1,21 @@
# web

> Caculate Salary

## 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).

+ 41
- 0
web/build/build.js View File

@@ -0,0 +1,41 @@
'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'
))
})
})

+ 54
- 0
web/build/check-versions.js View File

@@ -0,0 +1,54 @@
'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)
}
}

BIN
web/build/logo.png View File


+ 101
- 0
web/build/utils.js View File

@@ -0,0 +1,101 @@
'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')
})
}
}

+ 22
- 0
web/build/vue-loader.conf.js View File

@@ -0,0 +1,22 @@
'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'
}
}

+ 82
- 0
web/build/webpack.base.conf.js View File

@@ -0,0 +1,82 @@
'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)
}



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: [
{
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: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
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'
}
}

+ 95
- 0
web/build/webpack.dev.conf.js View File

@@ -0,0 +1,95 @@
'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)
}
})
})

+ 145
- 0
web/build/webpack.prod.conf.js View File

@@ -0,0 +1,145 @@
'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

+ 7
- 0
web/config/dev.env.js View File

@@ -0,0 +1,7 @@
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})

+ 69
- 0
web/config/index.js View File

@@ -0,0 +1,69 @@
'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: 8080, // 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-

/**
* 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
}
}

+ 4
- 0
web/config/prod.env.js View File

@@ -0,0 +1,4 @@
'use strict'
module.exports = {
NODE_ENV: '"production"'
}

+ 12
- 0
web/index.html View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>web</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

+ 12028
- 0
web/package-lock.json
File diff suppressed because it is too large
View File


+ 64
- 0
web/package.json View File

@@ -0,0 +1,64 @@
{
"name": "salary",
"version": "1.0.0",
"description": "Calculate Salary",
"author": "abbycin <abbytsing@gmail.com>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"build": "node build/build.js"
},
"dependencies": {
"ant-design-vue": "^1.6.1",
"moment": "^2.26.0",
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.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",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"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"
]
}

+ 17
- 0
web/src/App.vue View File

@@ -0,0 +1,17 @@
<template>
<div id="app">
<router-view/>
</div>
</template>

<script>
export default {
name: 'App'
}
</script>

<style scoped>
#app {
margin-top: 3%;
}
</style>

BIN
web/src/assets/logo.png View File


+ 235
- 0
web/src/components/main.vue View File

@@ -0,0 +1,235 @@
<template>
<div id="main">
<a-list item-layout="horizontal" bordered :data-source="data">
<a-list-item slot="renderItem" slot-scope="item, index">
<a-row :gutter="{xs: 16, sm: 24, md:48}" align="middle" justify="center" type="flex">
<a-col :span="4">
<a-date-picker
:value="moment(item.date, dateFormat)"
@change="(d, ds) => { changeDate(d, ds, index); }"
/>
</a-col>
<a-col :span="5">
<a-input
addon-before="工时"
v-model="item.working_hour"
@change="validateNumber(index)"
suffix="小时"
/>
</a-col>
<a-col :span="5">
<a-input
addon-before="工钱"
v-model="item.money"
@change="validateNumber(index)"
suffix="元"
/>
</a-col>
<a-col :span="5">
<a-textarea v-model="item.remark" placeholder="备注" :rows="1" />
</a-col>
<a-col :span="5">
<a-popconfirm
title="确定要删除?删除后不能恢复的!"
ok-text="确定"
cancel-text="取消"
@confirm="removeRow(index)"
>
<a-button type="danger" icon="close">删除</a-button>
</a-popconfirm>

<a-button
type="primary"
icon="check"
@click="saveData(index)"
>{{ item.saved === true ? "更新" : "保存" }}</a-button>
</a-col>
</a-row>
</a-list-item>
<div slot="header">
<a-row>
<a-col :span="8">
<a-range-picker
:value="[moment(from, dateFormat), moment(to, dateFormat)]"
@change="changeRange"
/>
</a-col>
<a-col :span="5">
<a-input addon-before="结果" :value="result" suffix="元" />
</a-col>
<a-col :span="3">
<a-button type="primary" icon="cloud-sync" @click="calculateSalary">计算</a-button>
</a-col>
<a-col :span="2">
<a-checkbox v-model="descending">降序</a-checkbox>
</a-col>
<a-col :span="3">
<a-button type="primary" icon="reload" @click="refresh">刷新</a-button>
</a-col>
<a-col :span="3">
<a-button type="primary" icon="plus" @click="newItem">新建</a-button>
</a-col>
</a-row>
</div>
<div slot="footer" style="text-align:center">create by abbytsing@gmail.com</div>
</a-list>
</div>
</template>

<script>
import moment from "moment";
import "moment/locale/zh-cn";
moment.locale("zh-cn");
import { request } from "@/js/req";

let dateFormat = "yyyy-MM-DD";

export default {
name: "Main",
data() {
return {
dateFormat: dateFormat,
data: [],
descending: false,
from: moment()
.startOf("month")
.format(dateFormat),
to: moment()
.endOf("month")
.format(dateFormat),
result: 0
};
},

mounted() {
this.refresh();
},

methods: {
moment,

changeDate(d, ds, index) {
this.data[index].date = ds;
},

changeRange(d, ds) {
this.from = ds[0];
this.to = ds[1];
},

newItem() {
// if(this.data.length > 0 && this.data[0].date == moment().format('yyyy-MM-D')) {
// this.$message.error(`今天(${this.data[0].date})的已经存在了`);
// return;
// }
this.data.unshift({
date: moment().format(dateFormat),
working_hour: null,
money: null,
remark: null,
saved: false
});
},

calculateSalary() {
request(
"POST",
"/api/cal",
{
from: this.from,
to: this.to
},
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
this.result = ok.data;
},
err => {
this.$message.error(`错误: ${err}`);
}
);
},

saveData(index) {
let payload = { ...this.data[index] };
payload.date = moment(payload.date).format(this.dateFormat);
let api = this.data[index].saved === true ? "/api/update" : "/api/new";
// todo: validate duplication
delete payload.saved;
request(
"POST",
api,
payload,
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
this.refresh();
},
err => {
this.$message.error(`错误: ${err}`);
}
);
},

removeRow(index) {
if (this.data[index].saved === false) {
this.data.splice(index, 1);
return;
}
let payload = { ...this.data[index] };
payload.date = moment(payload.date).format(this.dateFormat);
request(
"POST",
"/api/delete",
payload,
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
this.data.splice(index, 1);
},
err => {
this.$message.error(`错误: ${err}`);
}
);
},

validateNumber(index) {
if (
isNaN(this.data[index].working_hour) ||
isNaN(this.data[index].money)
) {
this.$message.error(`工时和工钱必须是数字`);
}
},

refresh() {
request(
"POST",
"/api/init",
{
from: this.from,
to: this.to,
descending: this.descending
},
ok => {
if (ok.code !== 0) {
throw ok.msg;
}
this.data = [];
for (let x of ok.data) {
let tmp = { saved: true, ...x };
tmp.date = moment(tmp.date).format(dateFormat);
this.data.push(tmp);
}
},
err => {
this.$message.error(`错误:${err}`);
}
);
}
}
};
</script>

+ 38
- 0
web/src/js/req.js View File

@@ -0,0 +1,38 @@

function request(method, url, data, ok, err) {
let promise = null;
if(method === "GET") {
promise = fetch(url);
} else if(method === "DELETE") {
promise = fetch(url, {method: method});
} else {
promise = fetch(url, {
method: method,
body: JSON.stringify(data),
headers: {
'content-type': 'application/json'
}
})
}
promise.then(response => {
if(response.ok) {
return response.json();
} else {
response.text().then(txt => {
throw txt;
}).catch(e => {
err(e);
});
return null;
}
}).then(j => {
if(j) {
ok(j);
}
}).catch(e => {
err(e);
});
}

export {request};

+ 19
- 0
web/src/main.js View File

@@ -0,0 +1,19 @@
// 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 Vue from 'vue'
import App from './App'
import router from './router'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css'

Vue.config.productionTip = false

Vue.use(Antd);

/* eslint-disable no-new */
new Vue({
el: '#app',
router,